Search in sources :

Example 1 with Flux

use of reactor.core.publisher.Flux in project spring-framework by spring-projects.

the class DataBufferUtils method skipUntilByteCount.

/**
	 * Skip buffers from the given {@link Publisher} until the total
	 * {@linkplain DataBuffer#readableByteCount() byte count} reaches
	 * the given maximum byte count, or until the publisher is complete.
	 * @param publisher the publisher to filter
	 * @param maxByteCount the maximum byte count
	 * @return a flux with the remaining part of the given publisher
	 */
public static Flux<DataBuffer> skipUntilByteCount(Publisher<DataBuffer> publisher, long maxByteCount) {
    Assert.notNull(publisher, "Publisher must not be null");
    Assert.isTrue(maxByteCount >= 0, "'maxByteCount' must be a positive number");
    AtomicLong byteCountDown = new AtomicLong(maxByteCount);
    return Flux.from(publisher).skipUntil(dataBuffer -> {
        int delta = -dataBuffer.readableByteCount();
        long currentCount = byteCountDown.addAndGet(delta);
        if (currentCount < 0) {
            return true;
        } else {
            DataBufferUtils.release(dataBuffer);
            return false;
        }
    }).map(dataBuffer -> {
        long currentCount = byteCountDown.get();
        if (currentCount < 0) {
            int skip = (int) (currentCount + dataBuffer.readableByteCount());
            byteCountDown.set(0);
            return dataBuffer.slice(skip, dataBuffer.readableByteCount() - skip);
        }
        return dataBuffer;
    });
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) Channels(java.nio.channels.Channels) BiFunction(java.util.function.BiFunction) Publisher(org.reactivestreams.Publisher) FluxSink(reactor.core.publisher.FluxSink) CompletionHandler(java.nio.channels.CompletionHandler) IOException(java.io.IOException) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) ByteBuffer(java.nio.ByteBuffer) SynchronousSink(reactor.core.publisher.SynchronousSink) AtomicLong(java.util.concurrent.atomic.AtomicLong) Flux(reactor.core.publisher.Flux) InputStream(java.io.InputStream) Channel(java.nio.channels.Channel) Assert(org.springframework.util.Assert) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 2 with Flux

use of reactor.core.publisher.Flux in project spring-framework by spring-projects.

the class ByteArrayDecoderTests method decode.

@Test
public void decode() {
    DataBuffer fooBuffer = stringBuffer("foo");
    DataBuffer barBuffer = stringBuffer("bar");
    Flux<DataBuffer> source = Flux.just(fooBuffer, barBuffer);
    Flux<byte[]> output = this.decoder.decode(source, ResolvableType.forClassWithGenerics(Publisher.class, byte[].class), null, Collections.emptyMap());
    StepVerifier.create(output).consumeNextWith(bytes -> assertArrayEquals("foo".getBytes(), bytes)).consumeNextWith(bytes -> assertArrayEquals("bar".getBytes(), bytes)).expectComplete().verify();
}
Also used : Flux(reactor.core.publisher.Flux) StepVerifier(reactor.test.StepVerifier) AbstractDataBufferAllocatingTestCase(org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase) Assert.assertFalse(org.junit.Assert.assertFalse) Publisher(org.reactivestreams.Publisher) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ResolvableType(org.springframework.core.ResolvableType) MimeTypeUtils(org.springframework.util.MimeTypeUtils) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Collections(java.util.Collections) Publisher(org.reactivestreams.Publisher) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 3 with Flux

use of reactor.core.publisher.Flux in project spring-framework by spring-projects.

the class ServerSentEventHttpMessageReader method read.

@Override
public Flux<Object> read(ResolvableType elementType, ReactiveHttpInputMessage inputMessage, Map<String, Object> hints) {
    boolean hasSseWrapper = ServerSentEvent.class.isAssignableFrom(elementType.getRawClass());
    ResolvableType dataType = (hasSseWrapper ? elementType.getGeneric(0) : elementType);
    return Flux.from(inputMessage.getBody()).concatMap(ServerSentEventHttpMessageReader::splitOnNewline).map(buffer -> {
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
        DataBufferUtils.release(buffer);
        return charBuffer.toString();
    }).bufferUntil(line -> line.equals("\n")).concatMap(rawLines -> {
        String[] lines = rawLines.stream().collect(joining()).split("\\r?\\n");
        ServerSentEvent<Object> event = buildEvent(lines, dataType, hints);
        return (hasSseWrapper ? Mono.just(event) : Mono.justOrEmpty(event.data()));
    }).cast(Object.class);
}
Also used : Decoder(org.springframework.core.codec.Decoder) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) CharBuffer(java.nio.CharBuffer) StringDecoder(org.springframework.core.codec.StringDecoder) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) MimeTypeUtils(org.springframework.util.MimeTypeUtils) DataBuffer(org.springframework.core.io.buffer.DataBuffer) IntPredicate(java.util.function.IntPredicate) StandardCharsets(java.nio.charset.StandardCharsets) Collectors.joining(java.util.stream.Collectors.joining) ArrayList(java.util.ArrayList) CodecException(org.springframework.core.codec.CodecException) Flux(reactor.core.publisher.Flux) List(java.util.List) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Duration(java.time.Duration) Map(java.util.Map) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) ResolvableType(org.springframework.core.ResolvableType) Collections(java.util.Collections) Assert(org.springframework.util.Assert) CharBuffer(java.nio.CharBuffer) ResolvableType(org.springframework.core.ResolvableType)

Example 4 with Flux

use of reactor.core.publisher.Flux 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 5 with Flux

use of reactor.core.publisher.Flux 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)

Aggregations

Flux (reactor.core.publisher.Flux)28 Test (org.junit.Test)21 ResolvableType (org.springframework.core.ResolvableType)15 Collections (java.util.Collections)11 DataBuffer (org.springframework.core.io.buffer.DataBuffer)11 MediaType (org.springframework.http.MediaType)11 Mono (reactor.core.publisher.Mono)11 StepVerifier (reactor.test.StepVerifier)9 MockServerHttpRequest (org.springframework.mock.http.server.reactive.test.MockServerHttpRequest)8 Duration (java.time.Duration)7 List (java.util.List)7 Assert.assertFalse (org.junit.Assert.assertFalse)7 DefaultDataBufferFactory (org.springframework.core.io.buffer.DefaultDataBufferFactory)7 Assert (org.springframework.util.Assert)7 Map (java.util.Map)6 Assert.assertTrue (org.junit.Assert.assertTrue)6 AbstractDataBufferAllocatingTestCase (org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase)6 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)6 Assert.assertEquals (org.junit.Assert.assertEquals)5 ReactiveHttpInputMessage (org.springframework.http.ReactiveHttpInputMessage)5