Encoder/Decoder based payload serialization

See gh-21987
This commit is contained in:
Rossen Stoyanchev
2019-01-25 17:47:57 -05:00
parent bcf4f3911b
commit e3e1ffc986
12 changed files with 869 additions and 7 deletions

View File

@@ -0,0 +1,208 @@
/*
* Copyright 2002-2019 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.messaging.handler.annotation.support.reactive;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Decoder;
import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException;
import org.springframework.messaging.handler.invocation.ResolvableMethod;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.util.MimeTypeUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import static org.junit.Assert.*;
/**
* Unit tests for {@link PayloadMethodArgumentResolver}.
*
* @author Rossen Stoyanchev
*/
public class PayloadMethodArgumentResolverTests {
private final List<Decoder<?>> decoders = new ArrayList<>();
private final ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
@Test
public void supportsParameter() {
boolean useDefaultResolution = true;
PayloadMethodArgumentResolver resolver = createResolver(null, useDefaultResolution);
assertTrue(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg()));
assertTrue(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class)));
useDefaultResolution = false;
resolver = createResolver(null, useDefaultResolution);
assertTrue(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg()));
assertFalse(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class)));
}
@Test
public void emptyBodyWhenRequired() {
MethodParameter param = this.testMethod.arg(ResolvableType.forClassWithGenerics(Mono.class, String.class));
Mono<Object> mono = resolveValue(param, Mono.empty(), null);
StepVerifier.create(mono)
.consumeErrorWith(ex -> {
assertEquals(MethodArgumentResolutionException.class, ex.getClass());
assertTrue(ex.getMessage(), ex.getMessage().contains("Payload content is missing"));
})
.verify();
}
@Test
public void emptyBodyWhenNotRequired() {
MethodParameter param = this.testMethod.annotPresent(Payload.class).arg();
assertNull(resolveValue(param, Mono.empty(), null));
}
@Test
public void stringMono() {
String body = "foo";
MethodParameter param = this.testMethod.arg(ResolvableType.forClassWithGenerics(Mono.class, String.class));
Mono<DataBuffer> value = Mono.delay(Duration.ofMillis(10)).map(aLong -> toDataBuffer(body));
Mono<Object> mono = resolveValue(param, value, null);
assertEquals(body, mono.block());
}
@Test
public void stringFlux() {
List<String> body = Arrays.asList("foo", "bar");
ResolvableType type = ResolvableType.forClassWithGenerics(Flux.class, String.class);
MethodParameter param = this.testMethod.arg(type);
Flux<Object> flux = resolveValue(param, Flux.fromIterable(body)
.delayElements(Duration.ofMillis(10)).map(value -> toDataBuffer(value + "\n")), null);
assertEquals(body, flux.collectList().block());
}
@Test
public void string() {
String body = "foo";
MethodParameter param = this.testMethod.annotNotPresent(Payload.class).arg(String.class);
Object value = resolveValue(param, Mono.just(toDataBuffer(body)), null);
assertEquals(body, value);
}
@Test
public void validateStringMono() {
ResolvableType type = ResolvableType.forClassWithGenerics(Mono.class, String.class);
MethodParameter param = this.testMethod.arg(type);
Mono<Object> mono = resolveValue(param, Mono.just(toDataBuffer("12345")), new TestValidator());
StepVerifier.create(mono).expectNextCount(0)
.expectError(MethodArgumentNotValidException.class).verify();
}
@Test
public void validateStringFlux() {
ResolvableType type = ResolvableType.forClassWithGenerics(Flux.class, String.class);
MethodParameter param = this.testMethod.arg(type);
Flux<Object> flux = resolveValue(param, Flux.just(toDataBuffer("12345678\n12345")), new TestValidator());
StepVerifier.create(flux)
.expectNext("12345678")
.expectError(MethodArgumentNotValidException.class)
.verify();
}
private DataBuffer toDataBuffer(String value) {
return new DefaultDataBufferFactory().wrap(value.getBytes(StandardCharsets.UTF_8));
}
@SuppressWarnings("unchecked")
@Nullable
private <T> T resolveValue(MethodParameter param, Publisher<DataBuffer> content, Validator validator) {
Message<?> message = new GenericMessage<>(content,
Collections.singletonMap(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN));
Mono<Object> result = createResolver(validator, true).resolveArgument(param, message);
Object value = result.block(Duration.ofSeconds(5));
if (value != null) {
Class<?> expectedType = param.getParameterType();
assertTrue("Unexpected return value type: " + value, expectedType.isAssignableFrom(value.getClass()));
}
return (T) value;
}
private PayloadMethodArgumentResolver createResolver(@Nullable Validator validator, boolean useDefaultResolution) {
if (this.decoders.isEmpty()) {
this.decoders.add(StringDecoder.allMimeTypes());
}
List<StringDecoder> decoders = Collections.singletonList(StringDecoder.allMimeTypes());
return new PayloadMethodArgumentResolver(decoders, validator, null, useDefaultResolution) {};
}
@SuppressWarnings("unused")
private void handle(
@Validated Mono<String> valueMono,
@Validated Flux<String> valueFlux,
@Payload(required = false) String optionalValue,
String value) {
}
private static class TestValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(String.class);
}
@Override
public void validate(@Nullable Object target, Errors errors) {
if (target instanceof String && ((String) target).length() < 8) {
errors.reject("Invalid length");
}
}
}
}

View File

@@ -23,7 +23,6 @@ import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.ResolvableMethod;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

View File

@@ -166,7 +166,7 @@ public class MethodMessageHandlerTests {
this.method = "secondBestMatch";
}
public void illegalStateException(IllegalStateException exception) {
public void handleIllegalStateException(IllegalStateException exception) {
this.method = "illegalStateException";
this.arguments.put("exception", exception);
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.messaging.handler;
package org.springframework.messaging.handler.invocation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@@ -57,7 +57,10 @@ import org.springframework.util.ReflectionUtils;
import static java.util.stream.Collectors.*;
/**
* Convenience class to resolve method parameters from hints.
* NOTE: This class is a replica of the same class in spring-web so it can
* be used for tests in spring-messaging.
*
* <p>Convenience class to resolve method parameters from hints.
*
* <h1>Background</h1>
*
@@ -120,7 +123,7 @@ import static java.util.stream.Collectors.*;
* </pre>
*
* @author Rossen Stoyanchev
* @since 5.0
* @since 5.2
*/
public class ResolvableMethod {
@@ -186,6 +189,7 @@ public class ResolvableMethod {
/**
* Filter on method arguments with annotation.
* See {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filter) {
@@ -298,6 +302,7 @@ public class ResolvableMethod {
/**
* Filter on annotated methods.
* See {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final Builder<T> annot(Predicate<Method>... filters) {
@@ -308,6 +313,7 @@ public class ResolvableMethod {
/**
* Filter on methods annotated with the given annotation type.
* @see #annot(Predicate[])
* See {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
@@ -524,6 +530,7 @@ public class ResolvableMethod {
/**
* Filter on method arguments with annotations.
* See {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filters) {
@@ -535,6 +542,7 @@ public class ResolvableMethod {
* Filter on method arguments that have the given annotations.
* @param annotationTypes the annotation types
* @see #annot(Predicate[])
* See {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {

View File

@@ -0,0 +1,154 @@
/*
* Copyright 2002-2019 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.messaging.handler.invocation.reactive;
import java.util.Collections;
import java.util.List;
import io.reactivex.Completable;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.codec.Encoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import static java.nio.charset.StandardCharsets.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.springframework.messaging.handler.invocation.ResolvableMethod.*;
/**
* Unit tests for {@link AbstractEncoderMethodReturnValueHandler}.
*
* @author Rossen Stoyanchev
*/
public class EncoderMethodReturnValueHandlerTests {
private final TestEncoderMethodReturnValueHandler handler = new TestEncoderMethodReturnValueHandler(
Collections.singletonList(CharSequenceEncoder.textPlainOnly()),
ReactiveAdapterRegistry.getSharedInstance());
private final Message<?> message = mock(Message.class);
@Test
public void stringReturnValue() {
MethodParameter parameter = on(TestController.class).resolveReturnType(String.class);
this.handler.handleReturnValue("foo", parameter, message).block();
Flux<DataBuffer> result = this.handler.encodedContent;
StepVerifier.create(result)
.consumeNextWith(buffer -> assertEquals("foo", DataBufferTestUtils.dumpString(buffer, UTF_8)))
.verifyComplete();
}
@Test
public void objectReturnValue() {
MethodParameter parameter = on(TestController.class).resolveReturnType(Object.class);
this.handler.handleReturnValue("foo", parameter, message).block();
Flux<DataBuffer> result = this.handler.encodedContent;
StepVerifier.create(result)
.consumeNextWith(buffer -> assertEquals("foo", DataBufferTestUtils.dumpString(buffer, UTF_8)))
.verifyComplete();
}
@Test
public void fluxStringReturnValue() {
MethodParameter parameter = on(TestController.class).resolveReturnType(Flux.class, String.class);
this.handler.handleReturnValue(Flux.just("foo", "bar"), parameter, message).block();
Flux<DataBuffer> result = this.handler.encodedContent;
StepVerifier.create(result)
.consumeNextWith(buffer -> assertEquals("foo", DataBufferTestUtils.dumpString(buffer, UTF_8)))
.consumeNextWith(buffer -> assertEquals("bar", DataBufferTestUtils.dumpString(buffer, UTF_8)))
.verifyComplete();
}
@Test
public void voidReturnValue() {
testVoidReturnType(null, on(TestController.class).resolveReturnType(void.class));
testVoidReturnType(Mono.empty(), on(TestController.class).resolveReturnType(Mono.class, Void.class));
testVoidReturnType(Completable.complete(), on(TestController.class).resolveReturnType(Completable.class));
}
private void testVoidReturnType(@Nullable Object value, MethodParameter bodyParameter) {
this.handler.handleReturnValue(value, bodyParameter, message).block();
Flux<DataBuffer> result = this.handler.encodedContent;
StepVerifier.create(result).expectComplete().verify();
}
@Test
public void noEncoder() {
MethodParameter parameter = on(TestController.class).resolveReturnType(Object.class);
this.handler.handleReturnValue(new Object(), parameter, message).block();
Flux<DataBuffer> result = this.handler.encodedContent;
StepVerifier.create(result)
.expectErrorMessage("No encoder for method 'object' parameter -1")
.verify();
}
@SuppressWarnings({"unused", "ConstantConditions"})
private static class TestController {
String string() { return null; }
Object object() { return null; }
Flux<String> fluxString() { return null; }
void voidReturn() { }
Mono<Void> monoVoid() { return null; }
Completable completable() { return null; }
}
private static class TestEncoderMethodReturnValueHandler extends AbstractEncoderMethodReturnValueHandler {
private Flux<DataBuffer> encodedContent;
public Flux<DataBuffer> getEncodedContent() {
return this.encodedContent;
}
protected TestEncoderMethodReturnValueHandler(List<Encoder<?>> encoders, ReactiveAdapterRegistry registry) {
super(encoders, registry);
}
@Override
protected Mono<Void> handleEncodedContent(
Flux<DataBuffer> encodedContent, MethodParameter returnType, Message<?> message) {
this.encodedContent = encodedContent;
return Mono.empty();
}
}
}

View File

@@ -29,8 +29,8 @@ import reactor.test.StepVerifier;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.ResolvableMethod;
import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException;
import org.springframework.messaging.handler.invocation.ResolvableMethod;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;