Search in sources :

Example 21 with StringHttpMessageConverter

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

the class HttpEntityMethodProcessorTests method handleReturnValueWithMalformedAcceptHeader.

// gh-24539
@Test
public void handleReturnValueWithMalformedAcceptHeader() throws Exception {
    webRequest.getNativeRequest(MockHttpServletRequest.class).addHeader("Accept", "null");
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(new StringHttpMessageConverter());
    Method method = getClass().getDeclaredMethod("handle");
    MethodParameter returnType = new MethodParameter(method, -1);
    ResponseEntity<String> returnValue = ResponseEntity.badRequest().body("Foo");
    HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);
    processor.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    assertThat(servletResponse.getStatus()).isEqualTo(400);
    assertThat(servletResponse.getHeader("Content-Type")).isNull();
    assertThat(servletResponse.getContentAsString()).isEmpty();
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ArrayList(java.util.ArrayList) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) MethodParameter(org.springframework.core.MethodParameter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test)

Example 22 with StringHttpMessageConverter

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

the class HttpEntityMethodProcessorTests method handleReturnValueWithETagAndETagFilter.

// SPR-13423
@Test
public void handleReturnValueWithETagAndETagFilter() throws Exception {
    String eTagValue = "\"deadb33f8badf00d\"";
    String content = "body";
    Method method = getClass().getDeclaredMethod("handle");
    MethodParameter returnType = new MethodParameter(method, -1);
    FilterChain chain = (req, res) -> {
        ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(eTagValue).body(content);
        try {
            ServletWebRequest requestToUse = new ServletWebRequest((HttpServletRequest) req, (HttpServletResponse) res);
            new HttpEntityMethodProcessor(Collections.singletonList(new StringHttpMessageConverter())).handleReturnValue(returnValue, returnType, mavContainer, requestToUse);
            assertThat(this.servletResponse.getContentAsString()).as("Response body was cached? It should be written directly to the raw response").isEqualTo(content);
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    };
    this.servletRequest.setMethod("GET");
    new ShallowEtagHeaderFilter().doFilter(this.servletRequest, this.servletResponse, chain);
    assertThat(this.servletResponse.getStatus()).isEqualTo(200);
    assertThat(this.servletResponse.getHeader(HttpHeaders.ETAG)).isEqualTo(eTagValue);
    assertThat(this.servletResponse.getContentAsString()).isEqualTo(content);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebDataBinderFactory(org.springframework.web.bind.support.WebDataBinderFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayList(java.util.ArrayList) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) MethodParameter(org.springframework.core.MethodParameter) Nullable(org.springframework.lang.Nullable) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) FilterChain(jakarta.servlet.FilterChain) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Serializable(java.io.Serializable) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) WebDataBinder(org.springframework.web.bind.WebDataBinder) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ResponseEntity(org.springframework.http.ResponseEntity) MethodParameter(org.springframework.core.MethodParameter) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Example 23 with StringHttpMessageConverter

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

the class ServletAnnotationControllerHandlerMethodTests method unsupportedPatchBody.

@PathPatternsParameterizedTest
void unsupportedPatchBody(boolean usePathPatterns) throws Exception {
    initDispatcherServlet(RequestResponseBodyController.class, usePathPatterns, wac -> {
        RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
        adapterDef.getPropertyValues().add("messageConverters", converter);
        wac.registerBeanDefinition("handlerAdapter", adapterDef);
    });
    MockHttpServletRequest request = new MockHttpServletRequest("PATCH", "/something");
    String requestBody = "Hello World";
    request.setContent(requestBody.getBytes(StandardCharsets.UTF_8));
    request.addHeader("Content-Type", "application/pdf");
    MockHttpServletResponse response = new MockHttpServletResponse();
    getServlet().service(request, response);
    assertThat(response.getStatus()).isEqualTo(415);
    assertThat(response.getHeader("Accept-Patch")).isEqualTo("text/plain");
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) PathPatternsParameterizedTest(org.springframework.web.servlet.handler.PathPatternsParameterizedTest)

Example 24 with StringHttpMessageConverter

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

the class WebMvcConfigurationSupport method addDefaultHttpMessageConverters.

/**
 * Adds a set of default HttpMessageConverter instances to the given list.
 * Subclasses can call this method from {@link #configureMessageConverters}.
 * @param messageConverters the list to add the default message converters to
 */
protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new ResourceRegionHttpMessageConverter());
    if (!shouldIgnoreXml) {
        try {
            messageConverters.add(new SourceHttpMessageConverter<>());
        } catch (Throwable ex) {
        // Ignore when no TransformerFactory implementation is available...
        }
    }
    messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    if (romePresent) {
        messageConverters.add(new AtomFeedHttpMessageConverter());
        messageConverters.add(new RssChannelHttpMessageConverter());
    }
    if (!shouldIgnoreXml) {
        if (jackson2XmlPresent) {
            Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
            if (this.applicationContext != null) {
                builder.applicationContext(this.applicationContext);
            }
            messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
        } else if (jaxb2Present) {
            messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
    }
    if (kotlinSerializationJsonPresent) {
        messageConverters.add(new KotlinSerializationJsonHttpMessageConverter());
    }
    if (jackson2Present) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
        if (this.applicationContext != null) {
            builder.applicationContext(this.applicationContext);
        }
        messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    } else if (gsonPresent) {
        messageConverters.add(new GsonHttpMessageConverter());
    } else if (jsonbPresent) {
        messageConverters.add(new JsonbHttpMessageConverter());
    }
    if (jackson2SmilePresent) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.smile();
        if (this.applicationContext != null) {
            builder.applicationContext(this.applicationContext);
        }
        messageConverters.add(new MappingJackson2SmileHttpMessageConverter(builder.build()));
    }
    if (jackson2CborPresent) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.cbor();
        if (this.applicationContext != null) {
            builder.applicationContext(this.applicationContext);
        }
        messageConverters.add(new MappingJackson2CborHttpMessageConverter(builder.build()));
    }
}
Also used : Jaxb2RootElementHttpMessageConverter(org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) ResourceRegionHttpMessageConverter(org.springframework.http.converter.ResourceRegionHttpMessageConverter) AtomFeedHttpMessageConverter(org.springframework.http.converter.feed.AtomFeedHttpMessageConverter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) GsonHttpMessageConverter(org.springframework.http.converter.json.GsonHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MappingJackson2SmileHttpMessageConverter(org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverter) JsonbHttpMessageConverter(org.springframework.http.converter.json.JsonbHttpMessageConverter) Jackson2ObjectMapperBuilder(org.springframework.http.converter.json.Jackson2ObjectMapperBuilder) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) KotlinSerializationJsonHttpMessageConverter(org.springframework.http.converter.json.KotlinSerializationJsonHttpMessageConverter) RssChannelHttpMessageConverter(org.springframework.http.converter.feed.RssChannelHttpMessageConverter) ResourceHttpMessageConverter(org.springframework.http.converter.ResourceHttpMessageConverter) AllEncompassingFormHttpMessageConverter(org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter) MappingJackson2CborHttpMessageConverter(org.springframework.http.converter.cbor.MappingJackson2CborHttpMessageConverter)

Example 25 with StringHttpMessageConverter

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

the class DefaultServerResponseBuilderTests method body.

@Test
public void body() throws Exception {
    String body = "foo";
    ServerResponse response = ServerResponse.ok().body(body);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    ServerResponse.Context context = () -> Collections.singletonList(new StringHttpMessageConverter());
    ModelAndView mav = response.writeTo(mockRequest, mockResponse, context);
    assertThat(mav).isNull();
    assertThat(mockResponse.getContentAsString()).isEqualTo(body);
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test)

Aggregations

StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)91 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)46 ArrayList (java.util.ArrayList)38 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)25 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)24 RestTemplate (org.springframework.web.client.RestTemplate)23 Test (org.junit.jupiter.api.Test)21 ResourceHttpMessageConverter (org.springframework.http.converter.ResourceHttpMessageConverter)18 Test (org.junit.Test)16 AllEncompassingFormHttpMessageConverter (org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter)16 MappingJackson2XmlHttpMessageConverter (org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter)11 MediaType (org.springframework.http.MediaType)9 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)9 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)9 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)7 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)7 URI (java.net.URI)7 HashMap (java.util.HashMap)7 Before (org.junit.Before)7 MethodParameter (org.springframework.core.MethodParameter)7