Search in sources :

Example 1 with Publisher

use of org.reactivestreams.Publisher in project RxJava by ReactiveX.

the class TrampolineSchedulerTest method testTrampolineWorkerHandlesConcurrentScheduling.

/**
     * This is a regression test for #1702. Concurrent work scheduling that is improperly synchronized can cause an
     * action to be added or removed onto the priority queue during a poll, which can result in NPEs during queue
     * sifting. While it is difficult to isolate the issue directly, we can easily trigger the behavior by spamming the
     * trampoline with enqueue requests from multiple threads concurrently.
     */
@Test
public void testTrampolineWorkerHandlesConcurrentScheduling() {
    final Worker trampolineWorker = Schedulers.trampoline().createWorker();
    final Subscriber<Object> observer = TestHelper.mockSubscriber();
    final TestSubscriber<Disposable> ts = new TestSubscriber<Disposable>(observer);
    // Spam the trampoline with actions.
    Flowable.range(0, 50).flatMap(new Function<Integer, Publisher<Disposable>>() {

        @Override
        public Publisher<Disposable> apply(Integer count) {
            return Flowable.interval(1, TimeUnit.MICROSECONDS).map(new Function<Long, Disposable>() {

                @Override
                public Disposable apply(Long ount1) {
                    return trampolineWorker.schedule(Functions.EMPTY_RUNNABLE);
                }
            }).take(100);
        }
    }).subscribeOn(Schedulers.computation()).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Worker(io.reactivex.Scheduler.Worker) TestSubscriber(io.reactivex.subscribers.TestSubscriber) Publisher(org.reactivestreams.Publisher) Test(org.junit.Test)

Example 2 with Publisher

use of org.reactivestreams.Publisher 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 3 with Publisher

use of org.reactivestreams.Publisher in project spring-framework by spring-projects.

the class ServerSentEventHttpMessageWriter method write.

@Override
public Mono<Void> write(Publisher<?> inputStream, ResolvableType elementType, MediaType mediaType, ReactiveHttpOutputMessage outputMessage, Map<String, Object> hints) {
    outputMessage.getHeaders().setContentType(MediaType.TEXT_EVENT_STREAM);
    DataBufferFactory bufferFactory = outputMessage.bufferFactory();
    Flux<Publisher<DataBuffer>> body = encode(inputStream, bufferFactory, elementType, hints);
    return outputMessage.writeAndFlushWith(body);
}
Also used : Publisher(org.reactivestreams.Publisher) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory)

Example 4 with Publisher

use of org.reactivestreams.Publisher 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 Publisher

use of org.reactivestreams.Publisher in project spring-framework by spring-projects.

the class RxNettyHttpHandlerAdapter method handle.

@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> nativeRequest, HttpServerResponse<ByteBuf> nativeResponse) {
    Channel channel = nativeResponse.unsafeNettyChannel();
    NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(channel.alloc());
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    RxNettyServerHttpRequest request = new RxNettyServerHttpRequest(nativeRequest, bufferFactory, remoteAddress);
    RxNettyServerHttpResponse response = new RxNettyServerHttpResponse(nativeResponse, bufferFactory);
    Publisher<Void> result = this.httpHandler.handle(request, response).otherwise(ex -> {
        logger.error("Could not complete request", ex);
        nativeResponse.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return Mono.empty();
    }).doOnSuccess(aVoid -> logger.debug("Successfully completed request"));
    return RxReactiveStreams.toObservable(result);
}
Also used : HttpServerResponse(io.reactivex.netty.protocol.http.server.HttpServerResponse) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) Publisher(org.reactivestreams.Publisher) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) Observable(rx.Observable) Channel(io.netty.channel.Channel) RxReactiveStreams(rx.RxReactiveStreams) ByteBuf(io.netty.buffer.ByteBuf) HttpServerRequest(io.reactivex.netty.protocol.http.server.HttpServerRequest) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) RequestHandler(io.reactivex.netty.protocol.http.server.RequestHandler) Assert(org.springframework.util.Assert) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory)

Aggregations

Publisher (org.reactivestreams.Publisher)28 List (java.util.List)11 Mono (reactor.core.publisher.Mono)11 Test (org.junit.Test)9 Collections (java.util.Collections)8 Assert.assertSame (org.junit.Assert.assertSame)7 CharSequenceEncoder (org.springframework.core.codec.CharSequenceEncoder)7 HttpStatus (org.springframework.http.HttpStatus)7 EncoderHttpMessageWriter (org.springframework.http.codec.EncoderHttpMessageWriter)7 MockServerHttpRequest (org.springframework.mock.http.server.reactive.test.MockServerHttpRequest)7 Duration (java.time.Duration)6 CoreMatchers.instanceOf (org.hamcrest.CoreMatchers.instanceOf)6 CoreMatchers.startsWith (org.hamcrest.CoreMatchers.startsWith)6 Matchers.is (org.hamcrest.Matchers.is)6 Assert.assertEquals (org.junit.Assert.assertEquals)6 Assert.assertThat (org.junit.Assert.assertThat)6 Before (org.junit.Before)6 Subscriber (org.reactivestreams.Subscriber)6 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)6 Bean (org.springframework.context.annotation.Bean)6