Support content negotiation for RFC 7807

Closes gh-28189
This commit is contained in:
rstoyanchev
2022-05-09 18:31:47 +01:00
parent f3fd8f9e1d
commit 78ab4d7118
10 changed files with 228 additions and 33 deletions

View File

@@ -111,14 +111,25 @@ public abstract class HandlerResultHandlerSupport implements Ordered {
}
/**
* Select the best media type for the current request through a content negotiation algorithm.
* Select the best media type for the current request through a content
* negotiation algorithm.
* @param exchange the current request
* @param producibleTypesSupplier the media types that can be produced for the current request
* @param producibleTypesSupplier the media types producible for the request
* @return the selected media type, or {@code null} if none
*/
@Nullable
protected MediaType selectMediaType(ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier) {
return selectMediaType(exchange, producibleTypesSupplier, getAcceptableTypes(exchange));
}
/**
* Variant of {@link #selectMediaType(ServerWebExchange, Supplier)} with a
* given list of requested (acceptable) media types.
*/
@Nullable
protected MediaType selectMediaType(
ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier) {
ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier,
List<MediaType> acceptableTypes) {
MediaType contentType = exchange.getResponse().getHeaders().getContentType();
if (contentType != null && contentType.isConcrete()) {
@@ -128,7 +139,6 @@ public abstract class HandlerResultHandlerSupport implements Ordered {
return contentType;
}
List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 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.
@@ -17,6 +17,7 @@
package org.springframework.web.reactive.result.method.annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
@@ -32,6 +33,7 @@ import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Hints;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
@@ -57,6 +59,9 @@ public abstract class AbstractMessageWriterResultHandler extends HandlerResultHa
private final List<HttpMessageWriter<?>> messageWriters;
private final List<MediaType> problemMediaTypes =
Arrays.asList(MediaType.APPLICATION_PROBLEM_JSON, MediaType.APPLICATION_PROBLEM_XML);
/**
* Constructor with {@link HttpMessageWriter HttpMessageWriters} and a
@@ -161,6 +166,12 @@ public abstract class AbstractMessageWriterResultHandler extends HandlerResultHa
}
throw ex;
}
// Fall back on RFC 7807 format for ProblemDetail
if (bestMediaType == null && elementType.toClass().equals(ProblemDetail.class)) {
bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType), this.problemMediaTypes);
}
if (bestMediaType != null) {
String logPrefix = exchange.getLogPrefix();
if (logger.isDebugEnabled()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 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.
@@ -16,6 +16,7 @@
package org.springframework.web.reactive.result.method.annotation;
import java.net.URI;
import java.util.List;
import reactor.core.publisher.Mono;
@@ -23,6 +24,8 @@ import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.HandlerResult;
@@ -83,6 +86,13 @@ public class ResponseBodyResultHandler extends AbstractMessageWriterResultHandle
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
Object body = result.getReturnValue();
MethodParameter bodyTypeParameter = result.getReturnTypeSource();
if (body instanceof ProblemDetail detail) {
exchange.getResponse().setStatusCode(HttpStatusCode.valueOf(detail.getStatus()));
if (detail.getInstance() == null) {
URI path = URI.create(exchange.getRequest().getPath().value());
detail.setInstance(path);
}
}
return writeBody(body, bodyTypeParameter, exchange);
}

View File

@@ -17,6 +17,7 @@
package org.springframework.web.reactive.result.method.annotation;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -25,14 +26,19 @@ import io.reactivex.rxjava3.core.Single;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.codec.ByteBufferEncoder;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@@ -40,8 +46,11 @@ import org.springframework.web.method.HandlerMethod;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.get;
import static org.springframework.web.testfixture.method.ResolvableMethod.on;
/**
@@ -82,7 +91,7 @@ public class ResponseBodyResultHandlerTests {
testSupports(controller, method);
method = on(TestController.class).annotNotPresent(ResponseBody.class).resolveMethod("doWork");
HandlerResult handlerResult = getHandlerResult(controller, method);
HandlerResult handlerResult = getHandlerResult(controller, null, method);
assertThat(this.resultHandler.supports(handlerResult)).isFalse();
}
@@ -105,13 +114,42 @@ public class ResponseBodyResultHandlerTests {
}
private void testSupports(Object controller, Method method) {
HandlerResult handlerResult = getHandlerResult(controller, method);
HandlerResult handlerResult = getHandlerResult(controller, null, method);
assertThat(this.resultHandler.supports(handlerResult)).isTrue();
}
private HandlerResult getHandlerResult(Object controller, Method method) {
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
return new HandlerResult(handlerMethod, null, handlerMethod.getReturnType());
@Test
void problemDetailContentNegotiation() {
// Default
MockServerWebExchange exchange = MockServerWebExchange.from(get("/path"));
testProblemDetailMediaType(exchange, MediaType.APPLICATION_PROBLEM_JSON);
// JSON requested
exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON));
testProblemDetailMediaType(exchange, MediaType.APPLICATION_JSON);
// No match fallback
exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_PDF));
testProblemDetailMediaType(exchange, MediaType.APPLICATION_PROBLEM_JSON);
}
private void testProblemDetailMediaType(MockServerWebExchange exchange, MediaType expectedMediaType) {
ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
Method method = on(TestRestController.class).returning(ProblemDetail.class).resolveMethod();
HandlerResult result = getHandlerResult(new TestRestController(), problemDetail, method);
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(expectedMediaType);
assertResponseBody(exchange,
"{\"type\":\"about:blank\"," +
"\"title\":\"Bad Request\"," +
"\"status\":400," +
"\"detail\":null," +
"\"instance\":\"/path\"}");
}
@Test
@@ -119,6 +157,17 @@ public class ResponseBodyResultHandlerTests {
assertThat(this.resultHandler.getOrder()).isEqualTo(100);
}
private HandlerResult getHandlerResult(Object controller, @Nullable Object returnValue, Method method) {
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
return new HandlerResult(handlerMethod, returnValue, handlerMethod.getReturnType());
}
private void assertResponseBody(MockServerWebExchange exchange, @Nullable String responseBody) {
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith(buf -> assertThat(buf.toString(UTF_8)).isEqualTo(responseBody))
.expectComplete()
.verify();
}
@RestController
@@ -142,6 +191,11 @@ public class ResponseBodyResultHandlerTests {
public Completable handleToCompletable() {
return null;
}
public ProblemDetail handleToProblemDetail() {
return null;
}
}