Search in sources :

Example 76 with HttpMessageConverter

use of org.springframework.http.converter.HttpMessageConverter in project spring-framework by spring-projects.

the class RequestResponseBodyMethodProcessorTests method resolveArgumentParameterizedType.

@Test
public void resolveArgumentParameterizedType() throws Exception {
    String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
    this.servletRequest.setContent(content.getBytes("UTF-8"));
    this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new MappingJackson2HttpMessageConverter());
    RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
    @SuppressWarnings("unchecked") List<SimpleBean> result = (List<SimpleBean>) processor.resolveArgument(paramGenericList, container, request, factory);
    assertNotNull(result);
    assertEquals("Jad", result.get(0).getName());
    assertEquals("Robert", result.get(1).getName());
}
Also used : MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) ArrayList(java.util.ArrayList) AllEncompassingFormHttpMessageConverter(org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter) ResourceHttpMessageConverter(org.springframework.http.converter.ResourceHttpMessageConverter) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) List(java.util.List) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 77 with HttpMessageConverter

use of org.springframework.http.converter.HttpMessageConverter in project spring-framework by spring-projects.

the class RequestResponseBodyMethodProcessorTests method jacksonJsonViewWithResponseBodyAndJsonMessageConverter.

@Test
public void jacksonJsonViewWithResponseBodyAndJsonMessageConverter() throws Exception {
    Method method = JacksonController.class.getMethod("handleResponseBody");
    HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
    MethodParameter methodReturnType = handlerMethod.getReturnType();
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new MappingJackson2HttpMessageConverter());
    RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));
    Object returnValue = new JacksonController().handleResponseBody();
    processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);
    String content = this.servletResponse.getContentAsString();
    assertFalse(content.contains("\"withView1\":\"with\""));
    assertTrue(content.contains("\"withView2\":\"with\""));
    assertFalse(content.contains("\"withoutView\":\"without\""));
}
Also used : MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) ArrayList(java.util.ArrayList) AllEncompassingFormHttpMessageConverter(org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter) ResourceHttpMessageConverter(org.springframework.http.converter.ResourceHttpMessageConverter) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) MethodParameter(org.springframework.core.MethodParameter) HandlerMethod(org.springframework.web.method.HandlerMethod) Test(org.junit.Test)

Example 78 with HttpMessageConverter

use of org.springframework.http.converter.HttpMessageConverter in project spring-framework by spring-projects.

the class AbstractMessageConverterMethodArgumentResolver method readWithMessageConverters.

/**
	 * Create the method argument value of the expected parameter type by reading
	 * from the given HttpInputMessage.
	 * @param <T> the expected type of the argument value to be created
	 * @param inputMessage the HTTP input message representing the current request
	 * @param parameter the method parameter descriptor (may be {@code null})
	 * @param targetType the target type, not necessarily the same as the method
	 * parameter type, e.g. for {@code HttpEntity<String>}.
	 * @return the created method argument value
	 * @throws IOException if the reading from the request fails
	 * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
	 */
@SuppressWarnings("unchecked")
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
    MediaType contentType;
    boolean noContentType = false;
    try {
        contentType = inputMessage.getHeaders().getContentType();
    } catch (InvalidMediaTypeException ex) {
        throw new HttpMediaTypeNotSupportedException(ex.getMessage());
    }
    if (contentType == null) {
        noContentType = true;
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }
    Class<?> contextClass = (parameter != null ? parameter.getContainingClass() : null);
    Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
    if (targetClass == null) {
        ResolvableType resolvableType = (parameter != null ? ResolvableType.forMethodParameter(parameter) : ResolvableType.forType(targetType));
        targetClass = (Class<T>) resolvableType.resolve();
    }
    HttpMethod httpMethod = ((HttpRequest) inputMessage).getMethod();
    Object body = NO_VALUE;
    try {
        inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage);
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
            if (converter instanceof GenericHttpMessageConverter) {
                GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
                if (genericConverter.canRead(targetType, contextClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = genericConverter.read(targetType, contextClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            } else if (targetClass != null) {
                if (converter.canRead(targetClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            }
        }
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex);
    }
    if (body == NO_VALUE) {
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && inputMessage.getBody() == null)) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
    }
    return body;
}
Also used : HttpRequest(org.springframework.http.HttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 79 with HttpMessageConverter

use of org.springframework.http.converter.HttpMessageConverter in project spring-framework by spring-projects.

the class AbstractMessageConverterMethodProcessor method writeWithMessageConverters.

/**
	 * Writes the given return type to the given output message.
	 * @param value the value to write to the output message
	 * @param returnType the type of the value
	 * @param inputMessage the input messages. Used to inspect the {@code Accept} header.
	 * @param outputMessage the output message to write to
	 * @throws IOException thrown in case of I/O errors
	 * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
	 * the request cannot be met by the message converters
	 */
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
    Object outputValue;
    Class<?> valueType;
    Type declaredType;
    if (value instanceof CharSequence) {
        outputValue = value.toString();
        valueType = String.class;
        declaredType = String.class;
    } else {
        outputValue = value;
        valueType = getReturnValueType(outputValue, returnType);
        declaredType = getGenericType(returnType);
    }
    HttpServletRequest request = inputMessage.getServletRequest();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
    if (outputValue != null && producibleMediaTypes.isEmpty()) {
        throw new IllegalArgumentException("No converter found for return value of type: " + valueType);
    }
    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
    for (MediaType requestedType : requestedMediaTypes) {
        for (MediaType producibleType : producibleMediaTypes) {
            if (requestedType.isCompatibleWith(producibleType)) {
                compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
            }
        }
    }
    if (compatibleMediaTypes.isEmpty()) {
        if (outputValue != null) {
            throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
        }
        return;
    }
    List<MediaType> mediaTypes = new ArrayList<>(compatibleMediaTypes);
    MediaType.sortBySpecificityAndQuality(mediaTypes);
    MediaType selectedMediaType = null;
    for (MediaType mediaType : mediaTypes) {
        if (mediaType.isConcrete()) {
            selectedMediaType = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
            selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }
    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
            if (messageConverter instanceof GenericHttpMessageConverter) {
                if (((GenericHttpMessageConverter) messageConverter).canWrite(declaredType, valueType, selectedMediaType)) {
                    outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType, (Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(), inputMessage, outputMessage);
                    if (outputValue != null) {
                        addContentDispositionHeader(inputMessage, outputMessage);
                        ((GenericHttpMessageConverter) messageConverter).write(outputValue, declaredType, selectedMediaType, outputMessage);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Written [" + outputValue + "] as \"" + selectedMediaType + "\" using [" + messageConverter + "]");
                        }
                    }
                    return;
                }
            } else if (messageConverter.canWrite(valueType, selectedMediaType)) {
                outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType, (Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(), inputMessage, outputMessage);
                if (outputValue != null) {
                    addContentDispositionHeader(inputMessage, outputMessage);
                    ((HttpMessageConverter) messageConverter).write(outputValue, selectedMediaType, outputMessage);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Written [" + outputValue + "] as \"" + selectedMediaType + "\" using [" + messageConverter + "]");
                    }
                }
                return;
            }
        }
    }
    if (outputValue != null) {
        throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) ResolvableType(org.springframework.core.ResolvableType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 80 with HttpMessageConverter

use of org.springframework.http.converter.HttpMessageConverter in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportExtensionTests method requestMappingHandlerAdapter.

@SuppressWarnings("unchecked")
@Test
public void requestMappingHandlerAdapter() throws Exception {
    RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();
    // ConversionService
    String actual = this.config.mvcConversionService().convert(new TestBean(), String.class);
    assertEquals("converted", actual);
    // Message converters
    List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
    assertEquals(2, converters.size());
    assertEquals(StringHttpMessageConverter.class, converters.get(0).getClass());
    assertEquals(MappingJackson2HttpMessageConverter.class, converters.get(1).getClass());
    ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converters.get(1)).getObjectMapper();
    assertFalse(objectMapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
    assertFalse(objectMapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
    assertFalse(objectMapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
    DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
    // Custom argument resolvers and return value handlers
    List<HandlerMethodArgumentResolver> argResolvers = (List<HandlerMethodArgumentResolver>) fieldAccessor.getPropertyValue("customArgumentResolvers");
    assertEquals(1, argResolvers.size());
    List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>) fieldAccessor.getPropertyValue("customReturnValueHandlers");
    assertEquals(1, handlers.size());
    // Async support options
    assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
    assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));
    CallableProcessingInterceptor[] callableInterceptors = (CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
    assertEquals(1, callableInterceptors.length);
    DeferredResultProcessingInterceptor[] deferredResultInterceptors = (DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
    assertEquals(1, deferredResultInterceptors.length);
    assertEquals(false, fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect"));
}
Also used : HandlerMethodReturnValueHandler(org.springframework.web.method.support.HandlerMethodReturnValueHandler) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) DeferredResultProcessingInterceptor(org.springframework.web.context.request.async.DeferredResultProcessingInterceptor) HandlerMethodArgumentResolver(org.springframework.web.method.support.HandlerMethodArgumentResolver) TestBean(org.springframework.tests.sample.beans.TestBean) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) List(java.util.List) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Aggregations

HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)95 ArrayList (java.util.ArrayList)66 Test (org.junit.Test)62 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)59 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)51 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)37 MappingJackson2XmlHttpMessageConverter (org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter)33 ResourceHttpMessageConverter (org.springframework.http.converter.ResourceHttpMessageConverter)32 AllEncompassingFormHttpMessageConverter (org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter)30 RestTemplate (org.springframework.web.client.RestTemplate)29 Method (java.lang.reflect.Method)25 MethodParameter (org.springframework.core.MethodParameter)25 HandlerMethod (org.springframework.web.method.HandlerMethod)24 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)14 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)13 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)13 URI (java.net.URI)13 HashMap (java.util.HashMap)13 MapPropertySource (org.springframework.core.env.MapPropertySource)13 StandardEnvironment (org.springframework.core.env.StandardEnvironment)13