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

The following examples show how to use org.springframework.core.convert.converter.Converter. 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
Source File: DefaultMessageHandlerMethodFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 File: DefaultMessageHandlerMethodFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #3
Source File: Converters.java    From data-prep with 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 #4
Source File: AggregateConfiguration.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: JodaTimeStringConverters.java    From spring-data with 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 #6
Source File: ConversionServiceFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
public Converter<Long, SurveyTemplate> getIdToSurveyTemplateConverter() {
    return new Converter<java.lang.Long,  SurveyTemplate>() {
        public  SurveyTemplate convert(java.lang.Long id) {
        	log.info("converting Long to SurveyTemplate id=" + id + " result" + surveySettingsService.surveyTemplate_findById(id));
            return surveySettingsService.surveyTemplate_findById(id);
        }
    };
}
 
Example #8
Source File: CloudDatabaseConfiguration.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoCustomConversions customConversions() {
    List<Converter<?, ?>> converterList = new ArrayList<>();
    converterList.add(DateToZonedDateTimeConverter.INSTANCE);
    converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
    return new MongoCustomConversions(converterList);
}
 
Example #9
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
public Converter<String, Survey> getStringToSurveyConverter() {
    return new Converter<java.lang.String, Survey>() {
        public Survey convert(String id) {
        	log.info("converting String to Survey id=" + id);
            return getObject().convert(getObject().convert(id, Long.class), Survey.class);
        }
    };
}
 
Example #10
Source File: CloudDatabaseConfiguration.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoCustomConversions customConversions() {
    List<Converter<?, ?>> converterList = new ArrayList<>();
    converterList.add(DateToZonedDateTimeConverter.INSTANCE);
    converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
    return new MongoCustomConversions(converterList);
}
 
Example #11
Source File: ApplicationContextExpressionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void prototypeCreationReevaluatesExpressions() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
	GenericConversionService cs = new GenericConversionService();
	cs.addConverter(String.class, String.class, new Converter<String, String>() {
		@Override
		public String convert(String source) {
			return source.trim();
		}
	});
	ac.getBeanFactory().registerSingleton(GenericApplicationContext.CONVERSION_SERVICE_BEAN_NAME, cs);
	RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("country", "#{systemProperties.country}");
	rbd.getPropertyValues().add("country2", new TypedStringValue("-#{systemProperties.country}-"));
	ac.registerBeanDefinition("test", rbd);
	ac.refresh();

	try {
		System.getProperties().put("name", "juergen1");
		System.getProperties().put("country", " UK1 ");
		PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen1", tb.getName());
		assertEquals("UK1", tb.getCountry());
		assertEquals("-UK1-", tb.getCountry2());

		System.getProperties().put("name", "juergen2");
		System.getProperties().put("country", "  UK2  ");
		tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen2", tb.getName());
		assertEquals("UK2", tb.getCountry());
		assertEquals("-UK2-", tb.getCountry2());
	}
	finally {
		System.getProperties().remove("name");
		System.getProperties().remove("country");
	}
}
 
Example #12
Source File: OpPlusTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void test_binaryPlusWithTimeConverted() {

	final SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(new Converter<Time, String>() {
		@Override
		public String convert(Time source) {
			return format.format(source);
		}
	});

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);

	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
Example #13
Source File: IntStringValueToEnumConverterFactory.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
	Class<?> enumType = targetType;
	while(enumType != null && !enumType.isEnum()) {
		enumType = enumType.getSuperclass();
	}
	Assert.notNull(enumType, "The target type " + targetType.getName()
			+ " does not refer to an enum");
	return new StringToEnum(enumType);
}
 
Example #14
Source File: GenericConversionService.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void addConverter(Converter<?, ?> converter) {
	ResolvableType[] typeInfo = getRequiredTypeInfo(converter.getClass(), Converter.class);
	if (typeInfo == null && converter instanceof DecoratingProxy) {
		typeInfo = getRequiredTypeInfo(((DecoratingProxy) converter).getDecoratedClass(), Converter.class);
	}
	if (typeInfo == null) {
		throw new IllegalArgumentException("Unable to determine source type <S> and target type <T> for your " +
				"Converter [" + converter.getClass().getName() + "]; does the class parameterize those types?");
	}
	addConverter(new ConverterAdapter(converter, typeInfo[0], typeInfo[1]));
}
 
Example #15
Source File: ViolationTypesController.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Autowired
public ViolationTypesController(final ViolationTypeRepository violationTypeRepository, final Converter<ViolationTypeEntity, ViolationType> entityToDto) {
    Assert.notNull(violationTypeRepository, "violationTypeRepository must not be null");
    Assert.notNull(entityToDto, "entityToDto converter must not be null");

    this.violationTypeRepository = violationTypeRepository;
    this.entityToDto = entityToDto;
}
 
Example #16
Source File: AsmTest.java    From mica with 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 #17
Source File: ConverterConfiguration.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: SpannerReadConverter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public SpannerReadConverter(Collection<Converter> readConverters) {
	this(getCustomConversions(
			Stream.<Converter>concat(
					SpannerConverters.DEFAULT_SPANNER_READ_CONVERTERS.stream(),
					Optional.ofNullable(readConverters).orElse(Collections.emptyList()).stream())
				.collect(Collectors.toList())));

}
 
Example #19
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
public Converter<String, Sector> getStringToSectorConverter() {
    return new Converter<java.lang.String, Sector>() {
        public Sector convert(String id) {
        	log.info("converting String to Sector id=" + id);
            return getObject().convert(getObject().convert(id, Long.class), Sector.class);
        }
    };
}
 
Example #20
Source File: FormattingConversionServiceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #21
Source File: BindingServiceProperties.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	this.applicationContext = (ConfigurableApplicationContext) applicationContext;
	GenericConversionService cs = (GenericConversionService) IntegrationUtils
			.getConversionService(this.applicationContext.getBeanFactory());
	if (this.applicationContext.containsBean("spelConverter")) {
		Converter<?, ?> converter = (Converter<?, ?>) this.applicationContext
				.getBean("spelConverter");
		cs.addConverter(converter);
	}
}
 
Example #22
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #23
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #24
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #25
Source File: DateTimeFormatConfig.java    From yue-library with 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 #26
Source File: WebMvcConfigurationSupportExtensionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void addFormatters(FormatterRegistry registry) {
	registry.addConverter(new Converter<TestBean, String>() {
		@Override
		public String convert(TestBean source) {
			return "converted";
		}
	});
}
 
Example #27
Source File: MyResultProcessor.java    From specification-with-projection with 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 #28
Source File: ApplicationConversionServiceFactoryBean.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #29
Source File: DefaultConversionServiceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: CamelCloudZookeeperAutoConfigurationTest.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@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();
    }
}