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

The following examples show how to use org.springframework.core.convert.support.DefaultConversionService. 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: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with 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 #2
Source File: DataBinderTests.java    From spring-analysis-note with 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 #3
Source File: ServletModelAttributeMethodProcessorTests.java    From java-technology-stack with 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 #4
Source File: TypeConversionIT.java    From sdn-rx with 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 #5
Source File: ValidatorFactoryTests.java    From spring-analysis-note with 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 #6
Source File: NumberFormattingTests.java    From spring-analysis-note with 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 #7
Source File: DataBinderTests.java    From spring4-understanding with 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 #8
Source File: HeaderMethodArgumentResolverTests.java    From spring4-understanding with 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 #9
Source File: AbstractRequestAttributesArgumentResolverTests.java    From java-technology-stack with 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 File: AbstractRequestAttributesArgumentResolverTests.java    From spring-analysis-note with 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 #11
Source File: ServletModelAttributeMethodProcessorTests.java    From spring-analysis-note with 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 #12
Source File: PathVariableMethodArgumentResolverTests.java    From spring-analysis-note with 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 #13
Source File: SofaTracerConfigurationListener.java    From sofa-tracer with 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 File: ContentConverterTest.java    From blackduck-alert with 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 #15
Source File: AbstractEndpointTests.java    From quickfixj-spring-boot-starter with 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 #16
Source File: AttributeServiceConfiguration.java    From radman with 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 #17
Source File: RadiusUserServiceConfiguration.java    From radman with 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 #18
Source File: HeaderMethodArgumentResolverTests.java    From java-technology-stack with 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 #19
Source File: SingleColumnRowMapperTests.java    From java-technology-stack with 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 #20
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with 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 #21
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with 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 #22
Source File: DataBinderTests.java    From java-technology-stack with 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 #23
Source File: ValidatorFactoryTests.java    From java-technology-stack with 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 File: DataBinderTests.java    From java-technology-stack with 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 #25
Source File: GenericMapConverterTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void testEscapes() {
	DefaultConversionService conversionService = new DefaultConversionService();
	GenericMapConverter mapConverter = new GenericMapConverter(conversionService);
	conversionService.addConverter(mapConverter);

	TypeDescriptor targetType = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
			TypeDescriptor.valueOf(String[].class));
	@SuppressWarnings("unchecked")
	Map<String, String[]> result = (Map<String, String[]>) conversionService.convert("foo = bar\\,quizz",
			targetType);

	assertThat(result.values().iterator().next(), Matchers.arrayContaining("bar", "quizz"));

}
 
Example #26
Source File: TwoStepsConversions.java    From spring-cloud-gcp with 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);
}
 
Example #27
Source File: SystemServiceConfiguration.java    From radman with MIT License 5 votes vote down vote up
@Autowired
public SystemServiceConfiguration(SystemUserRepo systemUserRepo,
                                  PasswordEncoder passwordEncoder,
                                  DefaultConversionService conversionService) {
    this.systemUserRepo = systemUserRepo;
    this.passwordEncoder = passwordEncoder;
    this.conversionService = conversionService;

    conversionService.addConverter(new SystemUserToDtoConverter(conversionService));
    conversionService.addConverter(new DtoToSystemUserConverter(conversionService));
    conversionService.addConverter(new AuthProviderToDtoConverter());
    conversionService.addConverter(new DtoToAuthProviderConverter());
    conversionService.addConverter(new RoleToDtoConverter());
    conversionService.addConverter(new DtoToRoleConverter());
}
 
Example #28
Source File: AccountingServiceConfiguration.java    From radman with MIT License 5 votes vote down vote up
@Autowired
public AccountingServiceConfiguration(RadAcctRepo radAcctRepo,
                                      DefaultConversionService conversionService) {
    this.radAcctRepo = radAcctRepo;
    this.conversionService = conversionService;

    conversionService.addConverter(new RadAcctToDtoConverter());
}
 
Example #29
Source File: RelaxedConversionService.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link RelaxedConversionService} instance.
 *
 * @param conversionService and option root conversion service
 */
RelaxedConversionService(ConversionService conversionService){
    this.conversionService = conversionService;
    this.additionalConverters = new GenericConversionService();
    DefaultConversionService.addCollectionConverters(this.additionalConverters);
    this.additionalConverters
        .addConverterFactory(new RelaxedConversionService.StringToEnumIgnoringCaseConverterFactory());
    this.additionalConverters.addConverter(new StringToCharArrayConverter());
}
 
Example #30
Source File: PlatformITBaseConfig.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public ConversionService conversionService() {
  DefaultConversionService defaultConversionService = new DefaultConversionService();
  defaultConversionService.addConverter(new StringToDateConverter());
  defaultConversionService.addConverter(new StringToDateTimeConverter());
  return defaultConversionService;
}