Search in sources :

Example 6 with ConversionService

use of org.springframework.core.convert.ConversionService in project spring-framework by spring-projects.

the class DelegatingWebFluxConfigurationTests method requestMappingHandlerAdapter.

@Test
public void requestMappingHandlerAdapter() throws Exception {
    delegatingConfig.setConfigurers(Collections.singletonList(webFluxConfigurer));
    RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter();
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    ConversionService initializerConversionService = initializer.getConversionService();
    assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
    verify(webFluxConfigurer).configureMessageReaders(readers.capture());
    verify(webFluxConfigurer).extendMessageReaders(readers.capture());
    verify(webFluxConfigurer).getValidator();
    verify(webFluxConfigurer).getMessageCodesResolver();
    verify(webFluxConfigurer).addFormatters(formatterRegistry.capture());
    verify(webFluxConfigurer).addArgumentResolvers(any());
    assertSame(formatterRegistry.getValue(), initializerConversionService);
    assertEquals(7, readers.getValue().size());
}
Also used : LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) ConversionService(org.springframework.core.convert.ConversionService) RequestMappingHandlerAdapter(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter) Test(org.junit.Test)

Example 7 with ConversionService

use of org.springframework.core.convert.ConversionService in project spring-framework by spring-projects.

the class WebFluxConfigurationSupportTests method requestMappingHandlerAdapter.

@Test
public void requestMappingHandlerAdapter() throws Exception {
    ApplicationContext context = loadConfig(WebFluxConfig.class);
    String name = "requestMappingHandlerAdapter";
    RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
    assertNotNull(adapter);
    List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
    assertEquals(7, readers.size());
    assertHasMessageReader(readers, byte[].class, APPLICATION_OCTET_STREAM);
    assertHasMessageReader(readers, ByteBuffer.class, APPLICATION_OCTET_STREAM);
    assertHasMessageReader(readers, String.class, TEXT_PLAIN);
    assertHasMessageReader(readers, Resource.class, IMAGE_PNG);
    assertHasMessageReader(readers, TestBean.class, APPLICATION_XML);
    assertHasMessageReader(readers, TestBean.class, APPLICATION_JSON);
    assertHasMessageReader(readers, TestBean.class, null);
    WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
    assertNotNull(bindingInitializer);
    WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
    bindingInitializer.initBinder(binder);
    name = "webFluxConversionService";
    ConversionService service = context.getBean(name, ConversionService.class);
    assertSame(service, binder.getConversionService());
    name = "webFluxValidator";
    Validator validator = context.getBean(name, Validator.class);
    assertSame(validator, binder.getValidator());
}
Also used : DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ConversionService(org.springframework.core.convert.ConversionService) RequestMappingHandlerAdapter(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) Validator(org.springframework.validation.Validator) WebBindingInitializer(org.springframework.web.bind.support.WebBindingInitializer) Test(org.junit.Test)

Example 8 with ConversionService

use of org.springframework.core.convert.ConversionService in project spring-framework by spring-projects.

the class ServletModelAttributeMethodProcessor method createAttributeFromRequestValue.

/**
	 * Create a model attribute from a String request value (e.g. URI template
	 * variable, request parameter) using type conversion.
	 * <p>The default implementation converts only if there a registered
	 * {@link Converter} that can perform the conversion.
	 * @param sourceValue the source value to create the model attribute from
	 * @param attributeName the name of the attribute, never {@code null}
	 * @param methodParam the method parameter
	 * @param binderFactory for creating WebDataBinder instance
	 * @param request the current request
	 * @return the created model attribute, or {@code null}
	 * @throws Exception
	 */
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName, MethodParameter methodParam, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
    DataBinder binder = binderFactory.createBinder(request, null, attributeName);
    ConversionService conversionService = binder.getConversionService();
    if (conversionService != null) {
        TypeDescriptor source = TypeDescriptor.valueOf(String.class);
        TypeDescriptor target = new TypeDescriptor(methodParam);
        if (conversionService.canConvert(source, target)) {
            return binder.convertIfNecessary(sourceValue, methodParam.getParameterType(), methodParam);
        }
    }
    return null;
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionService(org.springframework.core.convert.ConversionService) ServletRequestDataBinder(org.springframework.web.bind.ServletRequestDataBinder) DataBinder(org.springframework.validation.DataBinder) WebDataBinder(org.springframework.web.bind.WebDataBinder)

Example 9 with ConversionService

use of org.springframework.core.convert.ConversionService in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportTests method requestMappingHandlerAdapter.

@Test
public void requestMappingHandlerAdapter() throws Exception {
    ApplicationContext context = initContext(WebConfig.class);
    RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
    List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
    assertEquals(11, converters.size());
    converters.stream().filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter).forEach(converter -> {
        ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
        assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
        assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
        assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
        if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
            assertEquals(XmlMapper.class, mapper.getClass());
        }
    });
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    assertNotNull(initializer);
    ConversionService conversionService = initializer.getConversionService();
    assertNotNull(conversionService);
    assertTrue(conversionService instanceof FormattingConversionService);
    Validator validator = initializer.getValidator();
    assertNotNull(validator);
    assertTrue(validator instanceof LocalValidatorFactoryBean);
    DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
    @SuppressWarnings("unchecked") List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
    assertEquals(2, bodyAdvice.size());
    assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
    assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
Also used : LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) PathVariable(org.springframework.web.bind.annotation.PathVariable) DEFAULT_VIEW_INCLUSION(com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION) Validator(org.springframework.validation.Validator) WebDataBinderFactory(org.springframework.web.bind.support.WebDataBinderFactory) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) DateTimeFormat(org.springframework.format.annotation.DateTimeFormat) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) FAIL_ON_UNKNOWN_PROPERTIES(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) HandlerExceptionResolverComposite(org.springframework.web.servlet.handler.HandlerExceptionResolverComposite) MvcUriComponentsBuilder(org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder) Locale(java.util.Locale) MethodParameter(org.springframework.core.MethodParameter) AntPathMatcher(org.springframework.util.AntPathMatcher) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) JsonViewRequestBodyAdvice(org.springframework.web.servlet.mvc.method.annotation.JsonViewRequestBodyAdvice) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) HandlerMethodArgumentResolver(org.springframework.web.method.support.HandlerMethodArgumentResolver) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) ISO(org.springframework.format.annotation.DateTimeFormat.ISO) StaticMessageSource(org.springframework.context.support.StaticMessageSource) Configuration(org.springframework.context.annotation.Configuration) MockServletContext(org.springframework.mock.web.test.MockServletContext) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) HandlerExceptionResolver(org.springframework.web.servlet.HandlerExceptionResolver) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) Assert.assertFalse(org.junit.Assert.assertFalse) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) ExceptionHandlerExceptionResolver(org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) ResponseStatusExceptionResolver(org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) HandlerMethodReturnValueHandler(org.springframework.web.method.support.HandlerMethodReturnValueHandler) Ordered(org.springframework.core.Ordered) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) JsonViewResponseBodyAdvice(org.springframework.web.servlet.mvc.method.annotation.JsonViewResponseBodyAdvice) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) AbstractJackson2HttpMessageConverter(org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Controller(org.springframework.stereotype.Controller) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Scope(org.springframework.context.annotation.Scope) HttpServletRequest(javax.servlet.http.HttpServletRequest) CompositeUriComponentsContributor(org.springframework.web.method.support.CompositeUriComponentsContributor) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ConversionService(org.springframework.core.convert.ConversionService) MessageSource(org.springframework.context.MessageSource) ViewResolver(org.springframework.web.servlet.ViewResolver) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) PathMatcher(org.springframework.util.PathMatcher) ViewResolverComposite(org.springframework.web.servlet.view.ViewResolverComposite) Assert.assertNotNull(org.junit.Assert.assertNotNull) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) ScopedProxyMode(org.springframework.context.annotation.ScopedProxyMode) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) FormattingConversionService(org.springframework.format.support.FormattingConversionService) ApplicationContext(org.springframework.context.ApplicationContext) BeanNameViewResolver(org.springframework.web.servlet.view.BeanNameViewResolver) HttpStatus(org.springframework.http.HttpStatus) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) Assert.assertNull(org.junit.Assert.assertNull) UrlPathHelper(org.springframework.web.util.UrlPathHelper) Bean(org.springframework.context.annotation.Bean) DefaultHandlerExceptionResolver(org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver) Assert.assertEquals(org.junit.Assert.assertEquals) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) FormattingConversionService(org.springframework.format.support.FormattingConversionService) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) ConversionService(org.springframework.core.convert.ConversionService) FormattingConversionService(org.springframework.format.support.FormattingConversionService) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) AbstractJackson2HttpMessageConverter(org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter) AbstractJackson2HttpMessageConverter(org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter) List(java.util.List) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Validator(org.springframework.validation.Validator) Test(org.junit.Test)

Example 10 with ConversionService

use of org.springframework.core.convert.ConversionService in project spring-framework by spring-projects.

the class DelegatingWebMvcConfigurationTests method requestMappingHandlerAdapter.

@Test
public void requestMappingHandlerAdapter() throws Exception {
    delegatingConfig.setConfigurers(Collections.singletonList(webMvcConfigurer));
    RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter();
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    ConversionService initializerConversionService = initializer.getConversionService();
    assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
    verify(webMvcConfigurer).configureMessageConverters(converters.capture());
    verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
    verify(webMvcConfigurer).addFormatters(conversionService.capture());
    verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture());
    verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
    verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());
    assertSame(conversionService.getValue(), initializerConversionService);
    assertEquals(0, resolvers.getValue().size());
    assertEquals(0, handlers.getValue().size());
    assertEquals(converters.getValue(), adapter.getMessageConverters());
    assertNotNull(asyncConfigurer);
}
Also used : LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) ConversionService(org.springframework.core.convert.ConversionService) FormattingConversionService(org.springframework.format.support.FormattingConversionService) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) Test(org.junit.Test)

Aggregations

ConversionService (org.springframework.core.convert.ConversionService)21 Test (org.junit.Test)11 DefaultConversionService (org.springframework.core.convert.support.DefaultConversionService)5 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)4 ApplicationContext (org.springframework.context.ApplicationContext)3 LocalValidatorFactoryBean (org.springframework.validation.beanvalidation.LocalValidatorFactoryBean)3 WebDataBinder (org.springframework.web.bind.WebDataBinder)3 ConfigurableWebBindingInitializer (org.springframework.web.bind.support.ConfigurableWebBindingInitializer)3 Collection (java.util.Collection)2 Map (java.util.Map)2 ConversionFailedException (org.springframework.core.convert.ConversionFailedException)2 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)2 StandardTypeConverter (org.springframework.expression.spel.support.StandardTypeConverter)2 FormattingConversionService (org.springframework.format.support.FormattingConversionService)2 Validator (org.springframework.validation.Validator)2 WebDataBinderFactory (org.springframework.web.bind.support.WebDataBinderFactory)2 RequestMappingHandlerAdapter (org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter)2 RequestMappingHandlerAdapter (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter)2 FAIL_ON_UNKNOWN_PROPERTIES (com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)1 DEFAULT_VIEW_INCLUSION (com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION)1