Search in sources :

Example 1 with DataBufferUtils

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

the class MultipartHttpMessageWriter method writeMultipart.

private Mono<Void> writeMultipart(MultiValueMap<String, ?> map, ReactiveHttpOutputMessage outputMessage, @Nullable MediaType mediaType, Map<String, Object> hints) {
    byte[] boundary = generateMultipartBoundary();
    mediaType = getMultipartMediaType(mediaType, boundary);
    outputMessage.getHeaders().setContentType(mediaType);
    LogFormatUtils.traceDebug(logger, traceOn -> Hints.getLogPrefix(hints) + "Encoding " + (isEnableLoggingRequestDetails() ? LogFormatUtils.formatValue(map, !traceOn) : "parts " + map.keySet() + " (content masked)"));
    DataBufferFactory bufferFactory = outputMessage.bufferFactory();
    Flux<DataBuffer> body = Flux.fromIterable(map.entrySet()).concatMap(entry -> encodePartValues(boundary, entry.getKey(), entry.getValue(), bufferFactory)).concatWith(generateLastLine(boundary, bufferFactory)).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
    if (logger.isDebugEnabled()) {
        body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
    }
    return outputMessage.writeWith(body);
}
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) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 2 with DataBufferUtils

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

the class AbstractServerHttpResponse method writeWith.

@Override
@SuppressWarnings("unchecked")
public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
    // We must resolve value first however, for a chance to handle potential error.
    if (body instanceof Mono) {
        return ((Mono<? extends DataBuffer>) body).flatMap(buffer -> {
            touchDataBuffer(buffer);
            AtomicBoolean subscribed = new AtomicBoolean();
            return doCommit(() -> {
                try {
                    return writeWithInternal(Mono.fromCallable(() -> buffer).doOnSubscribe(s -> subscribed.set(true)).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release));
                } catch (Throwable ex) {
                    return Mono.error(ex);
                }
            }).doOnError(ex -> DataBufferUtils.release(buffer)).doOnCancel(() -> {
                if (!subscribed.get()) {
                    DataBufferUtils.release(buffer);
                }
            });
        }).doOnError(t -> getHeaders().clearContentHeaders()).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
    } else {
        return new ChannelSendOperator<>(body, inner -> doCommit(() -> writeWithInternal(inner))).doOnError(t -> getHeaders().clearContentHeaders());
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Publisher(org.reactivestreams.Publisher) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Flux(reactor.core.publisher.Flux) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) CollectionUtils(org.springframework.util.CollectionUtils) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ResponseCookie(org.springframework.http.ResponseCookie) Assert(org.springframework.util.Assert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Mono(reactor.core.publisher.Mono) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 3 with DataBufferUtils

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

the class ReactiveGridFsTemplateTests method storeSavesGridFsUploadWithGivenIdCorrectly.

// DATAMONGO-625
@Test
public void storeSavesGridFsUploadWithGivenIdCorrectly() throws IOException {
    String id = "id-1";
    byte[] content = StreamUtils.copyToByteArray(resource.getInputStream());
    Flux<DataBuffer> data = DataBufferUtils.read(resource, new DefaultDataBufferFactory(), 256);
    ReactiveGridFsUpload<String> upload = // 
    ReactiveGridFsUpload.fromPublisher(data).id(// 
    id).filename(// 
    "gridFsUpload.xml").contentType(// 
    "xml").build();
    operations.store(upload).as(StepVerifier::create).expectNext(id).verifyComplete();
    operations.findOne(query(where("_id").is(id))).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();
    operations.findOne(query(where("_id").is(id))).as(StepVerifier::create).consumeNextWith(it -> {
        assertThat(it.getFilename()).isEqualTo("gridFsUpload.xml");
        assertThat(it.getId()).isEqualTo(new BsonString(id));
        assertThat(it.getMetadata()).containsValue("xml");
    }).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) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) BsonString(org.bson.BsonString) BsonString(org.bson.BsonString) StepVerifier(reactor.test.StepVerifier) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 4 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 5 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)

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