Search in sources :

Example 16 with HttpMessageWriter

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

the class WebFluxConfigurationSupportTests method assertHasMessageWriter.

private void assertHasMessageWriter(List<HttpMessageWriter<?>> writers, Class<?> clazz, MediaType mediaType) {
    ResolvableType type = ResolvableType.forClass(clazz);
    assertTrue(writers.stream().anyMatch(c -> mediaType == null || c.canWrite(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)

Example 17 with HttpMessageWriter

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

the class HttpMessageWriterView method applyMessageWriter.

@SuppressWarnings("unchecked")
private <T> Mono<Void> applyMessageWriter(Object value, MediaType contentType, ServerWebExchange exchange) {
    if (value == null) {
        return Mono.empty();
    }
    Publisher<? extends T> stream = Mono.just((T) value);
    ResolvableType type = ResolvableType.forClass(value.getClass());
    ServerHttpResponse response = exchange.getResponse();
    return ((HttpMessageWriter<T>) getMessageWriter()).write(stream, type, contentType, response, Collections.emptyMap());
}
Also used : EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) ResolvableType(org.springframework.core.ResolvableType) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse)

Example 18 with HttpMessageWriter

use of org.springframework.http.codec.HttpMessageWriter in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method getBody.

private static String getBody(ClientRequest request) {
    final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
    messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
    messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
    messageWriters.add(new ResourceHttpMessageWriter());
    Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
    messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
    messageWriters.add(new ServerSentEventHttpMessageWriter(jsonEncoder));
    messageWriters.add(new FormHttpMessageWriter());
    messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
    messageWriters.add(new MultipartHttpMessageWriter(messageWriters));
    BodyInserter.Context context = new BodyInserter.Context() {

        @Override
        public List<HttpMessageWriter<?>> messageWriters() {
            return messageWriters;
        }

        @Override
        public Optional<ServerHttpRequest> serverRequest() {
            return Optional.empty();
        }

        @Override
        public Map<String, Object> hints() {
            return new HashMap<>();
        }
    };
    MockClientHttpRequest body = new MockClientHttpRequest(HttpMethod.GET, "/");
    request.body().insert(body, context).block();
    return body.getBodyAsString().block();
}
Also used : ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) Context(reactor.util.context.Context) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) HashMap(java.util.HashMap) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ArrayList(java.util.ArrayList) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) BodyInserter(org.springframework.web.reactive.function.BodyInserter) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter)

Example 19 with HttpMessageWriter

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

the class MultipartHttpMessageWriter method encodePart.

@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory factory) {
    MultipartHttpOutputMessage message = new MultipartHttpOutputMessage(factory);
    HttpHeaders headers = message.getHeaders();
    T body;
    ResolvableType resolvableType = null;
    if (value instanceof HttpEntity) {
        HttpEntity<T> httpEntity = (HttpEntity<T>) value;
        headers.putAll(httpEntity.getHeaders());
        body = httpEntity.getBody();
        Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
        if (httpEntity instanceof ResolvableTypeProvider) {
            resolvableType = ((ResolvableTypeProvider) httpEntity).getResolvableType();
        }
    } else {
        body = value;
    }
    if (resolvableType == null) {
        resolvableType = ResolvableType.forClass(body.getClass());
    }
    if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
        if (body instanceof Resource) {
            headers.setContentDispositionFormData(name, ((Resource) body).getFilename());
        } else if (resolvableType.resolve() == Resource.class) {
            body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> headers.setContentDispositionFormData(name, ((Resource) o).getFilename()));
        } else {
            headers.setContentDispositionFormData(name, null);
        }
    }
    MediaType contentType = headers.getContentType();
    final ResolvableType finalBodyType = resolvableType;
    Optional<HttpMessageWriter<?>> writer = this.partWriters.stream().filter(partWriter -> partWriter.canWrite(finalBodyType, contentType)).findFirst();
    if (!writer.isPresent()) {
        return Flux.error(new CodecException("No suitable writer found for part: " + name));
    }
    Publisher<T> bodyPublisher = body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);
    // The writer will call MultipartHttpOutputMessage#write which doesn't actually write
    // but only stores the body Flux and returns Mono.empty().
    Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get()).write(bodyPublisher, resolvableType, contentType, message, DEFAULT_HINTS);
    // After partContentReady, we can access the part content from MultipartHttpOutputMessage
    // and use it for writing to the actual request body
    Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(message::getBody));
    return Flux.concat(generateBoundaryLine(boundary, factory), partContent, generateNewLine(factory));
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) Arrays(java.util.Arrays) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Hints(org.springframework.core.codec.Hints) ResolvableTypeProvider(org.springframework.core.ResolvableTypeProvider) Supplier(java.util.function.Supplier) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) ArrayList(java.util.ArrayList) CodecException(org.springframework.core.codec.CodecException) LogFormatUtils(org.springframework.core.log.LogFormatUtils) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) Map(java.util.Map) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) Resource(org.springframework.core.io.Resource) HttpHeaders(org.springframework.http.HttpHeaders) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Flux(reactor.core.publisher.Flux) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Optional(java.util.Optional) Collections(java.util.Collections) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Assert(org.springframework.util.Assert) HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Resource(org.springframework.core.io.Resource) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) CodecException(org.springframework.core.codec.CodecException) ResolvableType(org.springframework.core.ResolvableType) ResolvableTypeProvider(org.springframework.core.ResolvableTypeProvider) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 20 with HttpMessageWriter

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

the class WebFluxConfigurationSupportTests method responseEntityResultHandler.

@Test
public void responseEntityResultHandler() {
    ApplicationContext context = loadConfig(WebFluxConfig.class);
    String name = "responseEntityResultHandler";
    ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class);
    assertThat(handler).isNotNull();
    assertThat(handler.getOrder()).isEqualTo(0);
    List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
    assertThat(writers.size()).isEqualTo(13);
    assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
    assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
    assertHasMessageWriter(writers, forClass(String.class), TEXT_PLAIN);
    assertHasMessageWriter(writers, forClass(Resource.class), IMAGE_PNG);
    assertHasMessageWriter(writers, forClass(Message.class), new MediaType("application", "x-protobuf"));
    assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_XML);
    assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_JSON);
    assertHasMessageWriter(writers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
    assertHasMessageWriter(writers, forClass(TestBean.class), MediaType.parseMediaType("text/event-stream"));
    name = "webFluxContentTypeResolver";
    RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
    assertThat(handler.getContentTypeResolver()).isSameAs(resolver);
}
Also used : AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Message(com.google.protobuf.Message) ResponseEntityResultHandler(org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler) Resource(org.springframework.core.io.Resource) MediaType(org.springframework.http.MediaType) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.jupiter.api.Test)

Aggregations

HttpMessageWriter (org.springframework.http.codec.HttpMessageWriter)27 EncoderHttpMessageWriter (org.springframework.http.codec.EncoderHttpMessageWriter)23 ResourceHttpMessageWriter (org.springframework.http.codec.ResourceHttpMessageWriter)15 Test (org.junit.jupiter.api.Test)14 FormHttpMessageWriter (org.springframework.http.codec.FormHttpMessageWriter)11 Jackson2JsonEncoder (org.springframework.http.codec.json.Jackson2JsonEncoder)11 MultipartHttpMessageWriter (org.springframework.http.codec.multipart.MultipartHttpMessageWriter)11 ArrayList (java.util.ArrayList)10 ProtobufHttpMessageWriter (org.springframework.http.codec.protobuf.ProtobufHttpMessageWriter)8 ByteBufferEncoder (org.springframework.core.codec.ByteBufferEncoder)7 RequestedContentTypeResolver (org.springframework.web.reactive.accept.RequestedContentTypeResolver)6 List (java.util.List)5 MediaType (org.springframework.http.MediaType)5 HttpMessageReader (org.springframework.http.codec.HttpMessageReader)5 ServerSentEventHttpMessageWriter (org.springframework.http.codec.ServerSentEventHttpMessageWriter)5 Jaxb2XmlEncoder (org.springframework.http.codec.xml.Jaxb2XmlEncoder)5 ResolvableType (org.springframework.core.ResolvableType)4 BodyInserter (org.springframework.web.reactive.function.BodyInserter)4 ByteBuffer (java.nio.ByteBuffer)3 HashMap (java.util.HashMap)3