Add handler method parameter and result converters

This commit introduces the following changes:
 - Publisher -> Observable/Stream/etc. conversion is now managed
    in a dedicated ConversionService instead of directly in
    RequestBodyArgumentResolver and ResponseBodyResultHandler
 - More isolated logic that decides if the stream should be
    serialized as a JSON array or not
 - Publisher<ByteBuffer> are now handled by regular
   ByteBufferEncoder and ByteBufferDecoder
 - Handle Publisher<Void> return value properly
 - Ensure that the headers are properly written even for response
   without body
 - Improve JsonObjectEncoder to autodetect JSON arrays
This commit is contained in:
Sebastien Deleuze
2015-10-19 17:00:52 +02:00
parent cf2c1514af
commit adc50bbfb9
32 changed files with 758 additions and 202 deletions

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.reactive.codec.decoder;
import java.nio.ByteBuffer;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.io.buffer.Buffer;
import reactor.rx.Stream;
import reactor.rx.Streams;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
/**
* @author Sebastien Deleuze
*/
public class ByteBufferDecoderTests {
private final ByteBufferDecoder decoder = new ByteBufferDecoder();
@Test
public void canDecode() {
assertTrue(decoder.canDecode(ResolvableType.forClass(ByteBuffer.class), MediaType.TEXT_PLAIN));
assertFalse(decoder.canDecode(ResolvableType.forClass(Integer.class), MediaType.TEXT_PLAIN));
assertTrue(decoder.canDecode(ResolvableType.forClass(ByteBuffer.class), MediaType.APPLICATION_JSON));
}
@Test
public void decode() throws InterruptedException {
ByteBuffer fooBuffer = Buffer.wrap("foo").byteBuffer();
ByteBuffer barBuffer = Buffer.wrap("bar").byteBuffer();
Stream<ByteBuffer> source = Streams.just(fooBuffer, barBuffer);
List<ByteBuffer> results = Streams.wrap(decoder.decode(source,
ResolvableType.forClassWithGenerics(Publisher.class, ByteBuffer.class), null)).toList().await();
assertEquals(2, results.size());
assertEquals(fooBuffer, results.get(0));
assertEquals(barBuffer, results.get(1));
}
}

View File

@@ -31,9 +31,35 @@ import reactor.rx.Streams;
*/
public class JsonObjectDecoderTests {
@Test
public void decodeSingleChunkToJsonObject() throws InterruptedException {
JsonObjectDecoder decoder = new JsonObjectDecoder();
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer());
List<String> results = Streams.wrap(decoder.decode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
chunk.get(b);
return new String(b, StandardCharsets.UTF_8);
}).toList().await();
assertEquals(1, results.size());
assertEquals("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}", results.get(0));
}
@Test
public void decodeMultipleChunksToJsonObject() throws InterruptedException {
JsonObjectDecoder decoder = new JsonObjectDecoder();
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("{\"foo\": \"foofoo\"").byteBuffer(), Buffer.wrap(", \"bar\": \"barbar\"}").byteBuffer());
List<String> results = Streams.wrap(decoder.decode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
chunk.get(b);
return new String(b, StandardCharsets.UTF_8);
}).toList().await();
assertEquals(1, results.size());
assertEquals("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}", results.get(0));
}
@Test
public void decodeSingleChunkToArray() throws InterruptedException {
JsonObjectDecoder decoder = new JsonObjectDecoder(true);
JsonObjectDecoder decoder = new JsonObjectDecoder();
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("[{\"foo\": \"foofoo\", \"bar\": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}]").byteBuffer());
List<String> results = Streams.wrap(decoder.decode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
@@ -47,7 +73,7 @@ public class JsonObjectDecoderTests {
@Test
public void decodeMultipleChunksToArray() throws InterruptedException {
JsonObjectDecoder decoder = new JsonObjectDecoder(true);
JsonObjectDecoder decoder = new JsonObjectDecoder();
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("[{\"foo\": \"foofoo\", \"bar\"").byteBuffer(), Buffer.wrap(": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}]").byteBuffer());
List<String> results = Streams.wrap(decoder.decode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];

View File

@@ -23,13 +23,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.io.buffer.Buffer;
import reactor.rx.Stream;
import reactor.rx.Streams;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
import org.springframework.reactive.codec.Pojo;
/**
* @author Sebastien Deleuze
@@ -40,15 +40,16 @@ public class StringDecoderTests {
@Test
public void canDecode() {
assertTrue(decoder.canDecode(null, MediaType.TEXT_PLAIN));
assertFalse(decoder.canDecode(null, MediaType.APPLICATION_JSON));
assertTrue(decoder.canDecode(ResolvableType.forClass(String.class), MediaType.TEXT_PLAIN));
assertFalse(decoder.canDecode(ResolvableType.forClass(Integer.class), MediaType.TEXT_PLAIN));
assertFalse(decoder.canDecode(ResolvableType.forClass(String.class), MediaType.APPLICATION_JSON));
}
@Test
public void decode() throws InterruptedException {
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("foo").byteBuffer(), Buffer.wrap("bar").byteBuffer());
List<String> results = Streams.wrap(decoder.decode(source, ResolvableType.forClass(Pojo.class), null))
.toList().await();
List<String> results = Streams.wrap(decoder.decode(source,
ResolvableType.forClassWithGenerics(Publisher.class, String.class), null)).toList().await();
assertEquals(2, results.size());
assertEquals("foo", results.get(0));
assertEquals("bar", results.get(1));

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.reactive.codec.encoder;
import java.nio.ByteBuffer;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.io.buffer.Buffer;
import reactor.rx.Stream;
import reactor.rx.Streams;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
/**
* @author Sebastien Deleuze
*/
public class ByteBufferDecoderEncoder {
private final ByteBufferEncoder encoder = new ByteBufferEncoder();
@Test
public void canDecode() {
assertTrue(encoder.canEncode(ResolvableType.forClass(ByteBuffer.class), MediaType.TEXT_PLAIN));
assertFalse(encoder.canEncode(ResolvableType.forClass(Integer.class), MediaType.TEXT_PLAIN));
assertTrue(encoder.canEncode(ResolvableType.forClass(ByteBuffer.class), MediaType.APPLICATION_JSON));
}
@Test
public void decode() throws InterruptedException {
ByteBuffer fooBuffer = Buffer.wrap("foo").byteBuffer();
ByteBuffer barBuffer = Buffer.wrap("bar").byteBuffer();
Stream<ByteBuffer> source = Streams.just(fooBuffer, barBuffer);
List<ByteBuffer> results = Streams.wrap(encoder.encode(source,
ResolvableType.forClassWithGenerics(Publisher.class, ByteBuffer.class), null)).toList().await();
assertEquals(2, results.size());
assertEquals(fooBuffer, results.get(0));
assertEquals(barBuffer, results.get(1));
}
}

View File

@@ -32,9 +32,24 @@ import reactor.rx.Streams;
public class JsonObjectEncoderTests {
@Test
public void encodeToArray() throws InterruptedException {
public void encodeSingleElement() throws InterruptedException {
JsonObjectEncoder encoder = new JsonObjectEncoder();
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer(), Buffer.wrap("{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}").byteBuffer());
Stream<ByteBuffer> source = Streams.just(Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer());
List<String> results = Streams.wrap(encoder.encode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
chunk.get(b);
return new String(b, StandardCharsets.UTF_8);
}).toList().await();
String result = String.join("", results);
assertEquals("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}", result);
}
@Test
public void encodeTwoElements() throws InterruptedException {
JsonObjectEncoder encoder = new JsonObjectEncoder();
Stream<ByteBuffer> source = Streams.just(
Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer(),
Buffer.wrap("{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}").byteBuffer());
List<String> results = Streams.wrap(encoder.encode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
chunk.get(b);
@@ -44,4 +59,21 @@ public class JsonObjectEncoderTests {
assertEquals("[{\"foo\": \"foofoo\", \"bar\": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}]", result);
}
@Test
public void encodeThreeElements() throws InterruptedException {
JsonObjectEncoder encoder = new JsonObjectEncoder();
Stream<ByteBuffer> source = Streams.just(
Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer(),
Buffer.wrap("{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}").byteBuffer(),
Buffer.wrap("{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}").byteBuffer()
);
List<String> results = Streams.wrap(encoder.encode(source, null, null)).map(chunk -> {
byte[] b = new byte[chunk.remaining()];
chunk.get(b);
return new String(b, StandardCharsets.UTF_8);
}).toList().await();
String result = String.join("", results);
assertEquals("[{\"foo\": \"foofoo\", \"bar\": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"},{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}]", result);
}
}

View File

@@ -23,8 +23,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.rx.Streams;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
/**
@@ -36,8 +38,9 @@ public class StringEncoderTests {
@Test
public void canWrite() {
assertTrue(encoder.canEncode(null, MediaType.TEXT_PLAIN));
assertFalse(encoder.canEncode(null, MediaType.APPLICATION_JSON));
assertTrue(encoder.canEncode(ResolvableType.forClass(String.class), MediaType.TEXT_PLAIN));
assertFalse(encoder.canEncode(ResolvableType.forClass(Integer.class), MediaType.TEXT_PLAIN));
assertFalse(encoder.canEncode(ResolvableType.forClass(String.class), MediaType.APPLICATION_JSON));
}
@Test

View File

@@ -17,13 +17,20 @@ package org.springframework.reactive.web.dispatch.method.annotation;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.ResolvableType;
import reactor.io.buffer.Buffer;
import reactor.rx.Promise;
import reactor.rx.Promises;
import reactor.rx.Stream;
@@ -32,13 +39,16 @@ import rx.Observable;
import rx.Single;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.reactive.codec.encoder.ByteBufferEncoder;
import org.springframework.reactive.codec.encoder.JacksonJsonEncoder;
import org.springframework.reactive.codec.encoder.JsonObjectEncoder;
import org.springframework.reactive.codec.encoder.StringEncoder;
import org.springframework.reactive.web.dispatch.DispatcherHandler;
import org.springframework.reactive.web.dispatch.SimpleHandlerResultHandler;
import org.springframework.reactive.web.http.AbstractHttpHandlerIntegrationTests;
import org.springframework.reactive.web.http.HttpHandler;
import org.springframework.stereotype.Controller;
@@ -52,18 +62,25 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @author Stephane Maldini
*/
public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrationTests {
private TestController controller;
@Override
protected HttpHandler createHttpHandler() {
StaticWebApplicationContext wac = new StaticWebApplicationContext();
DefaultListableBeanFactory factory = wac.getDefaultListableBeanFactory();
wac.registerSingleton("handlerMapping", RequestMappingHandlerMapping.class);
wac.registerSingleton("handlerAdapter", RequestMappingHandlerAdapter.class);
wac.getDefaultListableBeanFactory().registerSingleton("responseBodyResultHandler",
new ResponseBodyResultHandler(Arrays.asList(new StringEncoder(), new JacksonJsonEncoder()), Arrays.asList(new JsonObjectEncoder())));
wac.registerSingleton("controller", TestController.class);
factory.registerSingleton("responseBodyResultHandler",
new ResponseBodyResultHandler(Arrays.asList(new ByteBufferEncoder(), new StringEncoder(), new JacksonJsonEncoder()), Arrays.asList
(new JsonObjectEncoder())));
wac.registerSingleton("simpleResultHandler", SimpleHandlerResultHandler.class);
this.controller = new TestController();
factory.registerSingleton("controller", this.controller);
wac.refresh();
DispatcherHandler dispatcherHandler = new DispatcherHandler();
@@ -83,6 +100,30 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
assertEquals("Hello George!", response.getBody());
}
@Test
public void rawPojoResponse() throws Exception {
RestTemplate restTemplate = new RestTemplate();
URI url = new URI("http://localhost:" + port + "/raw");
RequestEntity<Void> request = RequestEntity.get(url).build();
Person person = restTemplate.exchange(request, Person.class).getBody();
assertEquals(new Person("Robert"), person);
}
@Test
public void rawHelloResponse() throws Exception {
RestTemplate restTemplate = new RestTemplate();
URI url = new URI("http://localhost:" + port + "/raw-observable");
RequestEntity<Void> request = RequestEntity.get(url).build();
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
assertEquals("Hello!", response.getBody());
}
@Test
public void serializeAsPojo() throws Exception {
serializeAsPojo("http://localhost:" + port + "/person");
@@ -153,6 +194,19 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
capitalizePojo("http://localhost:" + port + "/promise-capitalize");
}
@Test
public void create() throws Exception {
RestTemplate restTemplate = new RestTemplate();
URI url = new URI("http://localhost:" + port + "/create");
List<Person> persons = Arrays.asList(new Person("Robert"), new Person("Marie"));
RequestEntity<List<Person>> request = RequestEntity.post(url).contentType(MediaType.APPLICATION_JSON).body(persons);
ResponseEntity<Void> response = restTemplate.exchange(request, Void.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(2, this.controller.persons.size());
}
public void serializeAsPojo(String requestUrl) throws Exception {
RestTemplate restTemplate = new RestTemplate();
@@ -164,6 +218,17 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
assertEquals(new Person("Robert"), response.getBody());
}
public void postAsPojo(String requestUrl) throws Exception {
RestTemplate restTemplate = new RestTemplate();
URI url = new URI(requestUrl);
RequestEntity<Person> request = RequestEntity.post(url).accept(MediaType.APPLICATION_JSON).body(new Person
("Robert"));
ResponseEntity<Person> response = restTemplate.exchange(request, Person.class);
assertEquals(new Person("Robert"), response.getBody());
}
public void serializeAsCollection(String requestUrl) throws Exception {
RestTemplate restTemplate = new RestTemplate();
@@ -214,6 +279,8 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
@SuppressWarnings("unused")
private static class TestController {
final List<Person> persons = new ArrayList<>();
@RequestMapping("/param")
@ResponseBody
public Publisher<String> handleWithParam(@RequestParam String name) {
@@ -232,6 +299,19 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
return CompletableFuture.completedFuture(new Person("Robert"));
}
@RequestMapping("/raw")
@ResponseBody
public Publisher<ByteBuffer> rawResponseBody() {
JacksonJsonEncoder encoder = new JacksonJsonEncoder();
return encoder.encode(Streams.just(new Person("Robert")), ResolvableType.forClass(Person.class), MediaType.APPLICATION_JSON);
}
@RequestMapping("/raw-observable")
@ResponseBody
public Observable<ByteBuffer> rawObservableResponseBody() {
return Observable.just(Buffer.wrap("Hello!").byteBuffer());
}
@RequestMapping("/single")
@ResponseBody
public Single<Person> singleResponseBody() {
@@ -322,6 +402,13 @@ public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrati
});
}
@RequestMapping("/create")
public Publisher<Void> create(@RequestBody Stream<Person> personStream) {
return personStream.toList().onSuccess(personList -> persons.addAll(personList)).after();
}
//TODO add mixed and T request mappings tests
}
private static class Person {

View File

@@ -44,7 +44,7 @@ public class ResponseBodyResultHandlerTests {
assertTrue(resultHandler.supports(new HandlerResult(publisherStringMethod, null)));
HandlerMethod publisherVoidMethod = new HandlerMethod(controller, TestController.class.getMethod("publisherVoid"));
assertFalse(resultHandler.supports(new HandlerResult(publisherVoidMethod, null)));
assertTrue(resultHandler.supports(new HandlerResult(publisherVoidMethod, null)));
}