Search in sources :

Example 1 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class UndertowRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
    ServerHttpRequest request = exchange.getRequest();
    Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required");
    HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange();
    Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet());
    Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
    List<Handshake> handshakes = Collections.singletonList(handshake);
    URI url = request.getURI();
    HttpHeaders headers = request.getHeaders();
    Mono<Principal> principal = exchange.getPrincipal();
    HandshakeInfo info = new HandshakeInfo(url, headers, principal, subProtocol);
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    try {
        DefaultCallback callback = new DefaultCallback(info, handler, bufferFactory);
        new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
    } catch (Exception ex) {
        return Mono.error(ex);
    }
    return Mono.empty();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) Principal(java.security.Principal) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake)

Example 2 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class ResourceRegionHttpMessageWriter method writeResourceRegion.

private Mono<Void> writeResourceRegion(ResourceRegion region, ReactiveHttpOutputMessage outputMessage) {
    if (outputMessage instanceof ZeroCopyHttpOutputMessage) {
        Optional<File> file = getFile(region.getResource());
        if (file.isPresent()) {
            ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) outputMessage;
            return zeroCopyResponse.writeWith(file.get(), region.getPosition(), region.getCount());
        }
    }
    // non-zero copy fallback, using ResourceRegionEncoder
    DataBufferFactory bufferFactory = outputMessage.bufferFactory();
    MediaType contentType = outputMessage.getHeaders().getContentType();
    Map<String, Object> hints = Collections.emptyMap();
    Flux<DataBuffer> body = this.encoder.encode(Mono.just(region), bufferFactory, TYPE, contentType, hints);
    return outputMessage.writeWith(body);
}
Also used : ZeroCopyHttpOutputMessage(org.springframework.http.ZeroCopyHttpOutputMessage) MediaType(org.springframework.http.MediaType) File(java.io.File) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 3 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class ServerSentEventHttpMessageWriter method applyEncoder.

@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> applyEncoder(Object data, DataBufferFactory bufferFactory, Map<String, Object> hints) {
    ResolvableType elementType = ResolvableType.forClass(data.getClass());
    Optional<Encoder<?>> encoder = dataEncoders.stream().filter(e -> e.canEncode(elementType, MimeTypeUtils.APPLICATION_JSON)).findFirst();
    return ((Encoder<T>) encoder.orElseThrow(() -> new CodecException("No suitable encoder found!"))).encode(Mono.just((T) data), bufferFactory, elementType, MimeTypeUtils.APPLICATION_JSON, hints).concatWith(encodeString("\n", bufferFactory));
}
Also used : Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) HashMap(java.util.HashMap) Mono(reactor.core.publisher.Mono) MimeTypeUtils(org.springframework.util.MimeTypeUtils) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) ArrayList(java.util.ArrayList) CodecException(org.springframework.core.codec.CodecException) Flux(reactor.core.publisher.Flux) List(java.util.List) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Map(java.util.Map) Optional(java.util.Optional) ResolvableType(org.springframework.core.ResolvableType) Collections(java.util.Collections) Encoder(org.springframework.core.codec.Encoder) Assert(org.springframework.util.Assert) Encoder(org.springframework.core.codec.Encoder) CodecException(org.springframework.core.codec.CodecException) ResolvableType(org.springframework.core.ResolvableType)

Example 4 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class Jackson2JsonEncoder method encode.

@Override
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
    Assert.notNull(inputStream, "'inputStream' must not be null");
    Assert.notNull(bufferFactory, "'bufferFactory' must not be null");
    Assert.notNull(elementType, "'elementType' must not be null");
    if (inputStream instanceof Mono) {
        return Flux.from(inputStream).map(value -> encodeValue(value, bufferFactory, elementType, hints));
    } else if (APPLICATION_STREAM_JSON.isCompatibleWith(mimeType)) {
        return Flux.from(inputStream).map(value -> {
            DataBuffer buffer = encodeValue(value, bufferFactory, elementType, hints);
            buffer.write(new byte[] { '\n' });
            return buffer;
        });
    }
    ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
    return Flux.from(inputStream).collectList().map(list -> encodeValue(list, bufferFactory, listType, hints)).flux();
}
Also used : SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) CodecException(org.springframework.core.codec.CodecException) MimeType(org.springframework.util.MimeType) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map) DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) JavaType(com.fasterxml.jackson.databind.JavaType) ResolvableType(org.springframework.core.ResolvableType) Encoder(org.springframework.core.codec.Encoder) OutputStream(java.io.OutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) DefaultIndenter(com.fasterxml.jackson.core.util.DefaultIndenter) DataBuffer(org.springframework.core.io.buffer.DataBuffer) APPLICATION_STREAM_JSON(org.springframework.http.MediaType.APPLICATION_STREAM_JSON) Flux(reactor.core.publisher.Flux) List(java.util.List) Jackson2ObjectMapperBuilder(org.springframework.http.converter.json.Jackson2ObjectMapperBuilder) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) PrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter) Assert(org.springframework.util.Assert) Mono(reactor.core.publisher.Mono) ResolvableType(org.springframework.core.ResolvableType) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 5 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-integration by spring-projects.

the class WebFluxRequestExecutingMessageHandlerTests method testFluxReply.

@Test
@SuppressWarnings("unchecked")
public void testFluxReply() {
    ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        DataBufferFactory bufferFactory = response.bufferFactory();
        Mono<DataBuffer> data = Mono.just(bufferFactory.wrap("foo\nbar\nbaz".getBytes()));
        return response.writeWith(data).then(Mono.defer(response::setComplete));
    });
    WebClient webClient = WebClient.builder().clientConnector(httpConnector).build();
    String destinationUri = "http://www.springsource.org/spring-integration";
    WebFluxRequestExecutingMessageHandler reactiveHandler = new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);
    QueueChannel replyChannel = new QueueChannel();
    reactiveHandler.setOutputChannel(replyChannel);
    reactiveHandler.setExpectedResponseType(String.class);
    reactiveHandler.setReplyPayloadToFlux(true);
    reactiveHandler.handleMessage(MessageBuilder.withPayload("hello, world").build());
    Message<?> receive = replyChannel.receive(10_000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(Flux.class));
    Flux<String> flux = (Flux<String>) receive.getPayload();
    StepVerifier.create(flux).expectNext("foo", "bar", "baz").verifyComplete();
}
Also used : ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) QueueChannel(org.springframework.integration.channel.QueueChannel) Flux(reactor.core.publisher.Flux) Matchers.containsString(org.hamcrest.Matchers.containsString) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) WebClient(org.springframework.web.reactive.function.client.WebClient) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Aggregations

DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)28 DataBuffer (org.springframework.core.io.buffer.DataBuffer)14 Mono (reactor.core.publisher.Mono)12 Flux (reactor.core.publisher.Flux)11 List (java.util.List)9 Publisher (org.reactivestreams.Publisher)8 Nullable (org.springframework.lang.Nullable)8 IOException (java.io.IOException)7 MediaType (org.springframework.http.MediaType)7 Assert (org.springframework.util.Assert)7 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)7 Collections (java.util.Collections)6 Resource (org.springframework.core.io.Resource)6 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 Supplier (java.util.function.Supplier)5 ResolvableType (org.springframework.core.ResolvableType)5 DataBufferUtils (org.springframework.core.io.buffer.DataBufferUtils)5 Test (org.junit.Test)4