Search in sources :

Example 11 with ReactiveHttpOutputMessage

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

the class BodyInsertersTests method ofObject.

@Test
public void ofObject() {
    User body = new User("foo", "bar");
    BodyInserter<User, ReactiveHttpOutputMessage> inserter = BodyInserters.fromValue(body);
    MockServerHttpResponse response = new MockServerHttpResponse();
    Mono<Void> result = inserter.insert(response, this.context);
    StepVerifier.create(result).expectComplete().verify();
    StepVerifier.create(response.getBodyAsString()).expectNext("{\"username\":\"foo\",\"password\":\"bar\"}").expectComplete().verify();
}
Also used : ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) MockServerHttpResponse(org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse) Test(org.junit.jupiter.api.Test)

Example 12 with ReactiveHttpOutputMessage

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

the class BodyInsertersTests method ofResourceRange.

@Test
public void ofResourceRange() throws IOException {
    final int rangeStart = 10;
    Resource body = new ClassPathResource("response.txt", getClass());
    BodyInserter<Resource, ReactiveHttpOutputMessage> inserter = BodyInserters.fromResource(body);
    MockServerHttpRequest request = MockServerHttpRequest.get("/foo").range(HttpRange.createByteRange(rangeStart)).build();
    MockServerHttpResponse response = new MockServerHttpResponse();
    Mono<Void> result = inserter.insert(response, new BodyInserter.Context() {

        @Override
        public List<HttpMessageWriter<?>> messageWriters() {
            return Collections.singletonList(new ResourceHttpMessageWriter());
        }

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

        @Override
        public Map<String, Object> hints() {
            return hints;
        }
    });
    StepVerifier.create(result).expectComplete().verify();
    byte[] allBytes = Files.readAllBytes(body.getFile().toPath());
    byte[] expectedBytes = new byte[allBytes.length - rangeStart];
    System.arraycopy(allBytes, rangeStart, expectedBytes, 0, expectedBytes.length);
    StepVerifier.create(response.getBody()).consumeNextWith(dataBuffer -> {
        byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(resultBytes);
        DataBufferUtils.release(dataBuffer);
        assertThat(resultBytes).isEqualTo(expectedBytes);
    }).expectComplete().verify();
}
Also used : ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) Optional(java.util.Optional) Resource(org.springframework.core.io.Resource) ClassPathResource(org.springframework.core.io.ClassPathResource) MockServerHttpResponse(org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse) ClassPathResource(org.springframework.core.io.ClassPathResource) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.jupiter.api.Test)

Example 13 with ReactiveHttpOutputMessage

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

the class BodyInsertersTests method ofProducerWithSingle.

@Test
public void ofProducerWithSingle() {
    Single<User> body = Single.just(new User("foo", "bar"));
    BodyInserter<?, ReactiveHttpOutputMessage> inserter = BodyInserters.fromProducer(body, User.class);
    MockServerHttpResponse response = new MockServerHttpResponse();
    Mono<Void> result = inserter.insert(response, this.context);
    StepVerifier.create(result).expectComplete().verify();
    StepVerifier.create(response.getBodyAsString()).expectNext("{\"username\":\"foo\",\"password\":\"bar\"}").expectComplete().verify();
}
Also used : ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) MockServerHttpResponse(org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse) Test(org.junit.jupiter.api.Test)

Example 14 with ReactiveHttpOutputMessage

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

the class EncoderHttpMessageWriter method write.

@Override
public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType, @Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) {
    MediaType contentType = updateContentType(message, mediaType);
    Flux<DataBuffer> body = this.encoder.encode(inputStream, message.bufferFactory(), elementType, contentType, hints);
    if (inputStream instanceof Mono) {
        return body.singleOrEmpty().switchIfEmpty(Mono.defer(() -> {
            message.getHeaders().setContentLength(0);
            return message.setComplete().then(Mono.empty());
        })).flatMap(buffer -> {
            Hints.touchDataBuffer(buffer, hints, logger);
            message.getHeaders().setContentLength(buffer.readableByteCount());
            return message.writeWith(Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release));
        }).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
    }
    if (isStreamingMediaType(contentType)) {
        return message.writeAndFlushWith(body.map(buffer -> {
            Hints.touchDataBuffer(buffer, hints, logger);
            return Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
        }));
    }
    if (logger.isDebugEnabled()) {
        body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
    }
    return message.writeWith(body);
}
Also used : AbstractEncoder(org.springframework.core.codec.AbstractEncoder) HttpLogging(org.springframework.http.HttpLogging) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) Hints(org.springframework.core.codec.Hints) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) Flux(reactor.core.publisher.Flux) List(java.util.List) Map(java.util.Map) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Log(org.apache.commons.logging.Log) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) Encoder(org.springframework.core.codec.Encoder) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Mono(reactor.core.publisher.Mono) MediaType(org.springframework.http.MediaType) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 15 with ReactiveHttpOutputMessage

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

the class BodyInserters method fromProducer.

/**
 * Inserter to write the given producer of value(s) which must be a {@link Publisher}
 * or another producer adaptable to a {@code Publisher} via
 * {@link ReactiveAdapterRegistry}.
 * <p>Alternatively, consider using the {@code body} shortcuts on
 * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and
 * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}.
 * @param <T> the type of the body
 * @param producer the source of body value(s).
 * @param elementTypeRef the type of values to be produced
 * @return the inserter to write a producer
 * @since 5.2
 */
public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T producer, ParameterizedTypeReference<?> elementTypeRef) {
    Assert.notNull(producer, "'producer' must not be null");
    Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null");
    ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(producer.getClass());
    Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry");
    return (message, context) -> writeWithMessageWriters(message, context, producer, ResolvableType.forType(elementTypeRef), adapter);
}
Also used : ReactiveAdapter(org.springframework.core.ReactiveAdapter) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Collectors(java.util.stream.Collectors) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) ServerSentEvent(org.springframework.http.codec.ServerSentEvent) MultipartBodyBuilder(org.springframework.http.client.MultipartBodyBuilder) ClientHttpRequest(org.springframework.http.client.reactive.ClientHttpRequest) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Aggregations

ReactiveHttpOutputMessage (org.springframework.http.ReactiveHttpOutputMessage)15 Test (org.junit.jupiter.api.Test)9 MockServerHttpResponse (org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse)9 List (java.util.List)7 DataBuffer (org.springframework.core.io.buffer.DataBuffer)7 Publisher (org.reactivestreams.Publisher)6 ResolvableType (org.springframework.core.ResolvableType)6 Resource (org.springframework.core.io.Resource)6 MediaType (org.springframework.http.MediaType)6 Nullable (org.springframework.lang.Nullable)6 Mono (reactor.core.publisher.Mono)6 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)5 Assert (org.springframework.util.Assert)5 MultiValueMap (org.springframework.util.MultiValueMap)5 Flux (reactor.core.publisher.Flux)5 Map (java.util.Map)4 HttpEntity (org.springframework.http.HttpEntity)4 HttpMessageWriter (org.springframework.http.codec.HttpMessageWriter)4 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)4 Optional (java.util.Optional)3