Java Code Examples for org.springframework.core.convert.converter.Converter

The following examples show how to use org.springframework.core.convert.converter.Converter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void customConversion() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
		@Override
		public String convert(SampleBean source) {
			return "foo bar";
		}
	});
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
	assertMethodInvocation(sample, "simpleString");
}
 
Example 2
Source Project: spring-data   Source File: JodaTimeStringConverters.java    License: Apache License 2.0 6 votes vote down vote up
public static Collection<Converter<?, ?>> getConvertersToRegister() {
	if (!JODA_TIME_IS_PRESENT) {
		return Collections.emptySet();
	}
	final List<Converter<?, ?>> converters = new ArrayList<>();
	converters.add(InstantToStringConverter.INSTANCE);
	converters.add(DateTimeToStringConverter.INSTANCE);
	converters.add(LocalDateToStringConverter.INSTANCE);
	converters.add(LocalDateTimeToStringConverter.INSTANCE);

	converters.add(StringToInstantConverter.INSTANCE);
	converters.add(StringToDateTimeConverter.INSTANCE);
	converters.add(StringToLocalDateConverter.INSTANCE);
	converters.add(StringToLocalDateTimeConverter.INSTANCE);
	return converters;
}
 
Example 3
/**
 * Register the given Converter objects with the given target ConverterRegistry.
 * @param converters the converter objects: implementing {@link Converter},
 * {@link ConverterFactory}, or {@link GenericConverter}
 * @param registry the target registry
 */
public static void registerConverters(Set<?> converters, ConverterRegistry registry) {
	if (converters != null) {
		for (Object converter : converters) {
			if (converter instanceof GenericConverter) {
				registry.addConverter((GenericConverter) converter);
			}
			else if (converter instanceof Converter<?, ?>) {
				registry.addConverter((Converter<?, ?>) converter);
			}
			else if (converter instanceof ConverterFactory<?, ?>) {
				registry.addConverterFactory((ConverterFactory<?, ?>) converter);
			}
			else {
				throw new IllegalArgumentException("Each converter object must implement one of the " +
						"Converter, ConverterFactory, or GenericConverter interfaces");
			}
		}
	}
}
 
Example 4
@Test
public void customConversion() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
		@Override
		public String convert(SampleBean source) {
			return "foo bar";
		}
	});
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
	assertMethodInvocation(sample, "simpleString");
}
 
Example 5
@Override
public JdbcCustomConversions jdbcCustomConversions() {

	return new JdbcCustomConversions(asList(new Converter<Clob, String>() {

		@Nullable
		@Override
		public String convert(Clob clob) {

			try {

				return Math.toIntExact(clob.length()) == 0 //
						? "" //
						: clob.getSubString(1, Math.toIntExact(clob.length()));

			} catch (SQLException e) {
				throw new IllegalStateException("Failed to convert CLOB to String.", e);
			}
		}
	}));
}
 
Example 6
Source Project: data-prep   Source File: Converters.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public Converter<String, JsonNode> jsonNodeConverter() {
    // Don't convert to lambda -> cause issue for Spring to infer source and target types.
    return new Converter<String, JsonNode>() {

        @Override
        public JsonNode convert(String source) {
            if (source.isEmpty()) {
                throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION,
                        new IllegalArgumentException("Source should not be empty"));
            }
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.readTree(source);
            } catch (IOException e) {
                throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
            }
        }
    };
}
 
Example 7
public ConversionService create() {
    if (this.converters.isEmpty() && this.genericConverters.isEmpty()) {
        return ApplicationConversionService.getSharedInstance();
    }
    ApplicationConversionService conversionService = new ApplicationConversionService();
    for (Converter<?, ?> converter : this.converters) {
        conversionService.addConverter(converter);
    }
    for (GenericConverter genericConverter : this.genericConverters) {
        conversionService.addConverter(genericConverter);
    }
    return conversionService;
}
 
Example 8
Source Project: mica   Source File: AsmTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * copy 不做类型转换
 */
public void copy2(User user, Map<String, Object> userMap, Converter var3) {
	Object id = userMap.get("id");
	if (id != null) {
		// 不做类型转换生成的代码
		if (ClassUtil.isAssignableValue(Integer.class, id)) {
			// 此处 需要 asm 做 类型转换 判断
			user.setId((Integer) id);
		}
	}
}
 
Example 9
@Test
public void formatFieldForTypeWithPrinterParserWithCoercion() throws ParseException {
	formattingService.addConverter(new Converter<DateTime, LocalDate>() {
		@Override
		public LocalDate convert(DateTime source) {
			return source.toLocalDate();
		}
	});
	formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat
			.shortDate()), new DateTimeParser(DateTimeFormat.shortDate()));
	String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class);
	assertEquals("10/31/09", formatted);
	LocalDate date = formattingService.convert("10/31/09", LocalDate.class);
	assertEquals(new LocalDate(2009, 10, 31), date);
}
 
Example 10
@Override
@SuppressWarnings("unchecked")
public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
	if (Integer.class == targetType) {
		return (Converter<String, T>) new IntegerConverter();
	}
	else {
		throw new IllegalStateException();
	}
}
 
Example 11
Source Project: ShedLock   Source File: SpringLockConfigurationExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public SpringLockConfigurationExtractor(
    @NonNull Duration defaultLockAtMostFor,
    @NonNull Duration defaultLockAtLeastFor,
    @Nullable StringValueResolver embeddedValueResolver,
    @NonNull Converter<String, Duration> durationConverter
) {
    this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor);
    this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor);
    this.durationConverter = requireNonNull(durationConverter);
    this.embeddedValueResolver = embeddedValueResolver;
}
 
Example 12
Source Project: microservices-springboot   Source File: MongoConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public CustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<>();
    converters.add(new DateToZonedDateTimeConverter());
    converters.add(new ZonedDateTimeToDateConverter());
    return new CustomConversions(converters);
}
 
Example 13
public Converter<Long, Group> getIdToGroupConverter() {
    return new Converter<java.lang.Long,  Group>() {
        public  Group convert(java.lang.Long id) {
        	log.info("converting Long to Group id=" + id + " result" + userService.group_findById(id).toString());
            return userService.group_findById(id);
        }
    };
}
 
Example 14
public Converter<String, Group> getStringToGroupConverter() {
    return new Converter<java.lang.String, Group>() {
        public Group convert(String id) {
        	log.info("converting String to Group id=" + id);
            return getObject().convert(getObject().convert(id, Long.class), Group.class);
        }
    };
}
 
Example 15
public Converter<RegularExpression, String> getRegularExpressionToStringConverter() {
    return new Converter<RegularExpression, java.lang.String>() {
        public String convert(RegularExpression regularExpression) {
        	log.info("converting regularExpressionToString");
        	return new StringBuilder().append(regularExpression.getName()).toString();
        }
    };
}
 
Example 16
public Converter<String, VelocityTemplate> getStringToVelocityTemplateConverter() {
    return new Converter<java.lang.String, VelocityTemplate>() {
        public VelocityTemplate convert(String id) {
        	log.info("converting String to VelocityTemplate id=" + id);
            return getObject().convert(getObject().convert(id, Long.class), VelocityTemplate.class);
        }
    };
}
 
Example 17
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.consul.enabled=true",
            "--spring.cloud.consul.config.enabled=false",
            "--spring.cloud.consul.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--spring.main.allow-bean-definition-overriding=true"
        );

    // TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
    //  is released that supports Spring Boot 2.1 more properly

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ServiceDefinitionToConsulRegistration.class::isInstance)).isTrue();
    } finally {
        context.close();
    }
}
 
Example 18
@Test
public void testConsulServerToServiceDefinition() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.consul.enabled=true",
            "--spring.cloud.consul.config.enabled=false",
            "--spring.cloud.consul.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--spring.main.allow-bean-definition-overriding=true"
        );

    // TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
    //  is released that supports Spring Boot 2.1 more properly

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ConsulServerToServiceDefinition.class::isInstance)).isTrue();
    } finally {
        context.close();
    }
}
 
Example 19
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
    final ZookeeperServer server = new ZookeeperServer(temporaryFolder.newFolder(testName.getMethodName()));

    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.zookeeper.enabled=true",
            "--spring.cloud.zookeeper.connect-string=" + server.connectString(),
            "--spring.cloud.zookeeper.config.enabled=false",
            "--spring.cloud.zookeeper.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false"
        );

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ServiceDefinitionToZookeeperRegistration.class::isInstance)).isTrue();
    } finally {
        // shutdown spring context
        context.close();

        // shutdown zookeeper
        server.shutdown();
    }
}
 
Example 20
@Test
public void convertCannotOptimizeArray() {
	conversionService.addConverter(new Converter<Byte, Byte>() {

		@Override
		public Byte convert(Byte source) {
			return (byte) (source + 1);
		}
	});
	byte[] byteArray = new byte[] { 1, 2, 3 };
	byte[] converted = conversionService.convert(byteArray, byte[].class);
	assertNotSame(byteArray, converted);
	assertTrue(Arrays.equals(new byte[] { 2, 3, 4 }, converted));
}
 
Example 21
public Converter<Long, DataSet> getIdToDataSetConverter() {
    return new Converter<java.lang.Long,  DataSet>() {
        public  DataSet convert(java.lang.Long id) {
        	log.info("converting Long to DataSet id=" + id + " result" + surveySettingsService.velocityTemplate_findById(id).toString());
            return surveySettingsService.dataSet_findById(id);
        }
    };
}
 
Example 22
Source Project: specification-with-projection   Source File: MyResultProcessor.java    License: MIT License 5 votes vote down vote up
public <T> T processResult(@Nullable Object source, Converter<Object, Object> preparingConverter) {

        if (source == null || type.isInstance(source) || !type.isProjecting()) {
            return (T) source;
        }

        Assert.notNull(preparingConverter, "Preparing converter must not be null!");

        ChainingConverter converter = ChainingConverter.of(type.getReturnedType(), preparingConverter).and(this.converter);

        if (source instanceof Slice ) {
            return (T) ((Slice<?>) source).map(converter::convert);
        }

        if (source instanceof Collection ) {

            Collection<?> collection = (Collection<?>) source;
            Collection<Object> target = createCollectionFor(collection);

            for (Object columns : collection) {
                target.add(type.isInstance(columns) ? columns : converter.convert(columns));
            }

            return (T) target;
        }
        return (T) converter.convert(source);
    }
 
Example 23
@Override
public void addFormatters(FormatterRegistry registry) {
	registry.addConverter(new Converter<TestBean, String>() {
		@Override
		public String convert(TestBean source) {
			return "converted";
		}
	});
}
 
Example 24
Source Project: yue-library   Source File: DateTimeFormatConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 日期参数接收转换器,将json字符串转为日期类型
 * 
 * @return MVC LocalDate 参数接收转换器
 */
@Bean
public Converter<String, LocalDate> localDateConvert() {
	return new Converter<String, LocalDate>() {
		@Override
		public LocalDate convert(String source) {
			return LocalDate.parse(source, DateUtils.DATE_FORMATTER);
		}
	};
}
 
Example 25
public Converter<GroupingOperator, String> geGroupingOperatorToStringConverter() {
    return new Converter<GroupingOperator, java.lang.String>() {
        public String convert(GroupingOperator groupingOperator) {
        	log.info("converting QuestionTypeToString");
        	return groupingOperator.getCode();
        }
    };
}
 
Example 26
public Converter<Sector, String> getSectorToStringConverter() {
    return new Converter<Sector, java.lang.String>() {
        public String convert(Sector sector) {
        	log.info("converting SectorToString");
        	return new StringBuilder().append(sector.getName()).toString();
        }
    };
}
 
Example 27
public Converter<String, User> getStringToUserConverter() {
    return new Converter<java.lang.String, User>() {
        public User convert(String id) {
        	log.info("converting String to User id=" + id);
            return getObject().convert(getObject().convert(id, Long.class), User.class);
        }
    };
}
 
Example 28
@Bean
public MongoCustomConversions customConversions() {
    List<Converter<?, ?>> converterList = new ArrayList<>();
    converterList.add(DateToZonedDateTimeConverter.INSTANCE);
    converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
    return new MongoCustomConversions(converterList);
}
 
Example 29
@Test
public void formatFieldForTypeWithPrinterParserWithCoercion() throws ParseException {
	formattingService.addConverter(new Converter<DateTime, LocalDate>() {
		@Override
		public LocalDate convert(DateTime source) {
			return source.toLocalDate();
		}
	});
	formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat
			.shortDate()), new DateTimeParser(DateTimeFormat.shortDate()));
	String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class);
	assertEquals("10/31/09", formatted);
	LocalDate date = formattingService.convert("10/31/09", LocalDate.class);
	assertEquals(new LocalDate(2009, 10, 31), date);
}
 
Example 30
@Bean
public CassandraCustomConversions customConversions() {

	List<Converter<?, ?>> converters = new ArrayList<>();
	converters.add(new PersonWriteConverter());
	converters.add(new PersonReadConverter());
	converters.add(new CustomAddressbookReadConverter());
	converters.add(CurrencyToStringConverter.INSTANCE);
	converters.add(StringToCurrencyConverter.INSTANCE);

	return new CassandraCustomConversions(converters);
}