io.smallrye.mutiny.Uni Java Examples

The following examples show how to use io.smallrye.mutiny.Uni. 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: HibernateReactiveTestEndpoint.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@GET
@Path("/reactiveRemoveTransientEntity")
@Produces(MediaType.APPLICATION_JSON)
public Uni<String> reactiveRemoveTransientEntity() {
    return mutinySession
            .flatMap(mutinySession -> {
                return populateDB()
                        .flatMap(junk -> selectNameFromId(5))
                        .map(name -> {
                            if (name == null)
                                throw new AssertionError("Database was not populated properly");
                            return name;
                        })
                        .flatMap(junk -> mutinySession.merge(new GuineaPig(5, "Aloi")))
                        .flatMap(aloi -> mutinySession.remove(aloi))
                        .flatMap(junk -> mutinySession.flush())
                        .flatMap(junk -> selectNameFromId(5))
                        .map(result -> {
                            if (result == null)
                                return "OK";
                            else
                                return result;
                        });
            });
}
 
Example #2
Source File: UniOnNotNullItemTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testApply() {
    assertThat(Uni.createFrom().item("hello")
            .onItem().ifNotNull().apply(String::toUpperCase)
            .await().indefinitely()).isEqualTo("HELLO");

    assertThat(Uni.createFrom().item(() -> (String) null)
            .onItem().ifNotNull().apply(String::toUpperCase)
            .onItem().ifNull().continueWith("yolo")
            .await().indefinitely()).isEqualTo("yolo");

    assertThatThrownBy(() -> Uni.createFrom().<String> failure(new Exception("boom"))
            .onItem().ifNotNull().apply(String::toUpperCase)
            .onItem().ifNull().continueWith("yolo")
            .await().indefinitely()).hasMessageContaining("boom");
}
 
Example #3
Source File: StartFromFifthOffsetFromLatestButFailOnFirstConsumerRebalanceListener.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<Void> onPartitionsAssigned(KafkaConsumer<?, ?> consumer, Set<TopicPartition> set) {
    // will perform the underlying operation but simulate an error on the first attempt
    return super.onPartitionsAssigned(consumer, set)
            .onItem()
            .produceUni(a -> {
                if (!set.isEmpty() && failOnFirstAttempt.getAndSet(false)) {
                    return Uni
                            .createFrom()
                            .failure(new Exception("testing failure"));
                } else {
                    return Uni
                            .createFrom()
                            .item(a);
                }
            });
}
 
Example #4
Source File: MultiOnItem.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
/**
 * Produces a new {@link Multi} invoking the given @{code action} when an {@code item} event is received. Note that
 * the received item cannot be {@code null}.
 * <p>
 * Unlike {@link #invoke(Consumer)}, the passed function returns a {@link Uni}. When the produced {@code Uni} sends
 * its result, the result is discarded, and the original {@code item} is forwarded downstream. If the produced
 * {@code Uni} fails, the failure is propagated downstream.
 *
 * If the asynchronous action throws an exception, this exception is propagated downstream.
 *
 * This method preserves the order of the items, meaning that the downstream received the items in the same order
 * as the upstream has emitted them.
 *
 * @param action the function taking the item and returning a {@link Uni}, must not be {@code null}
 * @return the new {@link Multi}
 */
public Multi<T> invokeUni(Function<? super T, ? extends Uni<?>> action) {
    ParameterValidation.nonNull(action, "action");
    return produceUni(i -> {
        Uni<?> uni = action.apply(i);
        if (uni == null) {
            throw new NullPointerException("The `action` produced a `null` Uni");
        }
        return uni.onItemOrFailure().produceUni((ignored, failure) -> {
            if (failure != null) {
                return Uni.createFrom().failure(failure);
            } else {
                return Uni.createFrom().item(i);
            }
        });
    }).concatenate();
}
 
Example #5
Source File: UniOnFailureInvokeTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeUniNotCalledOnItem() {
    AtomicReference<Throwable> container = new AtomicReference<>();
    AtomicInteger called = new AtomicInteger(-1);
    int res = Uni.createFrom().item(3)
            .onFailure().invokeUni(t -> {
                container.set(t);
                return Uni.createFrom().item(22).onItem().invoke(called::set);
            })
            .onFailure().recoverWithItem(1)
            .await().indefinitely();

    assertThat(res).isEqualTo(3);
    assertThat(container).hasValue(null);
    assertThat(called).hasValue(-1);
}
 
Example #6
Source File: UniOnItemFlatMapToCompletionStageTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCancellationBeforeEmission() {
    UniAssertSubscriber<Integer> test = UniAssertSubscriber.create();
    AtomicBoolean cancelled = new AtomicBoolean();
    @SuppressWarnings("unchecked")
    CompletableFuture<Integer> future = new CompletableFuture() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            cancelled.set(true);
            return true;
        }
    };

    Uni<Integer> uni = Uni.createFrom().item(1).onItem().produceCompletionStage(v -> future);
    uni.subscribe().withSubscriber(test);
    test.cancel();
    test.assertNotCompleted();
    assertThat(cancelled).isTrue();
}
 
Example #7
Source File: MultiToUniTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromAnUniSendingResultEventInTheFuture() {
    AtomicInteger count = new AtomicInteger();

    Multi<Integer> multi = Multi.createFrom()
            .completionStage(() -> CompletableFuture.supplyAsync(count::incrementAndGet));

    multi.toUni().subscribe().withSubscriber(UniAssertSubscriber.create())
            .await()
            .assertItem(1)
            .assertCompletedSuccessfully();

    Uni.createFrom().multi(multi).subscribe().withSubscriber(UniAssertSubscriber.create())
            .await()
            .assertItem(2)
            .assertCompletedSuccessfully();
}
 
Example #8
Source File: MutinyContextEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Transactional
@GET
@Path("/transaction-uni")
public Uni<String> contextPropagationWithTxAndUni() throws SystemException {
    SomeEntity.deleteAll();
    Uni<String> ret = Uni.createFrom().item("OK");
    SomeEntity entity = new SomeEntity();
    entity.name = "Stef";
    entity.persist();
    Transaction t1 = Panache.getTransactionManager().getTransaction();
    Assertions.assertNotNull(t1);

    return ret
            .emitOn(executor)
            .map(text -> {
                Assertions.assertEquals(1, SomeEntity.count());
                Transaction t2;
                try {
                    t2 = Panache.getTransactionManager().getTransaction();
                } catch (SystemException e) {
                    throw new RuntimeException(e);
                }
                Assertions.assertEquals(t1, t2);
                return text;
            });
}
 
Example #9
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoRepeatUntil() {
    AtomicInteger count = new AtomicInteger();
    List<Integer> list = Uni.createFrom().item(count::getAndIncrement)
            .repeat().until(x -> true)
            .collectItems().asList()
            .await().indefinitely();

    assertThat(list).isEmpty();
    assertThat(count).hasValue(1);
}
 
Example #10
Source File: ReactiveFruitService.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
public Uni<List<Fruit>> list() {
    return getCollection().find()
            .map(doc -> {
                Fruit fruit = new Fruit();
                fruit.setName(doc.getString("name"));
                fruit.setDescription(doc.getString("description"));
                return fruit;
            }).collectItems().asList();
}
 
Example #11
Source File: ReactorTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void uniExportToReactor() {
    Uni<String> uni = Uni.createFrom().item("hello");
    // tag::uni-export[]
    Mono<String> mono = uni.convert().with(UniReactorConverters.toMono());
    Flux<String> flux = uni.convert().with(UniReactorConverters.toFlux());
    // end::uni-export[]

    assertThat(mono.block()).isEqualTo("hello");
    assertThat(flux.blockFirst()).isEqualTo("hello");
}
 
Example #12
Source File: BeanWithProcessorsManipulatingPayloads.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming(NO_ACKNOWLEDGMENT_CS)
@Acknowledgment(Acknowledgment.Strategy.NONE)
@Outgoing("sink-" + NO_ACKNOWLEDGMENT_UNI)
public Uni<String> processorWithNoAckUni(String input) {
    return Uni.createFrom().item(() -> {
        processed(NO_ACKNOWLEDGMENT_UNI, input);
        return input + "1";
    });
}
 
Example #13
Source File: UniFromPublisherTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatValueIsNotEmittedBeforeSubscription() {
    UniAssertSubscriber<Integer> ts = UniAssertSubscriber.create();
    AtomicBoolean called = new AtomicBoolean();
    Uni<Integer> uni = Uni.createFrom().publisher(Flowable.generate(emitter -> {
        called.set(true);
        emitter.onNext(1);
        emitter.onComplete();
    }));

    assertThat(called).isFalse();
    uni.subscribe().withSubscriber(ts);
    ts.assertCompletedSuccessfully().assertItem(1);
    assertThat(called).isTrue();
}
 
Example #14
Source File: VoidFunction.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Funq("void-function")
public Uni<Void> voidFunction(boolean willThrow) {
    if (willThrow) {
        return Uni.createFrom().failure(new RuntimeException(TEST_EXCEPTION_MSG));
    } else {
        return Uni.createFrom().item((Void) null);
    }
}
 
Example #15
Source File: MutinySchedulerTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeout() {
    AtomicReference<String> thread = new AtomicReference<>();

    Uni.createFrom().emitter(e -> {
        // do nothing
    })
            .ifNoItem().after(Duration.ofMillis(10)).recoverWithItem("hello")
            .onItem().invoke(l -> thread.set(Thread.currentThread().getName()))
            .await().indefinitely();
    assertThat(thread.get()).startsWith("my-thread-");
}
 
Example #16
Source File: UniCreateFromCompletionStageTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithExceptionThrownByAStage() {
    UniAssertSubscriber<String> ts = UniAssertSubscriber.create();
    CompletionStage<String> cs = new CompletableFuture<>();
    Uni.createFrom().completionStage(() -> cs
            .thenApply(String::toUpperCase)
            .<String> thenApply(s -> {
                throw new IllegalStateException("boom");
            })).subscribe().withSubscriber(ts);
    cs.toCompletableFuture().complete("bonjour");
    ts.assertFailure(IllegalStateException.class, "boom");
}
 
Example #17
Source File: DelayTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelayMultiRandom() {
    // tag::delay-multi-random[]
    Random random = new Random();
    List<Integer> delayed = Multi.createFrom().items(1, 2, 3, 4, 5)
            .onItem().produceUni(i -> Uni.createFrom().item(i).onItem().delayIt().by(Duration.ofMillis(random.nextInt(100) + 1)))
            .merge()
            .collectItems().asList()
            .await().indefinitely();
    // end::delay-multi-random[]
    assertThat(delayed).containsExactlyInAnyOrder(1, 2, 3, 4, 5);
}
 
Example #18
Source File: UniAndTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFourUnisAndDeprecatedApis() {
    Uni<Integer> uni = Uni.createFrom().item(1);
    Uni<Integer> uni2 = Uni.createFrom().item(2);
    Uni<Integer> uni3 = Uni.createFrom().item(3);

    UniAssertSubscriber<Tuple4<Integer, Integer, Integer, Integer>> subscriber = uni.and()
            .unis(uni, uni2, uni3).asTuple()
            .subscribe().withSubscriber(UniAssertSubscriber.create());

    assertThat(subscriber.getItem().asList()).containsExactly(1, 1, 2, 3);
}
 
Example #19
Source File: OAuth2AuthMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the Authorization header and validate the bearer token if it exists. If it does, and is validated, this
 * builds the org.jboss.security.SecurityContext authenticated Subject that drives the container APIs as well as
 * the authorization layers.
 *
 * @param context - the http request exchange object
 * @param identityProviderManager - the current security context that
 * @return one of AUTHENTICATED, NOT_AUTHENTICATED or NOT_ATTEMPTED depending on the header and authentication outcome.
 */
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {
    String authHeader = context.request().headers().get("Authorization");
    String bearerToken = authHeader != null ? authHeader.substring(7) : null;
    if (bearerToken != null) {
        // Install the OAuth2 principal as the caller
        return identityProviderManager
                .authenticate(new TokenAuthenticationRequest(new TokenCredential(bearerToken, "bearer")));

    }
    // No suitable header has been found in this request,
    return Uni.createFrom().nullItem();
}
 
Example #20
Source File: UniOnItemDelayTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatDelayDoNotImpactFailures() {
    long begin = System.currentTimeMillis();
    UniAssertSubscriber<Void> subscriber = UniAssertSubscriber.create();
    Uni.createFrom().<Void> failure(new Exception("boom")).onItem().delayIt()
            .onExecutor(executor)
            .by(Duration.ofMillis(100)).subscribe().withSubscriber(subscriber);
    subscriber.await();
    long end = System.currentTimeMillis();
    assertThat(end - begin).isLessThan(100);
    subscriber.assertCompletedWithFailure().assertFailure(Exception.class, "boom");
}
 
Example #21
Source File: MultiOnFailureInvokeUniTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeUniWithSubFailure() {
    AtomicReference<Throwable> failure = new AtomicReference<>();

    MultiAssertSubscriber<Integer> subscriber = failed.onFailure().invokeUni(i -> {
        failure.set(i);
        return Uni.createFrom().failure(new IllegalStateException("d'oh"));
    }).subscribe().withSubscriber(MultiAssertSubscriber.create(10));

    subscriber
            .assertHasFailedWith(CompositeException.class, "boom")
            .assertHasFailedWith(CompositeException.class, "d'oh")
            .assertReceived(1, 2);
    assertThat(failure).hasValue(BOOM);
}
 
Example #22
Source File: UniCreateFromCompletionStageTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithNonNullValue() {
    UniAssertSubscriber<String> ts = UniAssertSubscriber.create();
    CompletionStage<String> cs = new CompletableFuture<>();
    Uni.createFrom().completionStage(cs).subscribe().withSubscriber(ts);
    cs.toCompletableFuture().complete("1");
    ts.assertCompletedSuccessfully().assertItem("1");
}
 
Example #23
Source File: UniOnItemDelayTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testRejectedScheduling() {
    executor.shutdown();
    UniAssertSubscriber<Integer> subscriber = new UniAssertSubscriber<>();
    Uni.createFrom().item(1).onItem().delayIt()
            .onExecutor(executor)
            .by(Duration.ofMillis(100)).subscribe().withSubscriber(subscriber);
    subscriber.assertCompletedWithFailure().assertFailure(RejectedExecutionException.class, "");
}
 
Example #24
Source File: UniConvertToTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingACompletableWithFailure() {
    Completable completable = Uni.createFrom().failure(new IOException("boom")).convert()
            .with(UniRxConverters.toCompletable());
    assertThat(completable).isNotNull();
    completable.test().assertError(e -> {
        assertThat(e).hasMessage("boom").isInstanceOf(IOException.class);
        return true;
    });
}
 
Example #25
Source File: UniToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected Uni createInstanceFailingAsynchronously(RuntimeException e) {
    return Uni.createFrom().item("X")
            .onItem().delayIt().by(Duration.ofMillis(10))
            .map(s -> {
                throw e;
            });
}
 
Example #26
Source File: SingleSkipTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out-3")
public Uni<String> processPayloadAsync(String s) {
    if (s.equalsIgnoreCase("skip")) {
        // Important, you must not return `null`, but a `null` content
        return Uni.createFrom().nullItem();
    }
    return Uni.createFrom().item(s.toUpperCase());
}
 
Example #27
Source File: UniZipTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithSixUnis() {
    Uni<Integer> uni1 = Uni.createFrom().item(1);
    Uni<Integer> uni2 = Uni.createFrom().item(2);
    Uni<Integer> uni3 = Uni.createFrom().item(3);
    Uni<Integer> uni4 = Uni.createFrom().item(4);
    Uni<Integer> uni5 = Uni.createFrom().item(5);
    Uni<Integer> uni6 = Uni.createFrom().item(6);

    UniAssertSubscriber<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer>> subscriber = Uni.combine()
            .all()
            .unis(uni1, uni2, uni3, uni4, uni5, uni6).asTuple()
            .subscribe().withSubscriber(UniAssertSubscriber.create());

    subscriber.assertCompletedSuccessfully();

    assertThat(subscriber.getItem().asList()).containsExactly(1, 2, 3, 4, 5, 6);
}
 
Example #28
Source File: UniSubscribeAsCompletionStageTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatTwoSubscribersWithCache() {
    AtomicInteger count = new AtomicInteger(1);
    Uni<Integer> cached = Uni.createFrom().deferred(() -> Uni.createFrom().item(count.getAndIncrement())).cache();
    CompletionStage<Integer> cs1 = cached.subscribe().asCompletionStage();
    CompletionStage<Integer> cs2 = cached.subscribe().asCompletionStage();
    assertThat(cs1).isNotNull();
    assertThat(cs2).isNotNull();
    assertThat(cs1).isCompletedWithValue(1);
    assertThat(cs1).isCompletedWithValue(1);
}
 
Example #29
Source File: UniCreateFromCompletionStageTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatSubscriberCanCancelAfterEmission() {
    AtomicBoolean called = new AtomicBoolean();
    UniAssertSubscriber<Integer> ts = UniAssertSubscriber.create();
    CompletableFuture<Integer> cs = new CompletableFuture<>();
    Uni<Integer> uni = Uni.createFrom().completionStage(cs)
            .onItem().invoke(i -> called.set(true));

    uni.subscribe().withSubscriber(ts);
    cs.complete(1);
    ts.cancel();
    assertThat(called).isTrue();
    ts.assertItem(1);
}
 
Example #30
Source File: UniCreateFromDeferredSupplierTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithSharedStateProducingNull() {
    UniAssertSubscriber<Integer> ts1 = UniAssertSubscriber.create();
    UniAssertSubscriber<Integer> ts2 = UniAssertSubscriber.create();
    Supplier<AtomicInteger> boom = () -> null;

    Uni<Integer> uni = Uni.createFrom().deferred(boom,
            page -> Uni.createFrom().item(page.getAndIncrement()));

    uni.subscribe().withSubscriber(ts1);
    ts1.assertFailure(NullPointerException.class, "supplier");
    uni.subscribe().withSubscriber(ts2);
    ts2.assertFailure(IllegalStateException.class, "Invalid shared state");
}