Search in sources :

Example 6 with DataBufferUtils

use of org.springframework.core.io.buffer.DataBufferUtils in project spring-data-mongodb by spring-projects.

the class ReactiveGridFsTemplateTests method getResourceShouldRetrieveContentByIdentity.

// DATAMONGO-1855
@Test
public void getResourceShouldRetrieveContentByIdentity() throws IOException {
    byte[] content = StreamUtils.copyToByteArray(resource.getInputStream());
    Flux<DataBuffer> source = DataBufferUtils.read(resource, new DefaultDataBufferFactory(), 256);
    ObjectId reference = operations.store(source, "foo.xml", null, null).block();
    operations.findOne(query(where("_id").is(reference))).flatMap(operations::getResource).flatMapMany(// 
    ReactiveGridFsResource::getDownloadStream).transform(// 
    DataBufferUtils::join).as(// 
    StepVerifier::create).consumeNextWith(dataBuffer -> {
        byte[] actual = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(actual);
        assertThat(actual).isEqualTo(content);
    }).verifyComplete();
}
Also used : Document(org.bson.Document) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) StepVerifier(reactor.test.StepVerifier) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) RunWith(org.junit.runner.RunWith) ClassPathResource(org.springframework.core.io.ClassPathResource) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) Autowired(org.springframework.beans.factory.annotation.Autowired) BsonString(org.bson.BsonString) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) ByteBuffer(java.nio.ByteBuffer) Assertions(org.assertj.core.api.Assertions) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Sort(org.springframework.data.domain.Sort) SpringRunner(org.springframework.test.context.junit4.SpringRunner) Before(org.junit.Before) Resource(org.springframework.core.io.Resource) StreamUtils(org.springframework.util.StreamUtils) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) BsonObjectId(org.bson.BsonObjectId) PageRequest(org.springframework.data.domain.PageRequest) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) Test(org.junit.Test) GridFsCriteria(org.springframework.data.mongodb.gridfs.GridFsCriteria) DataBuffer(org.springframework.core.io.buffer.DataBuffer) InputStreamReader(java.io.InputStreamReader) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) Flux(reactor.core.publisher.Flux) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ContextConfiguration(org.springframework.test.context.ContextConfiguration) ObjectId(org.bson.types.ObjectId) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) HexUtils(com.mongodb.internal.HexUtils) FileCopyUtils(org.springframework.util.FileCopyUtils) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) BsonObjectId(org.bson.BsonObjectId) ObjectId(org.bson.types.ObjectId) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) StepVerifier(reactor.test.StepVerifier) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 7 with DataBufferUtils

use of org.springframework.core.io.buffer.DataBufferUtils 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 8 with DataBufferUtils

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

the class ServerSentEventHttpMessageWriter method encode.

private Flux<Publisher<DataBuffer>> encode(Publisher<?> input, ResolvableType elementType, MediaType mediaType, DataBufferFactory factory, Map<String, Object> hints) {
    ResolvableType dataType = (ServerSentEvent.class.isAssignableFrom(elementType.toClass()) ? elementType.getGeneric() : elementType);
    return Flux.from(input).map(element -> {
        ServerSentEvent<?> sse = (element instanceof ServerSentEvent ? (ServerSentEvent<?>) element : ServerSentEvent.builder().data(element).build());
        StringBuilder sb = new StringBuilder();
        String id = sse.id();
        String event = sse.event();
        Duration retry = sse.retry();
        String comment = sse.comment();
        Object data = sse.data();
        if (id != null) {
            writeField("id", id, sb);
        }
        if (event != null) {
            writeField("event", event, sb);
        }
        if (retry != null) {
            writeField("retry", retry.toMillis(), sb);
        }
        if (comment != null) {
            sb.append(':').append(StringUtils.replace(comment, "\n", "\n:")).append('\n');
        }
        if (data != null) {
            sb.append("data:");
        }
        Flux<DataBuffer> result;
        if (data == null) {
            result = Flux.just(encodeText(sb + "\n", mediaType, factory));
        } else if (data instanceof String) {
            data = StringUtils.replace((String) data, "\n", "\ndata:");
            result = Flux.just(encodeText(sb + (String) data + "\n\n", mediaType, factory));
        } else {
            result = encodeEvent(sb, data, dataType, mediaType, factory, hints);
        }
        return result.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
    });
}
Also used : DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Duration(java.time.Duration) ResolvableType(org.springframework.core.ResolvableType) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 9 with DataBufferUtils

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

the class DefaultRSocketRequesterBuilder method getSetupPayload.

private Mono<Payload> getSetupPayload(MimeType dataMimeType, MimeType metaMimeType, RSocketStrategies strategies) {
    Object data = this.setupData;
    boolean hasMetadata = (this.setupRoute != null || !CollectionUtils.isEmpty(this.setupMetadata));
    if (!hasMetadata && data == null) {
        return Mono.just(EMPTY_SETUP_PAYLOAD);
    }
    Mono<DataBuffer> dataMono = Mono.empty();
    if (data != null) {
        ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(data.getClass());
        Assert.isTrue(adapter == null || !adapter.isMultiValue(), "Expected single value: " + data);
        Mono<?> mono = (adapter != null ? Mono.from(adapter.toPublisher(data)) : Mono.just(data));
        dataMono = mono.map(value -> {
            ResolvableType type = ResolvableType.forClass(value.getClass());
            Encoder<Object> encoder = strategies.encoder(type, dataMimeType);
            Assert.notNull(encoder, () -> "No encoder for " + dataMimeType + ", " + type);
            return encoder.encodeValue(value, strategies.dataBufferFactory(), type, dataMimeType, HINTS);
        });
    }
    Mono<DataBuffer> metaMono = Mono.empty();
    if (hasMetadata) {
        metaMono = new MetadataEncoder(metaMimeType, strategies).metadataAndOrRoute(this.setupMetadata, this.setupRoute, this.setupRouteVars).encode();
    }
    Mono<DataBuffer> emptyBuffer = Mono.fromCallable(() -> strategies.dataBufferFactory().wrap(EMPTY_BYTE_ARRAY));
    dataMono = dataMono.switchIfEmpty(emptyBuffer);
    metaMono = metaMono.switchIfEmpty(emptyBuffer);
    return Mono.zip(dataMono, metaMono).map(tuple -> PayloadUtils.createPayload(tuple.getT1(), tuple.getT2())).doOnDiscard(DataBuffer.class, DataBufferUtils::release).doOnDiscard(Payload.class, Payload::release);
}
Also used : ClientTransport(io.rsocket.transport.ClientTransport) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) Decoder(org.springframework.core.codec.Decoder) LoadbalanceTarget(io.rsocket.loadbalance.LoadbalanceTarget) PayloadDecoder(io.rsocket.frame.decoder.PayloadDecoder) WebsocketClientTransport(io.rsocket.transport.netty.client.WebsocketClientTransport) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) MimeType(org.springframework.util.MimeType) WellKnownMimeType(io.rsocket.metadata.WellKnownMimeType) Map(java.util.Map) DefaultPayload(io.rsocket.util.DefaultPayload) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) URI(java.net.URI) ResolvableType(org.springframework.core.ResolvableType) Encoder(org.springframework.core.codec.Encoder) ReactiveAdapter(org.springframework.core.ReactiveAdapter) RSocketConnector(io.rsocket.core.RSocketConnector) StringDecoder(org.springframework.core.codec.StringDecoder) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) MimeTypeUtils(org.springframework.util.MimeTypeUtils) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Consumer(java.util.function.Consumer) TcpClientTransport(io.rsocket.transport.netty.client.TcpClientTransport) List(java.util.List) LoadbalanceStrategy(io.rsocket.loadbalance.LoadbalanceStrategy) Payload(io.rsocket.Payload) LoadbalanceRSocketClient(io.rsocket.loadbalance.LoadbalanceRSocketClient) CollectionUtils(org.springframework.util.CollectionUtils) RSocketClient(io.rsocket.core.RSocketClient) Collections(java.util.Collections) Assert(org.springframework.util.Assert) Encoder(org.springframework.core.codec.Encoder) DefaultPayload(io.rsocket.util.DefaultPayload) Payload(io.rsocket.Payload) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 10 with DataBufferUtils

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

the class Jackson2JsonEncoderTests method encodeAsStreamWithCustomStreamingType.

// SPR-15727
@Test
public void encodeAsStreamWithCustomStreamingType() {
    MediaType fooMediaType = new MediaType("application", "foo");
    MediaType barMediaType = new MediaType("application", "bar");
    this.encoder.setStreamingMediaTypes(Arrays.asList(fooMediaType, barMediaType));
    Flux<Pojo> input = Flux.just(new Pojo("foo", "bar"), new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar"));
    testEncode(input, ResolvableType.forClass(Pojo.class), step -> step.consumeNextWith(expectString("{\"foo\":\"foo\",\"bar\":\"bar\"}\n").andThen(DataBufferUtils::release)).consumeNextWith(expectString("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n").andThen(DataBufferUtils::release)).consumeNextWith(expectString("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n").andThen(DataBufferUtils::release)).verifyComplete(), barMediaType, null);
}
Also used : Pojo(org.springframework.web.testfixture.xml.Pojo) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) MediaType(org.springframework.http.MediaType) Test(org.junit.jupiter.api.Test)

Aggregations

DataBufferUtils (org.springframework.core.io.buffer.DataBufferUtils)11 DataBuffer (org.springframework.core.io.buffer.DataBuffer)10 Mono (reactor.core.publisher.Mono)9 Flux (reactor.core.publisher.Flux)8 DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)7 Resource (org.springframework.core.io.Resource)6 IOException (java.io.IOException)5 Nullable (org.springframework.lang.Nullable)5 GridFSFile (com.mongodb.client.gridfs.model.GridFSFile)4 HexUtils (com.mongodb.internal.HexUtils)4 InputStreamReader (java.io.InputStreamReader)4 ByteBuffer (java.nio.ByteBuffer)4 Assertions (org.assertj.core.api.Assertions)4 BsonObjectId (org.bson.BsonObjectId)4 BsonString (org.bson.BsonString)4 Document (org.bson.Document)4 ObjectId (org.bson.types.ObjectId)4 Before (org.junit.Before)4 Test (org.junit.Test)4 RunWith (org.junit.runner.RunWith)4