Java Code Examples for org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams

The following examples show how to use org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: smallrye-mutiny   Source File: ConcatStageFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConcatenationWhenAllEmissionAreMadeFromMain() throws ExecutionException, InterruptedException {
    PublisherBuilder<Integer> f1 = ReactiveStreams.of(1, 2, 3);
    PublisherBuilder<Integer> f2 = ReactiveStreams.of(4, 5, 6);

    String currentThreadName = Thread.currentThread().getName();
    LinkedHashSet<String> threads = new LinkedHashSet<>();
    CompletionStage<List<Integer>> list = ReactiveStreams.concat(f1, f2)
            .peek(i -> threads.add(Thread.currentThread().getName()))
            .toList().run();
    await().until(() -> list.toCompletableFuture().isDone());

    List<Integer> ints = list.toCompletableFuture().get();
    assertThat(ints).containsExactly(1, 2, 3, 4, 5, 6);
    assertThat(threads).hasSize(1).contains(currentThreadName);
}
 
Example 2
private void processMethodReturningVoid() {
    if (configuration.isBlocking()) {
        this.subscriber = ReactiveStreams.<Message<?>> builder()
                .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m))
                        .onItem().produceUni(msg -> invokeBlocking(msg.getPayload()))
                        .onItemOrFailure().produceUni(handleInvocationResult(m))
                        .subscribeAsCompletionStage())
                .ignore();
    } else {
        this.subscriber = ReactiveStreams.<Message<?>> builder()
                .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m))
                        .onItem().apply(msg -> invoke(msg.getPayload()))
                        .onItemOrFailure().produceUni(handleInvocationResult(m))
                        .subscribeAsCompletionStage())
                .ignore();
    }
}
 
Example 3
Source Project: smallrye-mutiny   Source File: CoupledStageFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void coupledStageShouldCancelAndFailDownstreamWhenUpstreamFails() {
    CompletableFuture<Void> publisherCancelled = new CompletableFuture<>();
    CompletableFuture<Throwable> downstreamFailed = new CompletableFuture<>();

    ReactiveStreams.<Integer> failed(new QuietRuntimeException("failed"))
            .via(
                    ReactiveStreams.coupled(ReactiveStreams.builder().ignore(),
                            idlePublisher().onTerminate(() -> publisherCancelled.complete(null))))
            .onError(downstreamFailed::complete)
            .ignore()
            .run();

    await(publisherCancelled);
    assertTrue(await(downstreamFailed) instanceof QuietRuntimeException);
}
 
Example 4
@Test
public void testInjectingANullCompletionStage() {
    AtomicReference<Subscriber<? super String>> reference = new AtomicReference<>();
    Publisher<String> publisher = s -> {
        reference.set(s);
        s.onSubscribe(Subscriptions.empty());
    };

    CompletableFuture<List<String>> future = ReactiveStreams.fromPublisher(publisher)
            .flatMapCompletionStage(s -> (CompletionStage<String>) null)
            .toList()
            .run()
            .toCompletableFuture();

    reference.get().onNext("a");
    try {
        future.join();
        fail("exception expected");
    } catch (CompletionException e) {
        assertThat(e).hasCauseInstanceOf(NullPointerException.class);
    }
}
 
Example 5
@Test
public void create() throws ExecutionException, InterruptedException {
    List<Integer> list = ReactiveStreams.fromPublisher(Multi.createFrom().items(1, 2, 3)).toList().run()
            .toCompletableFuture()
            .get();
    assertThat(list).containsExactly(1, 2, 3);

    Optional<Integer> res = ReactiveStreams.fromPublisher(Multi.createFrom().item(25)).findFirst().run()
            .toCompletableFuture()
            .get();
    assertThat(res).contains(25);

    Optional<?> empty = ReactiveStreams.fromPublisher(Multi.createFrom().empty()).findFirst().run()
            .toCompletableFuture()
            .get();
    assertThat(empty).isEmpty();

    try {
        ReactiveStreams.fromPublisher(Multi.createFrom().failure(new Exception("Boom"))).findFirst().run()
                .toCompletableFuture().get();
        fail("Exception should be thrown");
    } catch (Exception e) {
        assertThat(e).hasMessageContaining("Boom");
    }
}
 
Example 6
@Test
public void create() throws ExecutionException, InterruptedException {
    List<Integer> list = ReactiveStreams.fromPublisher(Flowable.fromArray(1, 2, 3)).toList().run().toCompletableFuture()
            .get();
    assertThat(list).containsExactly(1, 2, 3);

    Optional<Integer> res = ReactiveStreams.fromPublisher(Flowable.just(25)).findFirst().run().toCompletableFuture().get();
    assertThat(res).contains(25);

    Optional<?> empty = ReactiveStreams.fromPublisher(Flowable.empty()).findFirst().run().toCompletableFuture().get();
    assertThat(empty).isEmpty();

    try {
        ReactiveStreams.fromPublisher(Flowable.error(new Exception("Boom"))).findFirst().run()
                .toCompletableFuture().get();
        fail("Exception should be thrown");
    } catch (Exception e) {
        assertThat(e).hasMessageContaining("Boom");
    }
}
 
Example 7
public static void main(String[] args) throws Exception {
    CamelContext context = new DefaultCamelContext();
    CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
    Subscriber<String> subscriber = camel
            .subscriber("file:./target?fileName=values.txt&fileExist=append", String.class);

    ReactiveStreams.of("hello", "from", "smallrye", "reactive", "stream", "operators",
            "using", "Apache", "Camel")
            .map(String::toUpperCase) // Transform the words
            .filter(s -> s.length() > 4) // Filter items
            .peek(System.out::println)
            .map(s -> s + " ")
            .to(subscriber)
            .run();
    context.start();

    // Just wait until it's done.
    Thread.sleep(1000);

    Files.readAllLines(new File("target/values.txt").toPath())
            .forEach(s -> System.out.println("File >> " + s));
}
 
Example 8
private void processMethodReturningACompletionStage() {
    boolean invokeWithPayload = MediatorConfiguration.Consumption.PAYLOAD == configuration.consumption();
    this.subscriber = ReactiveStreams.<Message<?>> builder()
            .flatMapCompletionStage(message -> Uni.createFrom().completionStage(handlePreProcessingAck(message))
                    .onItem().produceCompletionStage(m -> {
                        CompletionStage<?> stage;
                        if (invokeWithPayload) {
                            stage = invoke(message.getPayload());
                        } else {
                            stage = invoke(message);
                        }
                        return stage.thenApply(x -> message);
                    })
                    .onItemOrFailure().produceUni(handleInvocationResult(message))
                    .subscribeAsCompletionStage())
            .ignore();
}
 
Example 9
@Test
public void createOnVertxContext() {
    Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .subscribeOn(Schedulers.computation());

    AtomicBoolean completed = new AtomicBoolean();
    Set<String> threads = new LinkedHashSet<>();
    Callable<CompletionStage<List<String>>> callable = () -> ReactiveStreams.fromPublisher(flowable)
            .filter(i -> i < 4)
            .map(this::square)
            .onTerminate(() -> {
                completed.set(true);
                threads.add(Thread.currentThread().getName());
            })
            .map(this::asString)
            .toList()
            .run();

    executeOnEventLoop(callable).assertSuccess(Arrays.asList("1", "4", "9"));
    assertThat(completed).isTrue();
    assertThat(threads).hasSize(1).containsExactly(getCapturedThreadName());
}
 
Example 10
Source Project: smallrye-mutiny   Source File: CollectStageFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = QuietRuntimeException.class)
public void collectStageShouldPropagateErrorsFromFinisher() {
    CompletionStage<Object> result = ReactiveStreams.of(new Integer[] { 1, 2, 3 }).collect(Collector.of(
            () -> 0,
            (a, b) -> {
            },
            (a, b) -> a + b,
            (r) -> {
                throw new QuietRuntimeException("failed");
            }))
            .run();
    this.awaitCompletion(result);
}
 
Example 11
@Blocking
@Incoming("count")
@Outgoing("sink")
public ProcessorBuilder<Message<Integer>, Message<String>> process() {
    return ReactiveStreams.<Message<Integer>> builder()
            .map(Message::getPayload)
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .map(Message::of);
}
 
Example 12
@Outgoing("publisher-payload")
public Publisher<String> getAPublisherProducingPayload() {
    increment("publisher-payload");
    return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        .flatMap(i -> ReactiveStreams.of(i, i))
        .map(i -> Integer.toString(i))
        .buildRs();
}
 
Example 13
Source Project: quarkus   Source File: MyTestResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
public CompletionStage<String> compute() {
    return ReactiveStreams.of(1, 2, 3)
            .map(i -> i + 1) // 2, 3, 4
            .flatMapRsPublisher(x -> ReactiveStreams.of(x, x).buildRs()) // 2,2,3,3,4,4
            .distinct() // 2, 3, 4
            .limit(2) // 2, 3
            .collect(AtomicInteger::new, AtomicInteger::addAndGet)// 5
            .run()
            .thenApply(i -> Integer.toString(i.get())); // "5"
}
 
Example 14
@Test
public void createFromAlreadyFailedFuture() {
    CompletionStage<String> cs = new CompletableFuture<>();
    ((CompletableFuture<String>) cs).completeExceptionally(new Exception("Expected"));

    try {
        ReactiveStreams.fromCompletionStage(cs).findFirst().run().toCompletableFuture().join();
        fail("Exception expected");
    } catch (Exception e) {
        assertThat(e).hasMessageContaining("Expected");
    }
}
 
Example 15
@Incoming("count")
@Outgoing("sink")
public Processor<Integer, String> process() {
    return ReactiveStreams.<Integer> builder()
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .buildRs();
}
 
Example 16
@Incoming(PAYLOAD_NO_ACKNOWLEDGMENT_BUILDER)
@Acknowledgment(Acknowledgment.Strategy.NONE)
@Outgoing("sink-" + PAYLOAD_NO_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<String> processorWithNoAckWithPayloadBuilder(PublisherBuilder<String> input) {
    return input
            .flatMap(p -> ReactiveStreams.of(p, p))
            .peek(m -> processed(PAYLOAD_NO_ACKNOWLEDGMENT_BUILDER, m));
}
 
Example 17
@Test
public void createFromVertxContext() {
    Predicate<Integer> even = i -> i % 2 == 0;

    Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .subscribeOn(Schedulers.computation());

    Callable<CompletionStage<List<Integer>>> callable = () -> ReactiveStreams.fromPublisher(flowable).filter(even).toList()
            .run();

    executeOnEventLoop(callable).assertSuccess(Arrays.asList(2, 4, 6, 8, 10));
}
 
Example 18
Source Project: smallrye-mutiny   Source File: DistinctStageFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void create() throws ExecutionException, InterruptedException {
    Multi<Integer> publisher = Multi.createFrom()
            .items(1, 2, 1, 4, 3, 2, 5, 3, 6, 6, 4, 8, 7, 4, 5, 6, 7, 8, 9, 9, 10)
            .emitOn(executor);

    List<String> list = ReactiveStreams.fromPublisher(publisher)
            .filter(i -> i < 4)
            .distinct()
            .map(this::asString)
            .toList()
            .run().toCompletableFuture().get();

    assertThat(list).containsExactly("1", "2", "3");
}
 
Example 19
@Blocking
@Incoming("count")
@Outgoing("sink")
public PublisherBuilder<String> process(Integer payload) {
    return ReactiveStreams.of(payload)
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i));
}
 
Example 20
@Test
public void createFromFutureGoingToBeCompleted() {
    CompletableFuture<String> cf = new CompletableFuture<>();
    CompletionStage<Optional<String>> stage = ReactiveStreams.fromCompletionStageNullable(cf).findFirst().run();

    AtomicBoolean done = new AtomicBoolean();
    stage.whenComplete((res, err) -> {
        assertThat(err).isNull();
        assertThat(res).contains("Hello");
        done.set(true);
    });

    new Thread(() -> cf.complete("Hello")).start();
    await().untilAtomic(done, is(true));
}
 
Example 21
public void to() {
    //tag::to[]
    SubscriberBuilder<Integer, Optional<Integer>> subscriber
            = ReactiveStreams.<Integer>builder()
                .map(i -> i + 1)
                .findFirst();

    ReactiveStreams.of(1, 2, 3)
            .to(subscriber)
            .run()
            // Produce Optional[2]
            .thenAccept(optional ->
                    optional.ifPresent(i -> System.out.println("Result: " + i)));
    //end::to[]
}
 
Example 22
@Incoming("generator-message-async")
public Subscriber<Message<Integer>> getFromInfiniteAsyncMessageGenerator() {
    return ReactiveStreams.<Message<Integer>>builder()
        .limit(10)
        .map(Message::getPayload)
        .flatMap(i -> ReactiveStreams.of(i, i))
        .map(i -> Integer.toString(i))
        .forEach(s -> add("generator-message-async", s))
        .build();
}
 
Example 23
private void processMethodReturningAUniOfMessageAndConsumingIndividualMessage() {
    this.processor = ReactiveStreams.<Message<?>> builder()
            .flatMapRsPublisher(message -> Uni.createFrom().completionStage(handlePreProcessingAck(message))
                    .onItem().produceUni(x -> invoke(message))
                    .onItemOrFailure().produceUni((res, fail) -> handlePostInvocationWithMessage((Message) res, fail))
                    .onItem().produceMulti(this::handleSkip))
            .buildRs();
}
 
Example 24
@Incoming(DEFAULT_ACKNOWLEDGMENT)
@Outgoing("sink-" + DEFAULT_ACKNOWLEDGMENT)
public Processor<String, String> processorWithAutoAck() {
    return ReactiveStreams.<String> builder()
            .flatMap(m -> ReactiveStreams.of(m, m))
            .peek(m -> processed(DEFAULT_ACKNOWLEDGMENT, m))
            .buildRs();
}
 
Example 25
Source Project: smallrye-reactive-messaging   Source File: CollectorOnly.java    License: Apache License 2.0 5 votes vote down vote up
@Incoming("sink")
public Subscriber<Message<String>> sink() {
    CompletionSubscriber<Message<String>, List<Message<String>>> subscriber = ReactiveStreams.<Message<String>> builder()
            .toList().build();
    subscriber.getCompletion().thenAccept(result::addAll);
    return subscriber;
}
 
Example 26
@Incoming(PAYLOAD_DEFAULT_ACKNOWLEDGMENT_BUILDER)
@Outgoing("sink-" + PAYLOAD_DEFAULT_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<String> processorWithDefaultAckWithBuilderUsingPayload(PublisherBuilder<String> input) {
    return input
            .flatMap(p -> ReactiveStreams.of(p, p))
            .peek(m -> processed(PAYLOAD_DEFAULT_ACKNOWLEDGMENT_BUILDER, m));
}
 
Example 27
@Incoming("count")
@Outgoing("sink")
public Processor<Message<Integer>, Message<String>> process() {
    return ReactiveStreams.<Message<Integer>> builder()
            .map(Message::getPayload)
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .map(Message::of)
            .buildRs();
}
 
Example 28
@Test
public void createFromVertxContext() {
    Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .subscribeOn(Schedulers.computation());

    Callable<CompletionStage<List<Integer>>> callable = () -> ReactiveStreams.fromPublisher(flowable).dropWhile(i -> i < 6)
            .toList().run();

    executeOnEventLoop(callable).assertSuccess(Arrays.asList(6, 7, 8, 9, 10));
}
 
Example 29
public void collect() {
    //tag::collect[]
    ReactiveStreams.of(1, 2, 3)
            .collect(Collectors.summingInt(i -> i))
            .run()
            // Produce 6
            .thenAccept(res -> System.out.println("Result is: " + res));

    ReactiveStreams.of(1, 2, 3)
            .collect(() -> new AtomicInteger(1), AtomicInteger::addAndGet)
            .run()
            // Produce 7
            .thenAccept(res -> System.out.println("Result is: " + res));

    ReactiveStreams.of(1, 2, 3)
            .reduce((acc, item) -> acc + item)
            .run()
            // Produce Optional<6>
            .thenAccept(res -> res.ifPresent(sum ->
                    System.out.println("Result is: " + sum)));

    ReactiveStreams.of(1, 2, 3)
            .toList()
            .run()
            // Produce [1, 2, 3]
            .thenAccept(res -> System.out.println("Result is: " + res));
    //end::collect[]
}
 
Example 30
@Test
public void createWithProcessorBuildersFromVertxContext() {
    Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .subscribeOn(Schedulers.computation());

    executeOnEventLoop(() -> ReactiveStreams.fromPublisher(flowable)
            .filter(i -> i < 4)
            .via(duplicateProcessorBuilder())
            .via(asStringProcessorBuilder())
            .toList()
            .run()).assertSuccess(Arrays.asList("1", "1", "2", "2", "3", "3"));
}