Search in sources :

Example 1 with GenericHttpMessageConverter

use of cn.taketoday.http.converter.GenericHttpMessageConverter in project today-framework by TAKETODAY.

the class RestTemplateTests method exchangeParameterizedType.

@Test
@SuppressWarnings("rawtypes")
void exchangeParameterizedType() throws Exception {
    GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
    template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
    TypeReference<List<Integer>> intList = new TypeReference<List<Integer>>() {
    };
    given(converter.canRead(intList.getType(), null, null)).willReturn(true);
    given(converter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    given(converter.canWrite(String.class, String.class, null)).willReturn(true);
    HttpHeaders requestHeaders = HttpHeaders.create();
    mockSentRequest(POST, "https://example.com", requestHeaders);
    List<Integer> expected = Collections.singletonList(42);
    HttpHeaders responseHeaders = HttpHeaders.create();
    responseHeaders.setContentType(MediaType.TEXT_PLAIN);
    responseHeaders.setContentLength(10);
    mockResponseStatus(HttpStatus.OK);
    given(response.getHeaders()).willReturn(responseHeaders);
    given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
    given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
    given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
    HttpHeaders entityHeaders = HttpHeaders.create();
    entityHeaders.set("MyHeader", "MyValue");
    HttpEntity<String> requestEntity = new HttpEntity<>("Hello World", entityHeaders);
    ResponseEntity<List<Integer>> result = template.exchange("https://example.com", POST, requestEntity, intList);
    assertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected);
    assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
    assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
    assertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue");
    assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
    verify(response).close();
}
Also used : HttpInputMessage(cn.taketoday.http.HttpInputMessage) HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) TypeReference(cn.taketoday.core.TypeReference) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) Test(org.junit.jupiter.api.Test)

Example 2 with GenericHttpMessageConverter

use of cn.taketoday.http.converter.GenericHttpMessageConverter in project today-infrastructure by TAKETODAY.

the class RestTemplateTests method exchangeParameterizedType.

@Test
@SuppressWarnings("rawtypes")
void exchangeParameterizedType() throws Exception {
    GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
    template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
    TypeReference<List<Integer>> intList = new TypeReference<List<Integer>>() {
    };
    given(converter.canRead(intList.getType(), null, null)).willReturn(true);
    given(converter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    given(converter.canWrite(String.class, String.class, null)).willReturn(true);
    HttpHeaders requestHeaders = HttpHeaders.create();
    mockSentRequest(POST, "https://example.com", requestHeaders);
    List<Integer> expected = Collections.singletonList(42);
    HttpHeaders responseHeaders = HttpHeaders.create();
    responseHeaders.setContentType(MediaType.TEXT_PLAIN);
    responseHeaders.setContentLength(10);
    mockResponseStatus(HttpStatus.OK);
    given(response.getHeaders()).willReturn(responseHeaders);
    given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
    given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
    given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
    HttpHeaders entityHeaders = HttpHeaders.create();
    entityHeaders.set("MyHeader", "MyValue");
    HttpEntity<String> requestEntity = new HttpEntity<>("Hello World", entityHeaders);
    ResponseEntity<List<Integer>> result = template.exchange("https://example.com", POST, requestEntity, intList);
    assertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected);
    assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
    assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
    assertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue");
    assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
    verify(response).close();
}
Also used : HttpInputMessage(cn.taketoday.http.HttpInputMessage) HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) TypeReference(cn.taketoday.core.TypeReference) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) Test(org.junit.jupiter.api.Test)

Example 3 with GenericHttpMessageConverter

use of cn.taketoday.http.converter.GenericHttpMessageConverter in project today-framework by TAKETODAY.

the class AbstractMessageConverterParameterResolver method readWithMessageConverters.

/**
 * Create the method argument value of the expected parameter type by
 * reading from the given request.
 *
 * @param context the current request context
 * @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
 */
@Nullable
@SuppressWarnings("unchecked")
protected <T> Object readWithMessageConverters(RequestContext context, MethodParameter parameter, Type targetType) throws // 
IOException, // 
HttpMediaTypeNotSupportedException, // 
HttpMessageNotReadableException {
    MediaType contentType;
    boolean noContentType = false;
    try {
        contentType = context.requestHeaders().getContentType();
    } catch (InvalidMediaTypeException ex) {
        throw new HttpMediaTypeNotSupportedException(ex.getMessage());
    }
    if (contentType == null) {
        noContentType = true;
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }
    Class<?> contextClass = parameter.getContainingClass();
    Class<T> targetClass = targetType instanceof Class ? (Class<T>) targetType : null;
    if (targetClass == null) {
        ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
        targetClass = (Class<T>) resolvableType.resolve();
    }
    Object body = NO_VALUE;
    EmptyBodyCheckingHttpInputMessage message = null;
    try {
        message = new EmptyBodyCheckingHttpInputMessage(context);
        RequestResponseBodyAdviceChain adviceChain = getAdvice();
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
            GenericHttpMessageConverter<?> genericConverter = converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null;
            if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) : targetClass != null && converter.canRead(targetClass, contentType)) {
                if (message.hasBody()) {
                    HttpInputMessage msgToUse = adviceChain.beforeBodyRead(message, parameter, targetType, converterType);
                    body = genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) : ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse);
                    body = adviceChain.afterBodyRead(body, msgToUse, parameter, targetType, converterType);
                } else {
                    body = adviceChain.handleEmptyBody(null, message, parameter, targetType, converterType);
                }
                break;
            }
        }
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("I/O error while reading input message", ex, context);
    } finally {
        if (message != null && message.hasBody()) {
            closeStreamIfNecessary(message.getBody());
        }
    }
    if (body == NO_VALUE) {
        HttpMethod httpMethod = context.getMethod();
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && !message.hasBody())) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes(targetClass != null ? targetClass : Object.class));
    }
    MediaType selectedContentType = contentType;
    Object theBody = body;
    LogFormatUtils.traceDebug(log, traceOn -> {
        String formatted = LogFormatUtils.formatValue(theBody, !traceOn);
        return "Read \"" + selectedContentType + "\" to [" + formatted + "]";
    });
    return body;
}
Also used : HttpInputMessage(cn.taketoday.http.HttpInputMessage) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(cn.taketoday.web.HttpMediaTypeNotSupportedException) HttpMessageNotReadableException(cn.taketoday.http.converter.HttpMessageNotReadableException) HttpMessageConverter(cn.taketoday.http.converter.HttpMessageConverter) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) MediaType(cn.taketoday.http.MediaType) ResolvableType(cn.taketoday.core.ResolvableType) HttpMethod(cn.taketoday.http.HttpMethod) InvalidMediaTypeException(cn.taketoday.http.InvalidMediaTypeException) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) Nullable(cn.taketoday.lang.Nullable)

Aggregations

HttpInputMessage (cn.taketoday.http.HttpInputMessage)3 GenericHttpMessageConverter (cn.taketoday.http.converter.GenericHttpMessageConverter)3 TypeReference (cn.taketoday.core.TypeReference)2 HttpEntity (cn.taketoday.http.HttpEntity)2 HttpHeaders (cn.taketoday.http.HttpHeaders)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 List (java.util.List)2 Test (org.junit.jupiter.api.Test)2 ResolvableType (cn.taketoday.core.ResolvableType)1 HttpMethod (cn.taketoday.http.HttpMethod)1 InvalidMediaTypeException (cn.taketoday.http.InvalidMediaTypeException)1 MediaType (cn.taketoday.http.MediaType)1 HttpMessageConverter (cn.taketoday.http.converter.HttpMessageConverter)1 HttpMessageNotReadableException (cn.taketoday.http.converter.HttpMessageNotReadableException)1 Nullable (cn.taketoday.lang.Nullable)1 HttpMediaTypeNotSupportedException (cn.taketoday.web.HttpMediaTypeNotSupportedException)1 IOException (java.io.IOException)1