Search in sources :

Example 11 with TypeReference

use of cn.taketoday.core.TypeReference in project today-framework by TAKETODAY.

the class MappingJackson2HttpMessageConverterTests method readAndWriteParameterizedType.

@Test
@SuppressWarnings("unchecked")
public void readAndWriteParameterizedType() throws Exception {
    TypeReference<List<MyBean>> beansList = new TypeReference<List<MyBean>>() {
    };
    String body = "[{" + "\"bytes\":\"AQI=\"," + "\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42," + "\"string\":\"Foo\"," + "\"bool\":true," + "\"fraction\":42.0}]";
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
    inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), null, inputMessage);
    assertThat(results.size()).isEqualTo(1);
    MyBean result = results.get(0);
    assertThat(result.getString()).isEqualTo("Foo");
    assertThat(result.getNumber()).isEqualTo(42);
    assertThat(result.getFraction()).isCloseTo(42F, within(0F));
    assertThat(result.getArray()).isEqualTo(new String[] { "Foo", "Bar" });
    assertThat(result.isBool()).isTrue();
    assertThat(result.getBytes()).isEqualTo(new byte[] { 0x1, 0x2 });
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    converter.write(results, beansList.getType(), new MediaType("application", "json"), outputMessage);
    JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true);
}
Also used : MockHttpInputMessage(cn.taketoday.http.MockHttpInputMessage) MockHttpOutputMessage(cn.taketoday.http.MockHttpOutputMessage) MediaType(cn.taketoday.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(cn.taketoday.core.TypeReference) Test(org.junit.jupiter.api.Test)

Example 12 with TypeReference

use of cn.taketoday.core.TypeReference in project today-framework by TAKETODAY.

the class MappingJackson2HttpMessageConverterTests method writeParameterizedBaseType.

@Test
@SuppressWarnings("unchecked")
public void writeParameterizedBaseType() throws Exception {
    TypeReference<List<MyBean>> beansList = new TypeReference<List<MyBean>>() {
    };
    TypeReference<List<MyBase>> baseList = new TypeReference<List<MyBase>>() {
    };
    String body = "[{" + "\"bytes\":\"AQI=\"," + "\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42," + "\"string\":\"Foo\"," + "\"bool\":true," + "\"fraction\":42.0}]";
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
    inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), null, inputMessage);
    assertThat(results.size()).isEqualTo(1);
    MyBean result = results.get(0);
    assertThat(result.getString()).isEqualTo("Foo");
    assertThat(result.getNumber()).isEqualTo(42);
    assertThat(result.getFraction()).isCloseTo(42F, within(0F));
    assertThat(result.getArray()).isEqualTo(new String[] { "Foo", "Bar" });
    assertThat(result.isBool()).isTrue();
    assertThat(result.getBytes()).isEqualTo(new byte[] { 0x1, 0x2 });
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage);
    JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true);
}
Also used : MockHttpInputMessage(cn.taketoday.http.MockHttpInputMessage) MockHttpOutputMessage(cn.taketoday.http.MockHttpOutputMessage) MediaType(cn.taketoday.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(cn.taketoday.core.TypeReference) Test(org.junit.jupiter.api.Test)

Example 13 with TypeReference

use of cn.taketoday.core.TypeReference 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 14 with TypeReference

use of cn.taketoday.core.TypeReference in project today-framework by TAKETODAY.

the class HttpMessageConverterExtractorTests method generics.

@Test
@SuppressWarnings("unchecked")
void generics() throws IOException {
    responseHeaders.setContentType(contentType);
    String expected = "Foo";
    TypeReference<List<String>> reference = new TypeReference<List<String>>() {
    };
    Type type = reference.getType();
    GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
    HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor<List<String>>(type, asList(converter));
    given(response.getStatusCode()).willReturn(HttpStatus.OK);
    given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
    given(response.getHeaders()).willReturn(responseHeaders);
    given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
    given(converter.canRead(type, null, contentType)).willReturn(true);
    given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);
    Object result = extractor.extractData(response);
    assertThat(result).isEqualTo(expected);
}
Also used : HttpInputMessage(cn.taketoday.http.HttpInputMessage) Type(java.lang.reflect.Type) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) MediaType(cn.taketoday.http.MediaType) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Arrays.asList(java.util.Arrays.asList) TypeReference(cn.taketoday.core.TypeReference) Test(org.junit.jupiter.api.Test)

Example 15 with TypeReference

use of cn.taketoday.core.TypeReference in project today-framework by TAKETODAY.

the class BodyInserters method fromProducer.

/**
 * Inserter to write the given producer of value(s) which must be a {@link Publisher}
 * or another producer adaptable to a {@code Publisher} via
 * {@link ReactiveAdapterRegistry}.
 * <p>Alternatively, consider using the {@code body} shortcuts on
 * {@link WebClient WebClient} and
 * {@link cn.taketoday.web.reactive.function.server.ServerResponse ServerResponse}.
 *
 * @param <T> the type of the body
 * @param producer the source of body value(s).
 * @param elementTypeRef the type of values to be produced
 * @return the inserter to write a producer
 * @since 4.0
 */
public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T producer, TypeReference<?> elementTypeRef) {
    Assert.notNull(producer, "'producer' must not be null");
    Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null");
    ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(producer.getClass());
    Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry");
    return (message, context) -> writeWithMessageWriters(message, context, producer, ResolvableType.fromType(elementTypeRef), adapter);
}
Also used : LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) Assert(cn.taketoday.lang.Assert) WebClient(cn.taketoday.web.reactive.function.client.WebClient) ServerSentEvent(cn.taketoday.http.codec.ServerSentEvent) Publisher(org.reactivestreams.Publisher) ReactiveAdapterRegistry(cn.taketoday.core.ReactiveAdapterRegistry) ResolvableType(cn.taketoday.core.ResolvableType) Resource(cn.taketoday.core.io.Resource) MultipartBodyBuilder(cn.taketoday.http.client.MultipartBodyBuilder) HttpMessageWriter(cn.taketoday.http.codec.HttpMessageWriter) ServerHttpResponse(cn.taketoday.http.server.reactive.ServerHttpResponse) Mono(reactor.core.publisher.Mono) Collectors(java.util.stream.Collectors) List(java.util.List) ReactiveAdapter(cn.taketoday.core.ReactiveAdapter) ReactiveHttpOutputMessage(cn.taketoday.http.ReactiveHttpOutputMessage) Nullable(cn.taketoday.lang.Nullable) DataBuffer(cn.taketoday.core.io.buffer.DataBuffer) MultiValueMap(cn.taketoday.core.MultiValueMap) HttpEntity(cn.taketoday.http.HttpEntity) TypeReference(cn.taketoday.core.TypeReference) MediaType(cn.taketoday.http.MediaType) ClientHttpRequest(cn.taketoday.http.client.reactive.ClientHttpRequest) ReactiveAdapter(cn.taketoday.core.ReactiveAdapter)

Aggregations

TypeReference (cn.taketoday.core.TypeReference)30 Test (org.junit.jupiter.api.Test)28 List (java.util.List)22 MediaType (cn.taketoday.http.MediaType)16 ArrayList (java.util.ArrayList)16 MockHttpOutputMessage (cn.taketoday.http.MockHttpOutputMessage)14 MockHttpInputMessage (cn.taketoday.http.MockHttpInputMessage)12 DataBuffer (cn.taketoday.core.io.buffer.DataBuffer)6 HttpEntity (cn.taketoday.http.HttpEntity)6 Resource (cn.taketoday.core.io.Resource)4 DefaultDataBuffer (cn.taketoday.core.io.buffer.DefaultDataBuffer)4 HttpHeaders (cn.taketoday.http.HttpHeaders)4 HttpInputMessage (cn.taketoday.http.HttpInputMessage)4 DecoderHttpMessageReader (cn.taketoday.http.codec.DecoderHttpMessageReader)4 HttpMessageReader (cn.taketoday.http.codec.HttpMessageReader)4 HttpMessageWriter (cn.taketoday.http.codec.HttpMessageWriter)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 DefaultMultiValueMap (cn.taketoday.core.DefaultMultiValueMap)2 LinkedMultiValueMap (cn.taketoday.core.LinkedMultiValueMap)2 MultiValueMap (cn.taketoday.core.MultiValueMap)2