Search in sources :

Example 6 with HttpMessageReader

use of org.springframework.http.codec.HttpMessageReader in project spring-framework by spring-projects.

the class DefaultClientResponseTests method bodyToMonoError.

@Test
public void bodyToMonoError() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.TEXT_PLAIN);
    when(mockResponse.getHeaders()).thenReturn(httpHeaders);
    when(mockResponse.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND);
    Set<HttpMessageReader<?>> messageReaders = Collections.singleton(new DecoderHttpMessageReader<String>(new StringDecoder()));
    when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders::stream);
    Mono<String> resultMono = defaultClientResponse.bodyToMono(String.class);
    StepVerifier.create(resultMono).expectError(WebClientException.class).verify();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) StringDecoder(org.springframework.core.codec.StringDecoder) Test(org.junit.Test)

Example 7 with HttpMessageReader

use of org.springframework.http.codec.HttpMessageReader 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 8 with HttpMessageReader

use of org.springframework.http.codec.HttpMessageReader in project spring-framework by spring-projects.

the class BodyExtractors method readWithMessageReaders.

private static <T, S extends Publisher<T>> S readWithMessageReaders(ReactiveHttpInputMessage inputMessage, BodyExtractor.Context context, ResolvableType elementType, Function<HttpMessageReader<T>, S> readerFunction, Function<Throwable, S> unsupportedError) {
    MediaType contentType = contentType(inputMessage);
    Supplier<Stream<HttpMessageReader<?>>> messageReaders = context.messageReaders();
    return messageReaders.get().filter(r -> r.canRead(elementType, contentType)).findFirst().map(BodyExtractors::<T>cast).map(readerFunction).orElseGet(() -> {
        List<MediaType> supportedMediaTypes = messageReaders.get().flatMap(reader -> reader.getReadableMediaTypes().stream()).collect(Collectors.toList());
        UnsupportedMediaTypeException error = new UnsupportedMediaTypeException(contentType, supportedMediaTypes);
        return unsupportedError.apply(error);
    });
}
Also used : Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) ResolvableType(org.springframework.core.ResolvableType) HttpMessage(org.springframework.http.HttpMessage) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Assert(org.springframework.util.Assert) MediaType(org.springframework.http.MediaType) Stream(java.util.stream.Stream)

Example 9 with HttpMessageReader

use of org.springframework.http.codec.HttpMessageReader in project spring-framework by spring-projects.

the class HttpEntityArgumentResolverTests method createResolver.

private HttpEntityArgumentResolver createResolver() {
    List<HttpMessageReader<?>> readers = new ArrayList<>();
    readers.add(new DecoderHttpMessageReader<>(new StringDecoder()));
    return new HttpEntityArgumentResolver(readers, new ReactiveAdapterRegistry());
}
Also used : HttpMessageReader(org.springframework.http.codec.HttpMessageReader) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ArrayList(java.util.ArrayList) StringDecoder(org.springframework.core.codec.StringDecoder)

Example 10 with HttpMessageReader

use of org.springframework.http.codec.HttpMessageReader in project spring-framework by spring-projects.

the class WebFluxConfigurationSupportTests method assertHasMessageReader.

private void assertHasMessageReader(List<HttpMessageReader<?>> readers, Class<?> clazz, MediaType mediaType) {
    ResolvableType type = ResolvableType.forClass(clazz);
    assertTrue(readers.stream().anyMatch(c -> mediaType == null || c.canRead(type, mediaType)));
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) Validator(org.springframework.validation.Validator) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) WebHandler(org.springframework.web.server.WebHandler) ByteBuffer(java.nio.ByteBuffer) APPLICATION_XML(org.springframework.http.MediaType.APPLICATION_XML) MimeType(org.springframework.util.MimeType) FreeMarkerConfigurer(org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer) APPLICATION_OCTET_STREAM(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM) HttpMessageWriterView(org.springframework.web.reactive.result.view.HttpMessageWriterView) View(org.springframework.web.reactive.result.view.View) ResolvableType(org.springframework.core.ResolvableType) AbstractHandlerMapping(org.springframework.web.reactive.handler.AbstractHandlerMapping) Resource(org.springframework.core.io.Resource) SimpleUrlHandlerMapping(org.springframework.web.reactive.handler.SimpleUrlHandlerMapping) StringDecoder(org.springframework.core.codec.StringDecoder) MediaType(org.springframework.http.MediaType) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Ordered(org.springframework.core.Ordered) RequestMappingHandlerMapping(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) RequestMappingHandlerAdapter(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Assert.assertSame(org.junit.Assert.assertSame) ResponseBodyResultHandler(org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) APPLICATION_JSON(org.springframework.http.MediaType.APPLICATION_JSON) ConversionService(org.springframework.core.convert.ConversionService) WebBindingInitializer(org.springframework.web.bind.support.WebBindingInitializer) Jaxb2XmlEncoder(org.springframework.http.codec.xml.Jaxb2XmlEncoder) ViewResolutionResultHandler(org.springframework.web.reactive.result.view.ViewResolutionResultHandler) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) TEXT_PLAIN(org.springframework.http.MediaType.TEXT_PLAIN) Test(org.junit.Test) MimeTypeUtils(org.springframework.util.MimeTypeUtils) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) ApplicationContext(org.springframework.context.ApplicationContext) ResponseEntityResultHandler(org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler) MockServerHttpRequest(org.springframework.mock.http.server.reactive.test.MockServerHttpRequest) IMAGE_PNG(org.springframework.http.MediaType.IMAGE_PNG) FreeMarkerViewResolver(org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver) Bean(org.springframework.context.annotation.Bean) ViewResolver(org.springframework.web.reactive.result.view.ViewResolver) Collections(java.util.Collections) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Assert.assertEquals(org.junit.Assert.assertEquals) ResolvableType(org.springframework.core.ResolvableType)

Aggregations

HttpMessageReader (org.springframework.http.codec.HttpMessageReader)16 DecoderHttpMessageReader (org.springframework.http.codec.DecoderHttpMessageReader)14 Test (org.junit.Test)12 StringDecoder (org.springframework.core.codec.StringDecoder)11 HttpHeaders (org.springframework.http.HttpHeaders)9 DataBuffer (org.springframework.core.io.buffer.DataBuffer)8 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)7 DefaultDataBufferFactory (org.springframework.core.io.buffer.DefaultDataBufferFactory)7 List (java.util.List)5 ApplicationContext (org.springframework.context.ApplicationContext)3 ResolvableType (org.springframework.core.ResolvableType)3 MediaType (org.springframework.http.MediaType)3 Validator (org.springframework.validation.Validator)3 WebExchangeDataBinder (org.springframework.web.bind.support.WebExchangeDataBinder)3 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 Map (java.util.Map)2 Supplier (java.util.function.Supplier)2 Collectors (java.util.stream.Collectors)2 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)2