Search in sources :

Example 1 with UnsupportedMediaTypeStatusException

use of org.springframework.web.server.UnsupportedMediaTypeStatusException in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMapping method handleNoMatch.

/**
	 * Iterate all RequestMappingInfos once again, look if any match by URL at
	 * least and raise exceptions accordingly.
	 * @throws MethodNotAllowedException for matches by URL but not by HTTP method
	 * @throws UnsupportedMediaTypeStatusException if there are matches by URL
	 * and HTTP method but not by consumable media types
	 * @throws NotAcceptableStatusException if there are matches by URL and HTTP
	 * method but not by producible media types
	 * @throws ServerWebInputException if there are matches by URL and HTTP
	 * method but not by query parameter conditions
	 */
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, String lookupPath, ServerWebExchange exchange) throws Exception {
    PartialMatchHelper helper = new PartialMatchHelper(infos, exchange);
    if (helper.isEmpty()) {
        return null;
    }
    ServerHttpRequest request = exchange.getRequest();
    if (helper.hasMethodsMismatch()) {
        HttpMethod httpMethod = request.getMethod();
        Set<String> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.matches(httpMethod.name())) {
            HttpOptionsHandler handler = new HttpOptionsHandler(methods);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new MethodNotAllowedException(httpMethod.name(), methods);
    }
    if (helper.hasConsumesMismatch()) {
        Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
        MediaType contentType;
        try {
            contentType = request.getHeaders().getContentType();
        } catch (InvalidMediaTypeException ex) {
            throw new UnsupportedMediaTypeStatusException(ex.getMessage());
        }
        throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes));
    }
    if (helper.hasProducesMismatch()) {
        Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
        throw new NotAcceptableStatusException(new ArrayList<>(mediaTypes));
    }
    if (helper.hasParamsMismatch()) {
        throw new ServerWebInputException("Unsatisfied query parameter conditions: " + helper.getParamConditions() + ", actual parameters: " + request.getQueryParams());
    }
    return null;
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerWebInputException(org.springframework.web.server.ServerWebInputException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 2 with UnsupportedMediaTypeStatusException

use of org.springframework.web.server.UnsupportedMediaTypeStatusException in project spring-framework by spring-projects.

the class AbstractMessageReaderArgumentResolver method readBody.

protected Mono<Object> readBody(MethodParameter bodyParameter, boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve());
    ResolvableType elementType = (adapter != null ? bodyType.getGeneric(0) : bodyType);
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    MediaType mediaType = request.getHeaders().getContentType();
    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
    }
    for (HttpMessageReader<?> reader : getMessageReaders()) {
        if (reader.canRead(elementType, mediaType)) {
            Map<String, Object> readHints = Collections.emptyMap();
            if (adapter != null && adapter.isMultiValue()) {
                Flux<?> flux;
                if (reader instanceof ServerHttpMessageReader) {
                    ServerHttpMessageReader<?> serverReader = ((ServerHttpMessageReader<?>) reader);
                    flux = serverReader.read(bodyType, elementType, request, response, readHints);
                } else {
                    flux = reader.read(elementType, request, readHints);
                }
                flux = flux.onErrorResumeWith(ex -> Flux.error(getReadError(bodyParameter, ex)));
                if (isBodyRequired || !adapter.supportsEmpty()) {
                    flux = flux.switchIfEmpty(Flux.error(getRequiredBodyError(bodyParameter)));
                }
                Object[] hints = extractValidationHints(bodyParameter);
                if (hints != null) {
                    flux = flux.doOnNext(target -> validate(target, hints, bodyParameter, bindingContext, exchange));
                }
                return Mono.just(adapter.fromPublisher(flux));
            } else {
                Mono<?> mono;
                if (reader instanceof ServerHttpMessageReader) {
                    ServerHttpMessageReader<?> serverReader = (ServerHttpMessageReader<?>) reader;
                    mono = serverReader.readMono(bodyType, elementType, request, response, readHints);
                } else {
                    mono = reader.readMono(elementType, request, readHints);
                }
                mono = mono.otherwise(ex -> Mono.error(getReadError(bodyParameter, ex)));
                if (isBodyRequired || (adapter != null && !adapter.supportsEmpty())) {
                    mono = mono.otherwiseIfEmpty(Mono.error(getRequiredBodyError(bodyParameter)));
                }
                Object[] hints = extractValidationHints(bodyParameter);
                if (hints != null) {
                    mono = mono.doOnNext(target -> validate(target, hints, bodyParameter, bindingContext, exchange));
                }
                if (adapter != null) {
                    return Mono.just(adapter.fromPublisher(mono));
                } else {
                    return Mono.from(mono);
                }
            }
        }
    }
    return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes));
}
Also used : ServerHttpMessageReader(org.springframework.http.codec.ServerHttpMessageReader) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) Validator(org.springframework.validation.Validator) Conventions(org.springframework.core.Conventions) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) ServerWebInputException(org.springframework.web.server.ServerWebInputException) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) BindingContext(org.springframework.web.reactive.BindingContext) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ReactiveAdapter(org.springframework.core.ReactiveAdapter) Validated(org.springframework.validation.annotation.Validated) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) Collectors(java.util.stream.Collectors) Flux(reactor.core.publisher.Flux) List(java.util.List) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) Assert(org.springframework.util.Assert) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ServerHttpMessageReader(org.springframework.http.codec.ServerHttpMessageReader) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 3 with UnsupportedMediaTypeStatusException

use of org.springframework.web.server.UnsupportedMediaTypeStatusException in project spring-framework by spring-projects.

the class InvocableHandlerMethodTests method resolverThrowsException.

@Test
public void resolverThrowsException() throws Exception {
    Mono<Object> resolvedValue = Mono.error(new UnsupportedMediaTypeStatusException("boo"));
    Method method = on(TestController.class).mockCall(o -> o.singleArg(null)).method();
    Mono<HandlerResult> mono = invoke(new TestController(), method, resolverFor(resolvedValue));
    try {
        mono.block();
        fail("Expected UnsupportedMediaTypeStatusException");
    } catch (UnsupportedMediaTypeStatusException ex) {
        assertThat(ex.getMessage(), is("Request failure [status: 415, reason: \"boo\"]"));
    }
}
Also used : Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) ResolvableMethod.on(org.springframework.web.method.ResolvableMethod.on) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) BindingContext(org.springframework.web.reactive.BindingContext) Mockito.when(org.mockito.Mockito.when) HandlerResult(org.springframework.web.reactive.HandlerResult) Assert.assertThat(org.junit.Assert.assertThat) HttpStatus(org.springframework.http.HttpStatus) MockServerWebExchange(org.springframework.mock.http.server.reactive.test.MockServerWebExchange) MockServerHttpRequest(org.springframework.mock.http.server.reactive.test.MockServerHttpRequest) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Assert.fail(org.junit.Assert.fail) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) Mockito.any(org.mockito.Mockito.any) Method(java.lang.reflect.Method) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) HandlerResult(org.springframework.web.reactive.HandlerResult) Method(java.lang.reflect.Method) Test(org.junit.Test)

Aggregations

UnsupportedMediaTypeStatusException (org.springframework.web.server.UnsupportedMediaTypeStatusException)3 MediaType (org.springframework.http.MediaType)2 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)2 BindingContext (org.springframework.web.reactive.BindingContext)2 Mono (reactor.core.publisher.Mono)2 Annotation (java.lang.annotation.Annotation)1 Method (java.lang.reflect.Method)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Collectors (java.util.stream.Collectors)1 Matchers.is (org.hamcrest.Matchers.is)1 Assert.assertEquals (org.junit.Assert.assertEquals)1 Assert.assertThat (org.junit.Assert.assertThat)1 Assert.assertTrue (org.junit.Assert.assertTrue)1 Assert.fail (org.junit.Assert.fail)1 Test (org.junit.Test)1 Mockito.any (org.mockito.Mockito.any)1