org.springframework.web.server.NotAcceptableStatusException Java Examples

The following examples show how to use org.springframework.web.server.NotAcceptableStatusException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	List<ProduceMediaTypeExpression> result = getMatchingExpressions(exchange);
	if (!CollectionUtils.isEmpty(result)) {
		return new ProducesRequestCondition(result, this);
	}
	else {
		try {
			if (MediaType.ALL.isPresentIn(getAcceptedMediaTypes(exchange))) {
				return EMPTY_CONDITION;
			}
		}
		catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
			// Ignore
		}
	}
	return null;
}
 
Example #2
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Compares this and another "produces" condition as follows:
 * <ol>
 * <li>Sort 'Accept' header media types by quality value via
 * {@link MediaType#sortByQualityValue(List)} and iterate the list.
 * <li>Get the first index of matching media types in each "produces"
 * condition first matching with {@link MediaType#equals(Object)} and
 * then with {@link MediaType#includes(MediaType)}.
 * <li>If a lower index is found, the condition at that index wins.
 * <li>If both indexes are equal, the media types at the index are
 * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
 * </ol>
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(ServerWebExchange)} and each instance
 * contains the matching producible media type expression only or
 * is otherwise empty.
 */
@Override
public int compareTo(ProducesRequestCondition other, ServerWebExchange exchange) {
	try {
		List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange);
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
			int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
			int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
			thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
			otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
			result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
		}
		return 0;
	}
	catch (NotAcceptableStatusException ex) {
		// should never happen
		throw new IllegalStateException("Cannot compare without having any requested media types", ex);
	}
}
 
Example #3
Source File: ProducesRequestCondition.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Compares this and another "produces" condition as follows:
 * <ol>
 * <li>Sort 'Accept' header media types by quality value via
 * {@link MediaType#sortByQualityValue(List)} and iterate the list.
 * <li>Get the first index of matching media types in each "produces"
 * condition first matching with {@link MediaType#equals(Object)} and
 * then with {@link MediaType#includes(MediaType)}.
 * <li>If a lower index is found, the condition at that index wins.
 * <li>If both indexes are equal, the media types at the index are
 * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
 * </ol>
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(ServerWebExchange)} and each instance
 * contains the matching producible media type expression only or
 * is otherwise empty.
 */
@Override
public int compareTo(ProducesRequestCondition other, ServerWebExchange exchange) {
	try {
		List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange);
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
			int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
			int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
			thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
			otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
			result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
		}
		return 0;
	}
	catch (NotAcceptableStatusException ex) {
		// should never happen
		throw new IllegalStateException("Cannot compare without having any requested media types", ex);
	}
}
 
Example #4
Source File: ParameterContentTypeResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	String key = exchange.getRequest().getQueryParams().getFirst(getParameterName());
	if (!StringUtils.hasText(key)) {
		return MEDIA_TYPE_ALL_LIST;
	}
	key = formatKey(key);
	MediaType match = this.mediaTypes.get(key);
	if (match == null) {
		match = MediaTypeFactory.getMediaType("filename." + key)
				.orElseThrow(() -> {
					List<MediaType> supported = new ArrayList<>(this.mediaTypes.values());
					return new NotAcceptableStatusException(supported);
				});
	}
	this.mediaTypes.putIfAbsent(key, match);
	return Collections.singletonList(match);
}
 
Example #5
Source File: ParameterContentTypeResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	String key = exchange.getRequest().getQueryParams().getFirst(getParameterName());
	if (!StringUtils.hasText(key)) {
		return MEDIA_TYPE_ALL_LIST;
	}
	key = formatKey(key);
	MediaType match = this.mediaTypes.get(key);
	if (match == null) {
		match = MediaTypeFactory.getMediaType("filename." + key)
				.orElseThrow(() -> {
					List<MediaType> supported = new ArrayList<>(this.mediaTypes.values());
					return new NotAcceptableStatusException(supported);
				});
	}
	this.mediaTypes.putIfAbsent(key, match);
	return Collections.singletonList(match);
}
 
Example #6
Source File: HeaderContentTypeResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	try {
		List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return (!CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST);
	}
	catch (InvalidMediaTypeException ex) {
		String value = exchange.getRequest().getHeaders().getFirst("Accept");
		throw new NotAcceptableStatusException(
				"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
	}
}
 
Example #7
Source File: NotAcceptableAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleMediaTypeNotAcceptable(
        final NotAcceptableStatusException exception,
        final ServerWebExchange request) {
    return create(Status.NOT_ACCEPTABLE, exception, request);
}
 
Example #8
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testMediaTypeNotAcceptable(String url) {
	ServerWebExchange exchange = MockServerWebExchange.from(get(url).accept(MediaType.APPLICATION_JSON));
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, NotAcceptableStatusException.class, ex ->
			assertEquals("Invalid supported producible media types",
					Collections.singletonList(new MediaType("application", "xml")),
					ex.getSupportedMediaTypes()));
}
 
Example #9
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-9603
public void getHandlerRequestMethodMatchFalsePositive() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/users").accept(MediaType.APPLICATION_XML));
	this.handlerMapping.registerHandler(new UserController());
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	StepVerifier.create(mono)
			.expectError(NotAcceptableStatusException.class)
			.verify();
}
 
Example #10
Source File: ViewResolutionResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void contentNegotiationWith406() {
	TestBean value = new TestBean("Joe");
	MethodParameter returnType = on(Handler.class).resolveReturnType(TestBean.class);
	HandlerResult handlerResult = new HandlerResult(new Object(), value, returnType, this.bindingContext);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));

	ViewResolutionResultHandler resultHandler = resultHandler(new TestViewResolver("account"));
	Mono<Void> mono = resultHandler.handleResult(exchange, handlerResult);
	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(NotAcceptableStatusException.class)
			.verify();
}
 
Example #11
Source File: ParameterContentTypeResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = NotAcceptableStatusException.class)
public void noMatchForKey() {
	ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(Collections.emptyMap());
	List<MediaType> mediaTypes = resolver.resolveMediaTypes(createExchange("blah"));

	assertEquals(0, mediaTypes.size());
}
 
Example #12
Source File: DispatcherHandlerErrorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void responseBodyMessageConversionError() {
	ServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest.post("/request-body").accept(APPLICATION_JSON).body("body"));

	Mono<Void> publisher = this.dispatcherHandler.handle(exchange);

	StepVerifier.create(publisher)
			.consumeErrorWith(error -> assertThat(error, instanceOf(NotAcceptableStatusException.class)))
			.verify();
}
 
Example #13
Source File: ProducesRequestCondition.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws NotAcceptableStatusException {
	List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange);
	for (MediaType acceptedMediaType : acceptedMediaTypes) {
		if (getMediaType().isCompatibleWith(acceptedMediaType)) {
			return true;
		}
	}
	return false;
}
 
Example #14
Source File: ProducesRequestCondition.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(this.expressions);
	result.removeIf(expression -> !expression.match(exchange));
	if (!result.isEmpty()) {
		return new ProducesRequestCondition(result, this.contentTypeResolver);
	}
	else {
		try {
			if (MediaType.ALL.isPresentIn(getAcceptedMediaTypes(exchange))) {
				return EMPTY_CONDITION;
			}
		}
		catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
			// Ignore
		}
	}
	return null;
}
 
Example #15
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void testMediaTypeNotAcceptable(String url) {
	ServerWebExchange exchange = MockServerWebExchange.from(get(url).accept(MediaType.APPLICATION_JSON));
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, NotAcceptableStatusException.class, ex ->
			assertEquals("Invalid supported producible media types",
					Collections.singletonList(new MediaType("application", "xml")),
					ex.getSupportedMediaTypes()));
}
 
Example #16
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-9603
public void getHandlerRequestMethodMatchFalsePositive() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/users").accept(MediaType.APPLICATION_XML));
	this.handlerMapping.registerHandler(new UserController());
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	StepVerifier.create(mono)
			.expectError(NotAcceptableStatusException.class)
			.verify();
}
 
Example #17
Source File: ViewResolutionResultHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void contentNegotiationWith406() {
	TestBean value = new TestBean("Joe");
	MethodParameter returnType = on(Handler.class).resolveReturnType(TestBean.class);
	HandlerResult handlerResult = new HandlerResult(new Object(), value, returnType, this.bindingContext);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));

	ViewResolutionResultHandler resultHandler = resultHandler(new TestViewResolver("account"));
	Mono<Void> mono = resultHandler.handleResult(exchange, handlerResult);
	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(NotAcceptableStatusException.class)
			.verify();
}
 
Example #18
Source File: ParameterContentTypeResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = NotAcceptableStatusException.class)
public void noMatchForKey() {
	ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(Collections.emptyMap());
	List<MediaType> mediaTypes = resolver.resolveMediaTypes(createExchange("blah"));

	assertEquals(0, mediaTypes.size());
}
 
Example #19
Source File: DispatcherHandlerErrorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void responseBodyMessageConversionError() {
	ServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest.post("/request-body").accept(APPLICATION_JSON).body("body"));

	Mono<Void> publisher = this.dispatcherHandler.handle(exchange);

	StepVerifier.create(publisher)
			.consumeErrorWith(error -> assertThat(error, instanceOf(NotAcceptableStatusException.class)))
			.verify();
}
 
Example #20
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws NotAcceptableStatusException {
	List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange);
	for (MediaType acceptedMediaType : acceptedMediaTypes) {
		if (getMediaType().isCompatibleWith(acceptedMediaType) && matchParameters(acceptedMediaType)) {
			return true;
		}
	}
	return false;
}
 
Example #21
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private List<MediaType> getAcceptedMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	List<MediaType> result = exchange.getAttribute(MEDIA_TYPES_ATTRIBUTE);
	if (result == null) {
		result = this.contentTypeResolver.resolveMediaTypes(exchange);
		exchange.getAttributes().put(MEDIA_TYPES_ATTRIBUTE, result);
	}
	return result;
}
 
Example #22
Source File: HeaderContentTypeResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	try {
		List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return (!CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST);
	}
	catch (InvalidMediaTypeException ex) {
		String value = exchange.getRequest().getHeaders().getFirst("Accept");
		throw new NotAcceptableStatusException(
				"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
	}
}
 
Example #23
Source File: ProducesRequestCondition.java    From java-technology-stack with MIT License 4 votes vote down vote up
private List<MediaType> getAcceptedMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	return this.contentTypeResolver.resolveMediaTypes(exchange);
}
 
Example #24
Source File: HeaderContentTypeResolverTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test(expected = NotAcceptableStatusException.class)
public void resolveMediaTypesParseError() throws Exception {
	String header = "textplain; q=0.5";
	this.resolver.resolveMediaTypes(
			MockServerWebExchange.from(MockServerHttpRequest.get("/").header("accept", header)));
}
 
Example #25
Source File: AbstractMediaTypeExpression.java    From java-technology-stack with MIT License 4 votes vote down vote up
protected abstract boolean matchMediaType(ServerWebExchange exchange)
throws NotAcceptableStatusException, UnsupportedMediaTypeStatusException;
 
Example #26
Source File: AbstractMessageWriterResultHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Write a given body to the response with {@link HttpMessageWriter}.
 * @param body the object to write
 * @param bodyParameter the {@link MethodParameter} of the body to write
 * @param actualParam the actual return type of the method that returned the value;
 * could be different from {@code bodyParameter} when processing {@code HttpEntity}
 * for example
 * @param exchange the current exchange
 * @return indicates completion or error
 * @since 5.0.2
 */
@SuppressWarnings({"unchecked", "rawtypes"})
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter,
		@Nullable MethodParameter actualParam, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve(), body);

	Publisher<?> publisher;
	ResolvableType elementType;
	if (adapter != null) {
		publisher = adapter.toPublisher(body);
		ResolvableType genericType = bodyType.getGeneric();
		elementType = getElementType(adapter, genericType);
	}
	else {
		publisher = Mono.justOrEmpty(body);
		elementType = (bodyType.toClass() == Object.class && body != null ?
				ResolvableType.forInstance(body) : bodyType);
	}

	if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
		return Mono.from((Publisher<Void>) publisher);
	}

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();
	MediaType bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType));
	if (bestMediaType != null) {
		String logPrefix = exchange.getLogPrefix();
		if (logger.isDebugEnabled()) {
			logger.debug(logPrefix +
					(publisher instanceof Mono ? "0..1" : "0..N") + " [" + elementType + "]");
		}
		for (HttpMessageWriter<?> writer : getMessageWriters()) {
			if (writer.canWrite(elementType, bestMediaType)) {
				return writer.write((Publisher) publisher, actualType, elementType, bestMediaType,
						request, response, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix));
			}
		}
	}
	else {
		if (getMediaTypesFor(elementType).isEmpty()) {
			return Mono.error(new IllegalStateException("No writer for : " + elementType));
		}
	}

	return Mono.error(new NotAcceptableStatusException(getMediaTypesFor(elementType)));
}
 
Example #27
Source File: HeaderContentTypeResolverTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test(expected = NotAcceptableStatusException.class)
public void resolveMediaTypesParseError() throws Exception {
	String header = "textplain; q=0.5";
	this.resolver.resolveMediaTypes(
			MockServerWebExchange.from(MockServerHttpRequest.get("/").header("accept", header)));
}
 
Example #28
Source File: AbstractMessageWriterResultHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Write a given body to the response with {@link HttpMessageWriter}.
 * @param body the object to write
 * @param bodyParameter the {@link MethodParameter} of the body to write
 * @param actualParam the actual return type of the method that returned the value;
 * could be different from {@code bodyParameter} when processing {@code HttpEntity}
 * for example
 * @param exchange the current exchange
 * @return indicates completion or error
 * @since 5.0.2
 */
@SuppressWarnings({"unchecked", "rawtypes", "ConstantConditions"})
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter,
		@Nullable MethodParameter actualParam, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve(), body);

	Publisher<?> publisher;
	ResolvableType elementType;
	ResolvableType actualElementType;
	if (adapter != null) {
		publisher = adapter.toPublisher(body);
		boolean isUnwrapped = KotlinDetector.isKotlinReflectPresent() &&
				KotlinDetector.isKotlinType(bodyParameter.getContainingClass()) &&
				KotlinDelegate.isSuspend(bodyParameter.getMethod()) &&
				!COROUTINES_FLOW_CLASS_NAME.equals(bodyType.toClass().getName());
		ResolvableType genericType = isUnwrapped ? bodyType : bodyType.getGeneric();
		elementType = getElementType(adapter, genericType);
		actualElementType = elementType;
	}
	else {
		publisher = Mono.justOrEmpty(body);
		actualElementType = body != null ? ResolvableType.forInstance(body) : bodyType;
		elementType = (bodyType.toClass() == Object.class && body != null ? actualElementType : bodyType);
	}

	if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
		return Mono.from((Publisher<Void>) publisher);
	}

	MediaType bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType));
	if (bestMediaType != null) {
		String logPrefix = exchange.getLogPrefix();
		if (logger.isDebugEnabled()) {
			logger.debug(logPrefix +
					(publisher instanceof Mono ? "0..1" : "0..N") + " [" + elementType + "]");
		}
		for (HttpMessageWriter<?> writer : getMessageWriters()) {
			if (writer.canWrite(actualElementType, bestMediaType)) {
				return writer.write((Publisher) publisher, actualType, elementType,
						bestMediaType, exchange.getRequest(), exchange.getResponse(),
						Hints.from(Hints.LOG_PREFIX_HINT, logPrefix));
			}
		}
	}

	List<MediaType> mediaTypes = getMediaTypesFor(elementType);
	if (bestMediaType == null && mediaTypes.isEmpty()) {
		return Mono.error(new IllegalStateException("No HttpMessageWriter for " + elementType));
	}
	return Mono.error(new NotAcceptableStatusException(mediaTypes));
}
 
Example #29
Source File: AbstractMediaTypeExpression.java    From spring-analysis-note with MIT License 4 votes vote down vote up
protected abstract boolean matchMediaType(ServerWebExchange exchange)
throws NotAcceptableStatusException, UnsupportedMediaTypeStatusException;
 
Example #30
Source File: OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void handleFluxExceptions_handles_NotAcceptableStatusException_as_expected(
    boolean includesSupportedMediaTypes
) {
    // given
    List<MediaType> supportedMediaTypes = Arrays.asList(
        MediaType.APPLICATION_JSON,
        MediaType.IMAGE_JPEG
    );
    NotAcceptableStatusException ex =
        (includesSupportedMediaTypes)
        ? new NotAcceptableStatusException(supportedMediaTypes)
        : new NotAcceptableStatusException("Some reason");

    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>();
    ApiExceptionHandlerUtils.DEFAULT_IMPL.addBaseExceptionMessageToExtraDetailsForLogging(
        ex, expectedExtraDetailsForLogging
    );

    String expectedSupportedMediaTypesValueStr =
        (includesSupportedMediaTypes)
        ? supportedMediaTypes.stream().map(Object::toString).collect(Collectors.joining(","))
        : "";

    expectedExtraDetailsForLogging.add(Pair.of("supported_media_types", expectedSupportedMediaTypesValueStr));

    // when
    ApiExceptionHandlerListenerResult result = listener.handleSpringMvcOrWebfluxSpecificFrameworkExceptions(ex);

    // then
    validateResponse(
        result,
        true,
        singleton(testProjectApiErrors.getNoAcceptableRepresentationApiError()),
        expectedExtraDetailsForLogging
    );
}