Java Code Examples for org.springframework.core.convert.support.DefaultConversionService

The following examples show how to use org.springframework.core.convert.support.DefaultConversionService. 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
Source Project: sdn-rx   Author: neo4j   File: TypeConversionIT.java    License: Apache License 2.0 6 votes vote down vote up
@Autowired TypeConversionIT(
	Driver driver,
	CypherTypesRepository cypherTypesRepository,
	AdditionalTypesRepository additionalTypesRepository,
	SpatialTypesRepository spatialTypesRepository,
	CustomTypesRepository customTypesRepository,
	Neo4jConversions neo4jConversions
) {
	this.driver = driver;
	this.cypherTypesRepository = cypherTypesRepository;
	this.additionalTypesRepository = additionalTypesRepository;
	this.spatialTypesRepository = spatialTypesRepository;
	this.customTypesRepository = customTypesRepository;
	this.defaultConversionService = new DefaultConversionService();
	neo4jConversions.registerConvertersIn(defaultConversionService);
}
 
Example #2
Source Project: java-technology-stack   Author: codeEngraver   File: ServletModelAttributeMethodProcessorTests.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	processor = new ServletModelAttributeMethodProcessor(false);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	binderFactory = new ServletRequestDataBinderFactory(null, initializer);

	mavContainer = new ModelAndViewContainer();
	request = new MockHttpServletRequest();
	webRequest = new ServletWebRequest(request);

	Method method = getClass().getDeclaredMethod("modelAttribute",
			TestBean.class, TestBeanWithoutStringConstructor.class, Optional.class);
	testBeanModelAttr = new MethodParameter(method, 0);
	testBeanWithoutStringConstructorModelAttr = new MethodParameter(method, 1);
	testBeanWithOptionalModelAttr = new MethodParameter(method, 2);
}
 
Example #3
Source Project: spring-analysis-note   Author: Vip-Augus   File: DataBinderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testBindingWithFormatterAgainstList() {
	BeanWithIntegerList tb = new BeanWithIntegerList();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("integerList[0]", "1");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Integer(1), tb.getIntegerList().get(0));
		assertEquals("1", binder.getBindingResult().getFieldValue("integerList[0]"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: ValidatorFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testListValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ListContainer listContainer = new ListContainer();
	listContainer.addString("A");
	listContainer.addString("X");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(listContainer, "listContainer");
	errors.initConversion(new DefaultConversionService());
	validator.validate(listContainer, errors);

	FieldError fieldError = errors.getFieldError("list[1]");
	assertNotNull(fieldError);
	assertEquals("X", fieldError.getRejectedValue());
	assertEquals("X", errors.getFieldValue("list[1]"));
}
 
Example #5
Source Project: spring-analysis-note   Author: Vip-Augus   File: NumberFormattingTests.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.setEmbeddedValueResolver(new StringValueResolver() {
		@Override
		public String resolveStringValue(String strVal) {
			if ("${pattern}".equals(strVal)) {
				return "#,##.00";
			}
			else {
				return strVal;
			}
		}
	});
	conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
	conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
	LocaleContextHolder.setLocale(Locale.US);
	binder = new DataBinder(new TestBean());
	binder.setConversionService(conversionService);
}
 
Example #6
Source Project: spring4-understanding   Author: langtianya   File: DataBinderTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	binder.initDirectFieldAccess();
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(0.0), tb.getMyFloat());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat"));
		assertTrue(binder.getBindingResult().hasFieldErrors("myFloat"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #7
Source Project: spring4-understanding   Author: langtianya   File: HeaderMethodArgumentResolverTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
	@SuppressWarnings("resource")
	GenericApplicationContext cxt = new GenericApplicationContext();
	cxt.refresh();
	this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

	Method method = getClass().getDeclaredMethod("handleMessage",
			String.class, String.class, String.class, String.class, String.class);
	this.paramRequired = new SynthesizingMethodParameter(method, 0);
	this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
	this.paramSystemProperty = new SynthesizingMethodParameter(method, 2);
	this.paramNotAnnotated = new SynthesizingMethodParameter(method, 3);
	this.paramNativeHeader = new SynthesizingMethodParameter(method, 4);

	this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
	GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
 
Example #8
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractRequestAttributesArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolveOptional() throws Exception {
	WebDataBinder dataBinder = new WebRequestDataBinder(null);
	dataBinder.setConversionService(new DefaultConversionService());
	WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
	given(factory.createBinder(this.webRequest, null, "foo")).willReturn(dataBinder);

	MethodParameter param = initMethodParameter(3);
	Object actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertFalse(((Optional<?>) actual).isPresent());

	Foo foo = new Foo();
	this.webRequest.setAttribute("foo", foo, getScope());

	actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertTrue(((Optional<?>) actual).isPresent());
	assertSame(foo, ((Optional<?>) actual).get());
}
 
Example #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractRequestAttributesArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolveOptional() throws Exception {
	WebDataBinder dataBinder = new WebRequestDataBinder(null);
	dataBinder.setConversionService(new DefaultConversionService());
	WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
	given(factory.createBinder(this.webRequest, null, "foo")).willReturn(dataBinder);

	MethodParameter param = initMethodParameter(3);
	Object actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertFalse(((Optional<?>) actual).isPresent());

	Foo foo = new Foo();
	this.webRequest.setAttribute("foo", foo, getScope());

	actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertTrue(((Optional<?>) actual).isPresent());
	assertSame(foo, ((Optional<?>) actual).get());
}
 
Example #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: ServletModelAttributeMethodProcessorTests.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	processor = new ServletModelAttributeMethodProcessor(false);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	binderFactory = new ServletRequestDataBinderFactory(null, initializer);

	mavContainer = new ModelAndViewContainer();
	request = new MockHttpServletRequest();
	webRequest = new ServletWebRequest(request);

	Method method = getClass().getDeclaredMethod("modelAttribute",
			TestBean.class, TestBeanWithoutStringConstructor.class, Optional.class);
	testBeanModelAttr = new MethodParameter(method, 0);
	testBeanWithoutStringConstructorModelAttr = new MethodParameter(method, 1);
	testBeanWithOptionalModelAttr = new MethodParameter(method, 2);
}
 
Example #11
Source Project: spring-analysis-note   Author: Vip-Augus   File: PathVariableMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolveArgumentWrappedAsOptional() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	@SuppressWarnings("unchecked")
	Optional<String> result = (Optional<String>)
			resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory);
	assertEquals("PathVariable not resolved correctly", "value", result.get());

	@SuppressWarnings("unchecked")
	Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
	assertNotNull(pathVars);
	assertEquals(1, pathVars.size());
	assertEquals(Optional.of("value"), pathVars.get("name"));
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void resolveOptionalParamArray() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer[].class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.empty(), result);

	request.addParameter("name", "123", "456");
	result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.class, result.getClass());
	assertArrayEquals(new Integer[] {123, 456}, (Integer[]) ((Optional) result).get());
}
 
Example #13
Source Project: sofa-tracer   Author: sofastack   File: SofaTracerConfigurationListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();

    if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) {
        return;
    }

    // set loggingPath
    String loggingPath = environment.getProperty("logging.path");
    if (StringUtils.isNotBlank(loggingPath)) {
        System.setProperty("logging.path", loggingPath);
    }

    // check spring.application.name
    String applicationName = environment
        .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
    Assert.isTrue(!StringUtils.isBlank(applicationName),
        SofaTracerConfiguration.TRACER_APPNAME_KEY + " must be configured!");
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY,
        applicationName);

    SofaTracerProperties tempTarget = new SofaTracerProperties();
    PropertiesConfigurationFactory<SofaTracerProperties> binder = new PropertiesConfigurationFactory<SofaTracerProperties>(
        tempTarget);
    ConfigurationProperties configurationPropertiesAnnotation = this
        .getConfigurationPropertiesAnnotation(tempTarget);
    if (configurationPropertiesAnnotation != null
        && StringUtils.isNotBlank(configurationPropertiesAnnotation.prefix())) {
        //consider compatible Spring Boot 1.5.X and 2.x
        binder.setIgnoreInvalidFields(configurationPropertiesAnnotation.ignoreInvalidFields());
        binder.setIgnoreUnknownFields(configurationPropertiesAnnotation.ignoreUnknownFields());
        binder.setTargetName(configurationPropertiesAnnotation.prefix());
    } else {
        binder.setTargetName(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX);
    }
    binder.setConversionService(new DefaultConversionService());
    binder.setPropertySources(environment.getPropertySources());
    try {
        binder.bindPropertiesToTarget();
    } catch (BindException ex) {
        throw new IllegalStateException("Cannot bind to SofaTracerProperties", ex);
    }

    //properties convert to tracer
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.DISABLE_MIDDLEWARE_DIGEST_LOG_KEY,
        tempTarget.getDisableDigestLog());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY,
        tempTarget.getDisableConfiguration());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_ROLLING_KEY,
        tempTarget.getTracerGlobalRollingPolicy());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_LOG_RESERVE_DAY,
        tempTarget.getTracerGlobalLogReserveDay());
    //stat log interval
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.STAT_LOG_INTERVAL,
        tempTarget.getStatLogInterval());
    //baggage length
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH,
        tempTarget.getBaggageMaxLength());
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH,
        tempTarget.getBaggageMaxLength());

    //sampler config
    if (tempTarget.getSamplerName() != null) {
        SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY,
            tempTarget.getSamplerName());
    }
    if (StringUtils.isNotBlank(tempTarget.getSamplerCustomRuleClassName())) {
        SofaTracerConfiguration.setProperty(
            SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME,
            tempTarget.getSamplerCustomRuleClassName());
    }
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY,
        String.valueOf(tempTarget.getSamplerPercentage()));

    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.JSON_FORMAT_OUTPUT,
        String.valueOf(tempTarget.isJsonOutput()));
}
 
Example #14
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolveOptionalMultipartFile() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected = new MockMultipartFile("mfile", "Hello World".getBytes());
	request.addFile(expected);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);

	assertTrue(result instanceof Optional);
	assertEquals("Invalid result", expected, ((Optional<?>) result).get());
}
 
Example #15
Source Project: blackduck-alert   Author: blackducksoftware   File: ContentConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetContent() {
    final ContentConverter contentConverter = new ContentConverter(gson, new DefaultConversionService());

    final InnerContent innerContent = new InnerContent();
    innerContent.field1 = "field 1";
    innerContent.field2 = "field 2";

    final ExampleContent exampleContent = new ExampleContent();
    exampleContent.innerObject = innerContent;
    exampleContent.exampleString = "example";
    exampleContent.exampleLong = 5L;
    exampleContent.exampleBoolean = Boolean.TRUE;
    exampleContent.exampleNullString = null;

    final String jsonContent = gson.toJson(exampleContent);
    final ExampleContent convertedContent = contentConverter.getJsonContent(jsonContent, ExampleContent.class);

    assertEquals(convertedContent, exampleContent);
}
 
Example #16
Source Project: quickfixj-spring-boot-starter   Author: esanchezros   File: AbstractEndpointTests.java    License: Apache License 2.0 6 votes vote down vote up
private void load(Function<EndpointId, Long> timeToLive,
		PathMapper endpointPathMapper,
		Class<?> configuration,
		Consumer<WebEndpointDiscoverer> consumer) {

	try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration)) {
		ConversionServiceParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper(DefaultConversionService.getSharedInstance());
		EndpointMediaTypes mediaTypes = new EndpointMediaTypes(
				Collections.singletonList("application/json"),
				Collections.singletonList("application/json"));

		WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(context,
				parameterMapper,
				mediaTypes,
				Collections.singletonList(endpointPathMapper),
				Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)),
				Collections.emptyList());

		consumer.accept(discoverer);
	}
}
 
Example #17
Source Project: radman   Author: netcore-jsa   File: AttributeServiceConfiguration.java    License: MIT License 6 votes vote down vote up
@Autowired
public AttributeServiceConfiguration(RadCheckAttributeRepo checkAttributeRepo,
                                     RadReplyAttributeRepo replyAttributeRepo,
                                     RadCheckRepo radCheckRepo,
                                     RadReplyRepo radReplyRepo,
                                     RadGroupCheckRepo radGroupCheckRepo,
                                     RadGroupReplyRepo radGroupReplyRepo,
                                     DefaultConversionService conversionService) {
    this.checkAttributeRepo = checkAttributeRepo;
    this.replyAttributeRepo = replyAttributeRepo;
    this.radCheckRepo = radCheckRepo;
    this.radReplyRepo = radReplyRepo;
    this.radGroupCheckRepo = radGroupCheckRepo;
    this.radGroupReplyRepo = radGroupReplyRepo;
    this.conversionService = conversionService;

    conversionService.addConverter(new RadCheckAttributeToDtoConverter());
    conversionService.addConverter(new DtoToRadCheckAttributeConverter());
    conversionService.addConverter(new RadReplyAttributeToDtoConverter());
    conversionService.addConverter(new DtoToRadReplyAttributeConverter());
}
 
Example #18
Source Project: radman   Author: netcore-jsa   File: RadiusUserServiceConfiguration.java    License: MIT License 6 votes vote down vote up
@Autowired
public RadiusUserServiceConfiguration(RadiusUserRepo radiusUserRepo,
                                      RadiusGroupRepo radiusGroupRepo,
                                      RadUserGroupRepo radUserGroupRepo,
                                      RadCheckRepo radCheckRepo,
                                      RadReplyRepo radReplyRepo,
                                      RadGroupCheckRepo radGroupCheckRepo,
                                      RadGroupReplyRepo radGroupReplyRepo,
                                      DefaultConversionService conversionService) {
    this.radiusUserRepo = radiusUserRepo;
    this.radiusGroupRepo = radiusGroupRepo;
    this.radUserGroupRepo = radUserGroupRepo;
    this.radCheckRepo = radCheckRepo;
    this.radReplyRepo = radReplyRepo;
    this.radGroupCheckRepo = radGroupCheckRepo;
    this.radGroupReplyRepo = radGroupReplyRepo;
    this.conversionService = conversionService;

    conversionService.addConverter(new RadiusUserToDtoConverter());
    conversionService.addConverter(new DtoToRadiusUserConverter());
    conversionService.addConverter(new RadiusGroupToDtoConverter());
    conversionService.addConverter(new DtoToRadiusGroupConverter());
    conversionService.addConverter(new RadUserGroupToDtoConverter());
    conversionService.addConverter(new DtoToRadUserGroupConverter());
}
 
Example #19
Source Project: java-technology-stack   Author: codeEngraver   File: HeaderMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() {
	@SuppressWarnings("resource")
	GenericApplicationContext cxt = new GenericApplicationContext();
	cxt.refresh();
	this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

	Method method = ReflectionUtils.findMethod(getClass(), "handleMessage", (Class<?>[]) null);
	this.paramRequired = new SynthesizingMethodParameter(method, 0);
	this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
	this.paramSystemPropertyDefaultValue = new SynthesizingMethodParameter(method, 2);
	this.paramSystemPropertyName = new SynthesizingMethodParameter(method, 3);
	this.paramNotAnnotated = new SynthesizingMethodParameter(method, 4);
	this.paramOptional = new SynthesizingMethodParameter(method, 5);
	this.paramNativeHeader = new SynthesizingMethodParameter(method, 6);

	this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
	GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: SingleColumnRowMapperTests.java    License: MIT License 6 votes vote down vote up
@Test  // SPR-16483
public void useCustomConversionService() throws SQLException {
	Timestamp timestamp = new Timestamp(0);

	DefaultConversionService myConversionService = new DefaultConversionService();
	myConversionService.addConverter(Timestamp.class, MyLocalDateTime.class,
			source -> new MyLocalDateTime(source.toLocalDateTime()));
	SingleColumnRowMapper<MyLocalDateTime> rowMapper =
			SingleColumnRowMapper.newInstance(MyLocalDateTime.class, myConversionService);

	ResultSet resultSet = mock(ResultSet.class);
	ResultSetMetaData metaData = mock(ResultSetMetaData.class);
	given(metaData.getColumnCount()).willReturn(1);
	given(resultSet.getMetaData()).willReturn(metaData);
	given(resultSet.getObject(1, MyLocalDateTime.class))
			.willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getObject(1)).willReturn(timestamp);

	MyLocalDateTime actualMyLocalDateTime = rowMapper.mapRow(resultSet, 1);

	assertNotNull(actualMyLocalDateTime);
	assertEquals(timestamp.toLocalDateTime(), actualMyLocalDateTime.value);
}
 
Example #21
Source Project: java-technology-stack   Author: codeEngraver   File: DataBinderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatterAgainstList() {
	BeanWithIntegerList tb = new BeanWithIntegerList();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("integerList[0]", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertTrue(tb.getIntegerList().isEmpty());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("integerList[0]"));
		assertTrue(binder.getBindingResult().hasFieldErrors("integerList[0]"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: DataBinderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	binder.initDirectFieldAccess();
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(0.0), tb.getMyFloat());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat"));
		assertTrue(binder.getBindingResult().hasFieldErrors("myFloat"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #23
Source Project: java-technology-stack   Author: codeEngraver   File: ValidatorFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testListValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ListContainer listContainer = new ListContainer();
	listContainer.addString("A");
	listContainer.addString("X");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(listContainer, "listContainer");
	errors.initConversion(new DefaultConversionService());
	validator.validate(listContainer, errors);

	FieldError fieldError = errors.getFieldError("list[1]");
	assertEquals("X", errors.getFieldValue("list[1]"));
}
 
Example #24
Source Project: java-technology-stack   Author: codeEngraver   File: PropertySourcesPlaceholderConfigurerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void optionalPropertyWithoutValue() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setConversionService(new DefaultConversionService());
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(OptionalTestBean.class)
					.addPropertyValue("name", "${my.name}")
					.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "");

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.setNullValue("");
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.empty()));
}
 
Example #25
Source Project: sdn-rx   Author: neo4j   File: DefaultReactiveNeo4jClient.java    License: Apache License 2.0 5 votes vote down vote up
DefaultReactiveNeo4jClient(Driver driver) {

		this.driver = driver;
		this.typeSystem = driver.defaultTypeSystem();
		this.conversionService = new DefaultConversionService();
		new Neo4jConversions().registerConvertersIn((ConverterRegistry) conversionService);
	}
 
Example #26
Source Project: java-technology-stack   Author: codeEngraver   File: ObjectToStringHttpMessageConverterTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example #27
Source Project: spring-data   Author: arangodb   File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultArangoConverter(
	final MappingContext<? extends ArangoPersistentEntity<?>, ArangoPersistentProperty> context,
	final CustomConversions conversions, final ResolverFactory resolverFactory, final ArangoTypeMapper typeMapper) {

	this.context = context;
	this.conversions = conversions;
	this.resolverFactory = resolverFactory;
	this.typeMapper = typeMapper;
	conversionService = new DefaultConversionService();
	conversions.registerConvertersIn(conversionService);
	instantiators = new EntityInstantiators();
}
 
Example #28
Source Project: spring4-understanding   Author: langtianya   File: JodaTimeFormattingTests.java    License: Apache License 2.0 5 votes vote down vote up
private void setUp(JodaTimeFormatterRegistrar registrar) {
	conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	registrar.registerFormatters(conversionService);

	JodaTimeBean bean = new JodaTimeBean();
	bean.getChildren().add(new JodaTimeBean());
	binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	LocaleContextHolder.setLocale(Locale.US);
	JodaTimeContext context = new JodaTimeContext();
	context.setTimeZone(DateTimeZone.forID("-05:00"));
	JodaTimeContextHolder.setJodaTimeContext(context);
}
 
Example #29
Source Project: spring4-understanding   Author: langtianya   File: ObjectToStringHttpMessageConverterTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example #30
Source Project: spring-cloud-gcp   Author: spring-cloud   File: TwoStepsConversions.java    License: Apache License 2.0 5 votes vote down vote up
public TwoStepsConversions(CustomConversions customConversions,
		ObjectToKeyFactory objectToKeyFactory, DatastoreMappingContext datastoreMappingContext) {
	this.objectToKeyFactory = objectToKeyFactory;
	this.datastoreMappingContext = datastoreMappingContext;
	this.conversionService = new DefaultConversionService();
	this.internalConversionService = new DefaultConversionService();
	this.customConversions = customConversions;
	this.customConversions.registerConvertersIn(this.conversionService);

	this.internalConversionService.addConverter(BYTE_ARRAY_TO_BLOB_CONVERTER);
	this.internalConversionService.addConverter(BLOB_TO_BYTE_ARRAY_CONVERTER);
}