Search in sources :

Example 6 with SubmissionPublisher

use of java.util.concurrent.SubmissionPublisher in project helidon by oracle.

the class RequestContentTest method multiThreadingFilterAndReaderTest.

@SuppressWarnings("unchecked")
@Test
public void multiThreadingFilterAndReaderTest() throws Exception {
    CountDownLatch subscribedLatch = new CountDownLatch(1);
    SubmissionPublisher<DataChunk> publisher = new SubmissionPublisher<>(Runnable::run, 10);
    ForkJoinPool.commonPool().submit(() -> {
        try {
            if (!subscribedLatch.await(10, TimeUnit.SECONDS)) {
                fail("Subscriber didn't subscribe in timely manner!");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Interrupted!", e);
        }
        publisher.submit(DataChunk.create("first".getBytes()));
        publisher.submit(DataChunk.create("second".getBytes()));
        publisher.submit(DataChunk.create("third".getBytes()));
        publisher.close();
    });
    Request request = requestTestStub(Multi.create(publisher));
    request.content().registerFilter(originalPublisher -> subscriberDelegate -> originalPublisher.subscribe(new Subscriber<DataChunk>() {

        @Override
        public void onSubscribe(Subscription subscription) {
            subscriberDelegate.onSubscribe(subscription);
            subscribedLatch.countDown();
        }

        @Override
        public void onNext(DataChunk item) {
            // mapping the on next call only
            subscriberDelegate.onNext(DataChunk.create(requestChunkAsString(item).toUpperCase().getBytes()));
        }

        @Override
        public void onError(Throwable throwable) {
            subscriberDelegate.onError(throwable);
        }

        @Override
        public void onComplete() {
            subscriberDelegate.onComplete();
        }
    }));
    request.content().registerReader(Iterable.class, (publisher1, clazz) -> {
        fail("Iterable reader should have not been used!");
        throw new IllegalStateException("unreachable code");
    });
    request.content().registerReader(ArrayList.class, (publisher1, clazz) -> {
        fail("ArrayList reader should have not been used!");
        throw new IllegalStateException("unreachable code");
    });
    request.content().registerReader(List.class, (publisher1, clazz) -> {
        CompletableFuture<List> future = new CompletableFuture<>();
        List<String> list = new CopyOnWriteArrayList<>();
        publisher1.subscribe(new Subscriber<DataChunk>() {

            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(Long.MAX_VALUE);
                subscribedLatch.countDown();
            }

            @Override
            public void onNext(DataChunk item) {
                list.add(TestUtils.requestChunkAsString(item));
            }

            @Override
            public void onError(Throwable throwable) {
                fail("Received an exception: " + throwable.getMessage());
            }

            @Override
            public void onComplete() {
                future.complete(list);
            }
        });
        return future;
    });
    List<String> result = (List<String>) request.content().as(List.class).toCompletableFuture().get(10, TimeUnit.SECONDS);
    assertThat(result, hasItems(is("FIRST"), is("SECOND"), is("THIRD")));
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) TestUtils.requestChunkAsString(io.helidon.webserver.utils.TestUtils.requestChunkAsString) StringContains.containsString(org.hamcrest.core.StringContains.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java.util.concurrent.CompletableFuture) Subscriber(java.util.concurrent.Flow.Subscriber) DataChunk(io.helidon.common.http.DataChunk) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Subscription(java.util.concurrent.Flow.Subscription) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 7 with SubmissionPublisher

use of java.util.concurrent.SubmissionPublisher in project helidon by oracle.

the class NettyWebServerTest method main.

/**
 * Start the test and then run:
 * <pre><code>
 *     seq 1000 | head -c 1000 | curl -X PUT -Ssf http://localhost:8080 --data-binary @- http://localhost:8080 --data ahoj
 * </code></pre>
 * <p>
 *
 * @throws InterruptedException if the main thread is interrupted
 */
static void main(String[] args) throws InterruptedException {
    WebServer webServer = WebServer.builder().port(8080).host("localhost").routing(routing((breq, bres) -> {
        SubmissionPublisher<DataChunk> responsePublisher = new SubmissionPublisher<>(ForkJoinPool.commonPool(), 1024);
        responsePublisher.subscribe(bres);
        final AtomicReference<Subscription> subscription = new AtomicReference<>();
        // Read request and immediately write to response
        Multi.create(breq.bodyPublisher()).subscribe((DataChunk chunk) -> {
            DataChunk responseChunk = DataChunk.create(true, chunk::release, chunk.data());
            responsePublisher.submit(responseChunk);
            ForkJoinPool.commonPool().submit(() -> {
                try {
                    Thread.sleep(1);
                    subscription.get().request(ThreadLocalRandom.current().nextLong(1, 3));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(e);
                }
            });
        }, (Throwable ex) -> {
            LOGGER.log(Level.WARNING, "An error occurred during the flow consumption!", ex);
        }, responsePublisher::close, (Subscription s) -> {
            subscription.set(s);
            s.request(1);
            bres.writeStatusAndHeaders(Http.Status.CREATED_201, Collections.emptyMap());
        });
    })).build();
    webServer.start();
    Thread.currentThread().join();
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) DataChunk(io.helidon.common.http.DataChunk) AtomicReference(java.util.concurrent.atomic.AtomicReference) Subscription(java.util.concurrent.Flow.Subscription)

Example 8 with SubmissionPublisher

use of java.util.concurrent.SubmissionPublisher in project reactive-streams-jvm by reactive-streams.

the class SubmissionPublisherTckTest method createFailedPublisher.

@Override
public Publisher<Integer> createFailedPublisher() {
    final SubmissionPublisher<Integer> sp = new SubmissionPublisher<Integer>();
    sp.closeExceptionally(new IOException());
    return FlowAdapters.toPublisher(sp);
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) IOException(java.io.IOException)

Example 9 with SubmissionPublisher

use of java.util.concurrent.SubmissionPublisher in project Java-9-Spring-Webflux by kkTranslation.

the class ConsumeSubmissionPublisher method publish.

public static void publish() throws InterruptedException, ExecutionException {
    CompletableFuture future = null;
    try (SubmissionPublisher publisher = new SubmissionPublisher<Long>()) {
        System.out.println("Subscriber Buffer Size: " + publisher.getMaxBufferCapacity());
        future = publisher.consume(System.out::println);
        LongStream.range(1, 10).forEach(publisher::submit);
    } finally {
        future.get();
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) SubmissionPublisher(java.util.concurrent.SubmissionPublisher)

Example 10 with SubmissionPublisher

use of java.util.concurrent.SubmissionPublisher in project java-course by bwhyman.

the class FlowTest method test2.

// 每个订阅者均会收到相同的消息
// 属于pub/sub模式,而非P2P模式
private static void test2() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(2);
    SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>();
    MySubscriber s1 = new MySubscriber(latch);
    MySubscriber s2 = new MySubscriber(latch);
    publisher.subscribe(s1);
    publisher.subscribe(s2);
    for (int i = 0; i < 10; i++) {
        publisher.submit(i);
    }
    latch.await();
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

SubmissionPublisher (java.util.concurrent.SubmissionPublisher)12 CountDownLatch (java.util.concurrent.CountDownLatch)3 Test (org.junit.jupiter.api.Test)3 DataChunk (io.helidon.common.http.DataChunk)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Executor (java.util.concurrent.Executor)2 Subscription (java.util.concurrent.Flow.Subscription)2 Test (org.testng.annotations.Test)2 Order (com.dockerx.reactive.orderstock.product.Order)1 OrderItem (com.dockerx.reactive.orderstock.product.OrderItem)1 Product (com.dockerx.reactive.orderstock.product.Product)1 Stock (com.dockerx.reactive.orderstock.stock.Stock)1 StockMaintain (com.dockerx.reactive.orderstock.stock.StockMaintain)1 TestUtils.requestChunkAsString (io.helidon.webserver.utils.TestUtils.requestChunkAsString)1 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1