org.springframework.web.server.UnsupportedMediaTypeStatusException Java Examples

The following examples show how to use org.springframework.web.server.UnsupportedMediaTypeStatusException. 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: DefaultServerRequestTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bodyUnacceptable() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.TEXT_PLAIN);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.GET, "https://example.com?foo=bar")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());

	Flux<String> resultFlux = request.bodyToFlux(String.class);
	StepVerifier.create(resultFlux)
			.expectError(UnsupportedMediaTypeStatusException.class)
			.verify();
}
 
Example #3
Source File: DefaultServerRequestTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyUnacceptable() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.TEXT_PLAIN);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.GET, "http://example.com?foo=bar")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());

	Flux<String> resultFlux = request.bodyToFlux(String.class);
	StepVerifier.create(resultFlux)
			.expectError(UnsupportedMediaTypeStatusException.class)
			.verify();
}
 
Example #4
Source File: UnsupportedMediaTypeAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleMediaTypeNotSupportedException(
        final UnsupportedMediaTypeStatusException exception,
        final ServerWebExchange request) {

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(exception.getSupportedMediaTypes());

    return create(Status.UNSUPPORTED_MEDIA_TYPE, exception, request, headers);
}
 
Example #5
Source File: ConsumesRequestCondition.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws UnsupportedMediaTypeStatusException {
	try {
		MediaType contentType = exchange.getRequest().getHeaders().getContentType();
		contentType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
		return getMediaType().includes(contentType);
	}
	catch (InvalidMediaTypeException ex) {
		throw new UnsupportedMediaTypeStatusException("Can't parse Content-Type [" +
				exchange.getRequest().getHeaders().getFirst("Content-Type") +
				"]: " + ex.getMessage());
	}
}
 
Example #6
Source File: InvocableHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void exceptionInResolvingArg() {
	this.resolvers.add(stubResolver(Mono.error(new UnsupportedMediaTypeStatusException("boo"))));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected UnsupportedMediaTypeStatusException");
	}
	catch (UnsupportedMediaTypeStatusException ex) {
		assertThat(ex.getMessage(), is("415 UNSUPPORTED_MEDIA_TYPE \"boo\""));
	}
}
 
Example #7
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testHttpMediaTypeNotSupportedException(String url) {
	MockServerHttpRequest request = put(url).contentType(MediaType.APPLICATION_JSON).build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, UnsupportedMediaTypeStatusException.class, ex ->
			assertEquals("Invalid supported consumable media types",
					Collections.singletonList(new MediaType("application", "xml")),
					ex.getSupportedMediaTypes()));
}
 
Example #8
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getHandlerTestInvalidContentType() {
	MockServerHttpRequest request = put("/person/1").header("content-type", "bogus").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, UnsupportedMediaTypeStatusException.class,
			ex -> assertEquals("415 UNSUPPORTED_MEDIA_TYPE " +
					"\"Invalid mime type \"bogus\": does not contain '/'\"", ex.getMessage()));
}
 
Example #9
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void missingContentType() throws Exception {
	MockServerHttpRequest request = post("/path").body("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}");
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
	MethodParameter param = this.testMethod.arg(type);
	Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange);
	Mono<TestBean> value = (Mono<TestBean>) result.block(Duration.ofSeconds(1));

	StepVerifier.create(value).expectError(UnsupportedMediaTypeStatusException.class).verify();
}
 
Example #10
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 #11
Source File: ConsumesRequestCondition.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws UnsupportedMediaTypeStatusException {
	try {
		MediaType contentType = exchange.getRequest().getHeaders().getContentType();
		contentType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
		return getMediaType().includes(contentType);
	}
	catch (InvalidMediaTypeException ex) {
		throw new UnsupportedMediaTypeStatusException("Can't parse Content-Type [" +
				exchange.getRequest().getHeaders().getFirst("Content-Type") +
				"]: " + ex.getMessage());
	}
}
 
Example #12
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void exceptionInResolvingArg() {
	this.resolvers.add(stubResolver(Mono.error(new UnsupportedMediaTypeStatusException("boo"))));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected UnsupportedMediaTypeStatusException");
	}
	catch (UnsupportedMediaTypeStatusException ex) {
		assertThat(ex.getMessage(), is("415 UNSUPPORTED_MEDIA_TYPE \"boo\""));
	}
}
 
Example #13
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void testHttpMediaTypeNotSupportedException(String url) {
	MockServerHttpRequest request = put(url).contentType(MediaType.APPLICATION_JSON).build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, UnsupportedMediaTypeStatusException.class, ex ->
			assertEquals("Invalid supported consumable media types",
					Collections.singletonList(new MediaType("application", "xml")),
					ex.getSupportedMediaTypes()));
}
 
Example #14
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getHandlerTestInvalidContentType() {
	MockServerHttpRequest request = put("/person/1").header("content-type", "bogus").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, UnsupportedMediaTypeStatusException.class,
			ex -> assertEquals("415 UNSUPPORTED_MEDIA_TYPE " +
					"\"Invalid mime type \"bogus\": does not contain '/'\"", ex.getMessage()));
}
 
Example #15
Source File: MessageReaderArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void missingContentType() throws Exception {
	MockServerHttpRequest request = post("/path").body("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}");
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
	MethodParameter param = this.testMethod.arg(type);
	Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange);
	Mono<TestBean> value = (Mono<TestBean>) result.block(Duration.ofSeconds(1));

	StepVerifier.create(value).expectError(UnsupportedMediaTypeStatusException.class).verify();
}
 
Example #16
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 #17
Source File: AbstractMessageReaderArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
		boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	Class<?> resolvedType = bodyType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
	isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
	Object[] hints = extractValidationHints(bodyParam);

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null ?
				"Content-Type:" + contentType :
				"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}

	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
				flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					flux = flux.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
				mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					mono = mono.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	// No compatible reader but body may be empty..

	HttpMethod method = request.getMethod();
	if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
		Flux<DataBuffer> body = request.getBody().doOnNext(o -> {
			// Body not empty, back to 415..
			throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
		});
		if (isBodyRequired) {
			body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
		}
		return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}
 
Example #18
Source File: AbstractMessageReaderArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
		boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	Class<?> resolvedType = bodyType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
	isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
	Object[] hints = extractValidationHints(bodyParam);

	if (mediaType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
		return Mono.error(new IllegalStateException(
				"In a WebFlux application, form data is accessed via ServerWebExchange.getFormData()."));
	}

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null ?
				"Content-Type:" + contentType :
				"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}

	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
				flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					flux = flux.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
				mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					mono = mono.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	// No compatible reader but body may be empty..

	HttpMethod method = request.getMethod();
	if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
		Flux<DataBuffer> body = request.getBody().doOnNext(buffer -> {
			DataBufferUtils.release(buffer);
			// Body not empty, back to 415..
			throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
		});
		if (isBodyRequired) {
			body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
		}
		return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}
 
Example #19
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_UnsupportedMediaTypeStatusException_as_expected(
    boolean includeDetails
) {
    // given
    MediaType actualMediaType = MediaType.TEXT_PLAIN;
    List<MediaType> supportedMediaTypes = Arrays.asList(
        MediaType.APPLICATION_JSON,
        MediaType.IMAGE_JPEG
    );
    ResolvableType javaBodyType = ResolvableType.forClass(Integer.class);
    UnsupportedMediaTypeStatusException ex =
        (includeDetails)
        ? new UnsupportedMediaTypeStatusException(actualMediaType, supportedMediaTypes, javaBodyType)
        : new UnsupportedMediaTypeStatusException("Some reason");

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

    String expectedSupportedMediaTypesValueStr =
        (includeDetails)
        ? supportedMediaTypes.stream().map(Object::toString).collect(Collectors.joining(","))
        : "";
    String expectedJavaBodyTypeValueStr =
        (includeDetails)
        ? javaBodyType.toString()
        : "null";

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

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

    // then
    validateResponse(
        result,
        true,
        singleton(testProjectApiErrors.getUnsupportedMediaTypeApiError()),
        expectedExtraDetailsForLogging
    );
}
 
Example #20
Source File: RequestProcessor.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private Publisher<?> body(Object handler, ServerWebExchange exchange) {
	ResolvableType elementType = ResolvableType
			.forClass(this.inspector.getInputType(handler));

	// we effectively delegate type conversion to FunctionCatalog
	elementType = ResolvableType.forClass(String.class);

	ResolvableType actualType = elementType;

	Class<?> resolvedType = elementType.resolve();
	ReactiveAdapter adapter = (resolvedType != null
			? getAdapterRegistry().getAdapter(resolvedType) : null);

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType
			: MediaType.APPLICATION_OCTET_STREAM);

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null
				? "Content-Type:" + contentType
				: "No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}
	boolean isBodyRequired = (adapter != null && !adapter.supportsEmpty());

	MethodParameter bodyParam = new MethodParameter(handlerMethod(handler), 0);
	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT,
					exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(
							exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response,
						readHints);
				flux = flux.onErrorResume(
						ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(
							Flux.error(() -> handleMissingBody(bodyParam)));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request,
						response, readHints).doOnNext(v -> {
							if (logger.isDebugEnabled()) {
								logger.debug("received: " + v);
							}
						});
				mono = mono.onErrorResume(
						ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(
							Mono.error(() -> handleMissingBody(bodyParam)));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono))
						: Mono.from(mono));
			}
		}
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType,
			Arrays.asList(MediaType.APPLICATION_JSON), elementType));
}
 
Example #21
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;