io.smallrye.mutiny.infrastructure.Infrastructure Java Examples

The following examples show how to use io.smallrye.mutiny.infrastructure.Infrastructure. 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 File: MutinyContextEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/resteasy-uni-cs")
public Uni<String> resteasyContextPropagationWithUniCreatedFromCSWithManagedExecutor(@Context UriInfo uriInfo) {
    CompletableFuture<String> ret = all.completedFuture("OK");
    return Uni.createFrom().completionStage(ret)
            .emitOn(Infrastructure.getDefaultExecutor())
            .onItem().apply(s -> {
                Assertions.assertNotNull(uriInfo.getAbsolutePath());
                try {
                    Assertions.assertTrue(
                            uriInfo.getAbsolutePath().toURL().toExternalForm().contains("/resteasy-uni-cs"));
                } catch (MalformedURLException e) {
                    throw new AssertionError(e);
                }
                return s;
            });
}
 
Example #2
Source File: MultiOnFailure.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
/**
 * Produces a new {@link Multi} invoking the given callback when the upstream {@link Multi} emits a failure
 * (matching the predicate if set).
 * <p>
 * If the callback throws an exception, a {@link io.smallrye.mutiny.CompositeException} is propagated downstream.
 * This exception is composed by the received failure and the thrown exception.
 *
 * @param callback the callback, must not be {@code null}
 * @return the new {@link Multi}
 */
public Multi<T> invoke(Consumer<Throwable> callback) {
    nonNull(callback, "callback");
    nonNull(predicate, "predicate");
    return Infrastructure.onMultiCreation(new MultiSignalConsumerOp<>(
            upstream,
            null,
            null,
            failure -> {
                if (predicate.test(failure)) {
                    callback.accept(failure);
                }
            },
            null,
            null,
            null,
            null));
}
 
Example #3
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatWhilstCancelledWithTake() {
    int num = 10;
    final AtomicInteger invocations = new AtomicInteger();
    final AtomicInteger count = new AtomicInteger();
    int value = Uni.createFrom().item(count::incrementAndGet)
            .repeat().whilst(x -> {
                invocations.incrementAndGet();
                return true;
            })
            .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
            .transform().byTakingFirstItems(num)
            .collectItems().last()
            .await().indefinitely();
    assertThat(num).isEqualTo(value);
    assertThat(count).hasValue(value);
    assertThat(invocations).hasValue(value);
}
 
Example #4
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestWithAtMost() {
    final AtomicInteger count = new AtomicInteger();
    MultiAssertSubscriber<Integer> subscriber = Uni.createFrom().item(count::incrementAndGet)
            .repeat().atMost(3)
            .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
            .subscribe().withSubscriber(MultiAssertSubscriber.create());

    subscriber.assertSubscribed().assertHasNotReceivedAnyItem();
    subscriber
            .request(2)
            .run(() -> {
                await().until(() -> subscriber.items().size() == 2);
                assertThat(subscriber.items()).containsExactly(1, 2);
                assertThat(count).hasValue(2);
            })
            .request(20)
            .run(() -> {
                await().until(() -> subscriber.items().size() == 3);
                assertThat(subscriber.items()).containsExactly(1, 2, 3);
                assertThat(count).hasValue(3);
            })
            .assertCompletedSuccessfully();
}
 
Example #5
Source File: CancelStageFactoryTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void create() throws ExecutionException, InterruptedException {
    TerminalStage<Long, Void> terminal = factory.create(null, new Stage.Cancel() {
    });
    AtomicBoolean cancelled = new AtomicBoolean();
    List<Long> list = new ArrayList<>();
    Multi<Long> publisher = Multi.createFrom().ticks().every(Duration.ofMillis(1000))
            .emitOn(Infrastructure.getDefaultExecutor())
            .onItem().invoke(list::add)
            .on().cancellation(() -> cancelled.set(true));
    CompletionStage<Void> stage = terminal.apply(publisher);
    stage.toCompletableFuture().get();

    await().untilAtomic(cancelled, is(true));
    assertThat(list).isEmpty();
    assertThat(cancelled).isTrue();
}
 
Example #6
Source File: UniOnNull.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
/**
 * If the current {@link Uni} fires {@code null} as item, the produced {@link Uni} emits the events produced
 * by an {@link Uni} supplied using the passed {@link Supplier}
 *
 * @param supplier the supplier to use to produce the uni, must not be {@code null}, must not return {@code null}s
 * @return the new {@link Uni}
 */
public Uni<T> switchTo(Supplier<Uni<? extends T>> supplier) {
    nonNull(supplier, "supplier");

    Uni<T> uni = upstream.onItem().produceUni(res -> {
        if (res != null) {
            return Uni.createFrom().item(res);
        } else {
            Uni<? extends T> produced;
            try {
                produced = supplier.get();
            } catch (Throwable e) {
                return Uni.createFrom().failure(e);
            }

            if (produced == null) {
                return Uni.createFrom().failure(new NullPointerException(SUPPLIER_PRODUCED_NULL));
            } else {
                return produced;
            }
        }
    });
    return Infrastructure.onUniCreation(uni);
}
 
Example #7
Source File: UniOnNull.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
/**
 * If the current {@link Uni} fires {@code null} as item, the produced {@link Uni} emits a failure produced
 * using the given {@link Supplier}.
 *
 * @param supplier the supplier to produce the failure, must not be {@code null}, must not produce {@code null}
 * @return the new {@link Uni}
 */
public Uni<T> failWith(Supplier<? extends Throwable> supplier) {
    nonNull(supplier, "supplier");

    return Infrastructure.onUniCreation(upstream.onItem().produceUni((item, emitter) -> {
        if (item != null) {
            emitter.complete(item);
            return;
        }
        Throwable throwable;
        try {
            throwable = supplier.get();
        } catch (Throwable e) {
            emitter.fail(e);
            return;
        }

        if (throwable == null) {
            emitter.fail(new NullPointerException(SUPPLIER_PRODUCED_NULL));
        } else {
            emitter.fail(throwable);
        }
    }));
}
 
Example #8
Source File: MultiTakeUntilOtherOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(MultiSubscriber<? super T> actual) {
    TakeUntilMainProcessor<T> mainSubscriber = new TakeUntilMainProcessor<>(actual);
    TakeUntilOtherSubscriber<U> otherSubscriber = new TakeUntilOtherSubscriber<>(mainSubscriber);
    other.subscribe(Infrastructure.onMultiSubscription(other, otherSubscriber));
    upstream.subscribe(Infrastructure.onMultiSubscription(upstream, mainSubscriber));
}
 
Example #9
Source File: MultiZipOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
void subscribe(List<Publisher<?>> sources) {
    for (int i = 0; i < sources.size(); i++) {
        if (cancelled || (!postponeFailure && failures.get() != null)) {
            return;
        }
        Publisher<?> publisher = sources.get(i);
        publisher.subscribe(Infrastructure.onMultiSubscription(publisher, subscribers.get(i)));
    }
}
 
Example #10
Source File: MultiConcatOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompletion() {
    if (wip.getAndIncrement() == 0) {
        Publisher<? extends T>[] a = upstreams;
        do {

            if (isCancelled()) {
                return;
            }

            int i = currentIndex;
            if (i == a.length) {
                downstream.onCompletion();
                return;
            }

            Publisher<? extends T> p = a[i];
            long c = emitted;
            if (c != 0L) {
                emitted = 0L;
                emitted(c);
            }
            p.subscribe(Infrastructure.onMultiSubscription(p, this));

            if (isCancelled()) {
                return;
            }

            currentIndex = ++i;
        } while (wip.decrementAndGet() != 0);
    }

}
 
Example #11
Source File: UniFailOnTimeout.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
public UniFailOnTimeout(Uni<I> upstream, Duration timeout, Supplier<? extends Throwable> supplier,
        ScheduledExecutorService executor) {
    super(nonNull(upstream, "upstream"));
    this.timeout = validate(timeout, "onTimeout");
    this.supplier = nonNull(supplier, "supplier");
    this.executor = executor == null ? Infrastructure.getDefaultWorkerPool() : executor;
}
 
Example #12
Source File: CancelStageFactory.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public <I, O> TerminalStage<I, O> create(Engine engine, Stage.Cancel stage) {
    Objects.requireNonNull(stage);
    return (Multi<I> flow) -> {
        //noinspection SubscriberImplementation
        flow.subscribe(new Subscriber<I>() {
            @Override
            public void onSubscribe(Subscription s) {
                s.cancel();
            }

            @Override
            public void onNext(I in) {
                // Do nothing.
            }

            @Override
            public void onError(Throwable t) {
                // Do nothing.
            }

            @Override
            public void onComplete() {
                // Do nothing.
            }
        });
        return Infrastructure.wrapCompletableFuture(CompletableFuture.completedFuture(null));
    };
}
 
Example #13
Source File: UniBlockingTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    // tag::code[]
    Uni<String> blocking = Uni.createFrom().item(this::invokeRemoteServiceUsingBlockingIO)
            .runSubscriptionOn(Infrastructure.getDefaultWorkerPool());
    // end::code[]
    assertThat(blocking.await().indefinitely()).isEqualTo("hello");
}
 
Example #14
Source File: UniRunSubscriptionOnTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFailure() {
    Uni.createFrom().<Void> failure(new IOException("boom"))
            .runSubscriptionOn(Infrastructure.getDefaultExecutor())
            .subscribe().withSubscriber(UniAssertSubscriber.create())
            .await()
            .assertFailure(IOException.class, "boom");
}
 
Example #15
Source File: UniBlockingTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmitOn() {
    // tag::code-emitOn[]
    Multi<String> multi = Multi.createFrom().items("john", "jack", "sue")
            .emitOn(Infrastructure.getDefaultWorkerPool())
            .onItem().apply(this::invokeRemoteServiceUsingBlockingIO);
    // end::code-emitOn[]
    assertThat(multi.collectItems().asList().await().indefinitely()).containsExactly("JOHN", "JACK", "SUE");
}
 
Example #16
Source File: DeferredMulti.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(MultiSubscriber<? super T> downstream) {
    Publisher<? extends T> publisher;
    try {
        publisher = supplier.get();
        if (publisher == null) {
            throw new NullPointerException(ParameterValidation.SUPPLIER_PRODUCED_NULL);
        }
    } catch (Throwable failure) {
        Subscriptions.fail(downstream, failure);
        return;
    }
    publisher.subscribe(Infrastructure.onMultiSubscription(publisher, downstream));
}
 
Example #17
Source File: MultiRetry.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
/**
 * Produces a {@link Multi} resubscribing to the current {@link Multi} at most {@code numberOfAttempts} time,
 * until it gets items followed by the completion event. On every failure, it re-subscribes.
 * <p>
 * If the number of attempt is reached, the last failure is propagated.
 *
 * @param numberOfAttempts the number of attempt, must be greater than zero
 * @return a new {@link Multi} retrying at most {@code numberOfAttempts} times to subscribe to the current
 *         {@link Multi} until it gets an item. When the number of attempt is reached, the last failure is propagated.
 */
public Multi<T> atMost(long numberOfAttempts) {
    ParameterValidation.positive(numberOfAttempts, "numberOfAttempts");
    if (backOffConfigured) {
        Function<Multi<Throwable>, Publisher<Long>> whenStreamFactory = ExponentialBackoff
                .randomExponentialBackoffFunction(numberOfAttempts, initialBackOff, maxBackoff, jitter,
                        Infrastructure.getDefaultWorkerPool());
        return Infrastructure.onMultiCreation(
                new MultiRetryWhenOp<>(upstream, whenStreamFactory));
    } else {
        return Infrastructure.onMultiCreation(new MultiRetryOp<>(upstream, numberOfAttempts));
    }

}
 
Example #18
Source File: MultiPublishOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void connect(ConnectableMultiConnection connection) {
    boolean doConnect;
    PublishSubscriber<T> ps;
    // we loop because concurrent connect/disconnect and termination may change the state
    for (;;) {
        // retrieve the current subscriber-to-source instance
        ps = current.get();
        // if there is none yet or the current has been disposed
        if (ps == null || ps.cancelled.get()) {
            // create a new subscriber-to-source
            PublishSubscriber<T> u = new PublishSubscriber<T>(current, bufferSize);
            // try setting it as the current subscriber-to-source
            if (!current.compareAndSet(ps, u)) {
                // did not work, perhaps a new subscriber arrived
                // and created a new subscriber-to-source as well, retry
                continue;
            }
            ps = u;
        }
        // if connect() was called concurrently, only one of them should actually
        // connect to the source
        doConnect = !ps.shouldConnect.get() && ps.shouldConnect.compareAndSet(false, true);
        break;
    }

    if (connection != null) {
        connection.accept(ps);
    }

    if (doConnect) {
        upstream.subscribe(Infrastructure.onMultiSubscription(upstream, ps));
    }
}
 
Example #19
Source File: MultiCombineLatestOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(MultiSubscriber<? super O> downstream) {
    if (downstream == null) {
        throw new NullPointerException("The subscriber must not be `null`");
    }
    List<Publisher<? extends I>> publishers = new ArrayList<>();
    this.upstreams.forEach(publishers::add);

    if (publishers.isEmpty()) {
        Subscriptions.complete(downstream);
        return;
    }

    if (publishers.size() == 1) {
        publishers.get(0).subscribe(
                Infrastructure.onMultiSubscription(publishers.get(0),
                        new MultiMapOp.MapProcessor<>(downstream,
                                x -> combinator.apply(Collections.singletonList(x)))));
        return;
    }

    CombineLatestCoordinator<I, O> coordinator = new CombineLatestCoordinator<>(downstream, combinator,
            publishers.size(),
            bufferSize, delayErrors);
    downstream.onSubscribe(coordinator);
    coordinator.subscribe(publishers);
}
 
Example #20
Source File: UniOnNull.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a default item if the current {@link Uni} fires {@code null} as item.
 * The new item is supplied by the given {@link Supplier}.
 *
 * @param supplier the supplier to produce the new item, must not be {@code null}, must not produce {@code null}
 * @return the new {@link Uni}
 */
public Uni<T> continueWith(Supplier<? extends T> supplier) {
    nonNull(supplier, "supplier");
    return Infrastructure.onUniCreation(upstream.onItem().apply(res -> {
        if (res != null) {
            return res;
        }
        T outcome = supplier.get();
        if (outcome == null) {
            throw new NullPointerException(SUPPLIER_PRODUCED_NULL);
        }
        return outcome;
    }));
}
 
Example #21
Source File: MultiItemCombineIterable.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
<O> Multi<O> combine(Function<List<?>, ? extends O> combinator) {
    if (latest) {
        if (collectFailures) {
            return Infrastructure.onMultiCreation(new MultiCombineLatestOp<>(iterable, combinator, 128, true));
        } else {
            return Infrastructure.onMultiCreation(new MultiCombineLatestOp<>(iterable, combinator, 128, false));
        }
    } else {
        if (collectFailures) {
            return Infrastructure.onMultiCreation(new MultiZipOp<>(iterable, combinator, 128, true));
        } else {
            return Infrastructure.onMultiCreation(new MultiZipOp<>(iterable, combinator, 128, false));
        }
    }
}
 
Example #22
Source File: MultiFlatMapOp.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(MultiSubscriber<? super O> subscriber) {
    if (subscriber == null) {
        throw new NullPointerException("The subscriber must not be `null`");
    }
    FlatMapMainSubscriber<I, O> sub = new FlatMapMainSubscriber<>(subscriber,
            mapper,
            postponeFailurePropagation,
            maxConcurrency,
            mainQueueSupplier,
            innerQueueSupplier);
    upstream.subscribe(
            Infrastructure.onMultiSubscription(upstream, new SafeSubscriber<>(new SerializedSubscriber<>(sub))));
}
 
Example #23
Source File: MultiOnEvent.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches an action that is executed when the {@link Multi} emits a completion or a failure or when the subscriber
 * cancels the subscription.
 *
 * @param callback the consumer receiving the failure if any and a boolean indicating whether the termination
 *        is due to a cancellation (the failure parameter would be {@code null} in this case). Must not
 *        be {@code null}.
 * @return the new {@link Multi}
 */
public Multi<T> termination(BiConsumer<Throwable, Boolean> callback) {
    return Infrastructure.onMultiCreation(new MultiSignalConsumerOp<>(
            upstream,
            null,
            null,
            null,
            null,
            callback,
            null,
            null));
}
 
Example #24
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestAndCancellationWithRepeatWhilst() {
    final AtomicInteger count = new AtomicInteger();
    MultiAssertSubscriber<Integer> subscriber = Uni.createFrom().item(count::incrementAndGet)
            .repeat().whilst(x -> true)
            .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
            .subscribe().withSubscriber(MultiAssertSubscriber.create());

    subscriber.assertSubscribed().assertHasNotReceivedAnyItem();
    subscriber
            .request(2)
            .run(() -> {
                await().until(() -> subscriber.items().size() == 2);
                assertThat(subscriber.items()).containsExactly(1, 2);
                assertThat(count).hasValue(2);
            })
            .request(1)
            .run(() -> {
                await().until(() -> subscriber.items().size() == 3);
                assertThat(subscriber.items()).containsExactly(1, 2, 3);
                assertThat(count).hasValue(3);
            })
            .cancel()
            .run(() -> {
                await().until(() -> subscriber.items().size() == 3);
                assertThat(subscriber.items()).containsExactly(1, 2, 3);
                assertThat(count).hasValue(3);
            })
            .request(20)
            .run(() -> {
                await().until(() -> subscriber.items().size() == 3);
                assertThat(subscriber.items()).containsExactly(1, 2, 3);
                assertThat(count).hasValue(3);
            });
}
 
Example #25
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoStackOverflowWithRepeatWhilst() {
    AtomicInteger count = new AtomicInteger();
    int value = Uni.createFrom().item(1).repeat().whilst(x -> count.incrementAndGet() < 100000000L)
            .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
            .transform().byTakingFirstItems(100000L)
            .collectItems().last()
            .await().indefinitely();
    assertThat(value).isEqualTo(1);
}
 
Example #26
Source File: MultiBroadcaster.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
private static <T> Multi<T> createPublishImmediate(Multi<T> upstream, boolean cancelWhenNoOneIsListening,
        Duration delayAfterLastDeparture) {
    if (cancelWhenNoOneIsListening) {
        if (delayAfterLastDeparture != null) {
            return Infrastructure
                    .onMultiCreation(MultiPublishOp.create(upstream).referenceCount(1, delayAfterLastDeparture));
        } else {
            return Infrastructure.onMultiCreation(MultiPublishOp.create(upstream).referenceCount());
        }
    } else {
        return Infrastructure.onMultiCreation(MultiPublishOp.create(upstream).connectAfter(1));
    }
}
 
Example #27
Source File: MultiContextPropagationTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void initContext() {
    Infrastructure.clearInterceptors();
    Infrastructure.reloadUniInterceptors();
    Infrastructure.reloadMultiInterceptors();
    MyContext.init();
}
 
Example #28
Source File: MutinyInfrastructure.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void configureMutinyInfrastructure(ExecutorService exec) {
    Infrastructure.setDefaultExecutor(exec);
}
 
Example #29
Source File: MutinyContextManagerExtension.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
@Override
public void setup(ContextManager manager) {
    ThreadContext threadContext = manager.newThreadContextBuilder().build();
    Infrastructure.setCompletableFutureWrapper(threadContext::withContextCapture);
}
 
Example #30
Source File: GreetingService.java    From quarkus-quickstarts with Apache License 2.0 4 votes vote down vote up
public Uni<String> greeting(String name) {
    return Uni.createFrom().item("hello " + name)
            .emitOn(Infrastructure.getDefaultExecutor());
}