io.smallrye.mutiny.subscription.UniEmitter Java Examples

The following examples show how to use io.smallrye.mutiny.subscription.UniEmitter. 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: MpJwtValidator.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() {
        @Override
        public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) {
            try {
                JsonWebToken jwtPrincipal = parser.parse(request.getToken().getToken());
                uniEmitter.complete(QuarkusSecurityIdentity.builder().setPrincipal(jwtPrincipal)
                        .addRoles(jwtPrincipal.getGroups())
                        .addAttribute(SecurityIdentity.USER_ATTRIBUTE, jwtPrincipal).build());

            } catch (ParseException e) {
                log.debug("Authentication failed", e);
                uniEmitter.fail(new AuthenticationFailedException(e));
            }
        }
    });

}
 
Example #2
Source File: KafkaSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private void handleWriteResult(AsyncResult<?> ar, Message<?> message, ProducerRecord<?, ?> record,
        UniEmitter<? super Void> emitter) {
    String actualTopic = record.topic();
    if (ar.succeeded()) {
        log.successfullyToTopic(message, actualTopic);
        message.ack().whenComplete((x, f) -> {
            if (f != null) {
                emitter.fail(f);
            } else {
                emitter.complete(null);
            }
        });
    } else {
        // Fail, there will be retry.
        emitter.fail(ar.cause());
    }
}
 
Example #3
Source File: UniCreateFromEmitterTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testThatOnlyTheFirstSignalIsConsidered() {
    AtomicReference<UniEmitter<? super Integer>> reference = new AtomicReference<>();
    Uni<Integer> uni = Uni.createFrom().emitter(emitter -> {
        reference.set(emitter);
        emitter.complete(1);
        emitter.fail(new Exception());
        emitter.complete(2);
        emitter.complete(null);
    });
    UniAssertSubscriber<Integer> subscriber = UniAssertSubscriber.create();
    uni.subscribe().withSubscriber(subscriber);

    subscriber.assertCompletedSuccessfully().assertItem(1);
    // Other signals are dropped
    assertThat(((DefaultUniEmitter) reference.get()).isTerminated()).isTrue();
}
 
Example #4
Source File: UniCreateFromEmitterTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testThatEmitterIsDisposed() {
    UniAssertSubscriber<Void> subscriber = UniAssertSubscriber.create();
    AtomicReference<UniEmitter<? super Void>> reference = new AtomicReference<>();
    Uni.createFrom().<Void> emitter(emitter -> {
        reference.set(emitter);
        emitter.complete(null);
    }).subscribe().withSubscriber(subscriber);

    subscriber.assertCompletedSuccessfully();
    assertThat(reference.get()).isInstanceOf(DefaultUniEmitter.class)
            .satisfies(e -> ((DefaultUniEmitter<? super Void>) e).isTerminated());
}
 
Example #5
Source File: DefaultUniEmitter.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public UniEmitter<T> onTermination(Runnable callback) {
    Runnable actual = nonNull(callback, "callback");
    if (!disposed.get()) {
        this.onTermination.set(actual);
        // Re-check if the termination didn't happen in the meantime
        if (disposed.get()) {
            terminate();
        }
    }
    return this;
}
 
Example #6
Source File: UniOnItemDelayUntilTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancellationDuringWaitingTimeWithEmissionAfterward() {
    AtomicReference<UniEmitter<?>> reference = new AtomicReference<>();
    UniAssertSubscriber<Integer> subscriber = Uni.createFrom().item(1)
            .onItem().delayIt().until(i -> Uni.createFrom().emitter(reference::set))
            .subscribe().withSubscriber(UniAssertSubscriber.create());
    await().until(() -> reference.get() != null);
    subscriber.assertNoResult();
    subscriber.cancel();
    reference.get().complete(null);
    subscriber.assertNoResult();
}
 
Example #7
Source File: UniOnItemDelayUntilTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEmission() {
    AtomicReference<UniEmitter<?>> reference = new AtomicReference<>();
    UniAssertSubscriber<Integer> subscriber = Uni.createFrom().item(1)
            .onItem().delayIt().until(i -> Uni.createFrom().emitter(reference::set))
            .subscribe().withSubscriber(UniAssertSubscriber.create());
    await().until(() -> reference.get() != null);
    subscriber.assertNoResult();
    reference.get().complete(null);
    subscriber.await().assertItem(1);
}
 
Example #8
Source File: UniOnItemFlatMapWithEmitterTest.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testThatTheMapperCannotBeNull() {
    Uni.createFrom().item(1).onItem().produceUni((BiConsumer<Integer, UniEmitter<? super Integer>>) null);
}
 
Example #9
Source File: UniStreamObserver.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public UniStreamObserver(UniEmitter<? super T> emitter) {
    this.emitter = emitter;
}
 
Example #10
Source File: FormAuthenticationMechanism.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public Uni<SecurityIdentity> runFormAuth(final RoutingContext exchange,
        final IdentityProviderManager securityContext) {
    exchange.request().setExpectMultipart(true);
    return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() {
        @Override
        public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) {
            exchange.request().endHandler(new Handler<Void>() {
                @Override
                public void handle(Void event) {
                    try {
                        MultiMap res = exchange.request().formAttributes();

                        final String jUsername = res.get("j_username");
                        final String jPassword = res.get("j_password");
                        if (jUsername == null || jPassword == null) {
                            log.debugf(
                                    "Could not authenticate as username or password was not present in the posted result for %s",
                                    exchange);
                            uniEmitter.complete(null);
                            return;
                        }
                        securityContext
                                .authenticate(new UsernamePasswordAuthenticationRequest(jUsername,
                                        new PasswordCredential(jPassword.toCharArray())))
                                .subscribe().with(new Consumer<SecurityIdentity>() {
                                    @Override
                                    public void accept(SecurityIdentity identity) {
                                        loginManager.save(identity, exchange, null);
                                        if (redirectAfterLogin || exchange.getCookie(locationCookie) != null) {
                                            handleRedirectBack(exchange);
                                            //we  have authenticated, but we want to just redirect back to the original page
                                            //so we don't actually authenticate the current request
                                            //instead we have just set a cookie so the redirected request will be authenticated
                                        } else {
                                            exchange.response().setStatusCode(200);
                                            exchange.response().end();
                                        }
                                        uniEmitter.complete(null);
                                    }
                                }, new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) {
                                        uniEmitter.fail(throwable);
                                    }
                                });
                    } catch (Throwable t) {
                        uniEmitter.fail(t);
                    }
                }
            });
            exchange.request().resume();
        }
    });
}
 
Example #11
Source File: OidcIdentityProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private Uni<SecurityIdentity> validateTokenWithOidcServer(TokenAuthenticationRequest request,
        TenantConfigContext resolvedContext) {

    return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() {
        @Override
        public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) {
            resolvedContext.auth.decodeToken(request.getToken().getToken(),
                    new Handler<AsyncResult<AccessToken>>() {
                        @Override
                        public void handle(AsyncResult<AccessToken> event) {
                            if (event.failed()) {
                                uniEmitter.fail(new AuthenticationFailedException(event.cause()));
                                return;
                            }
                            // Token has been verified, as a JWT or an opaque token, possibly involving
                            // an introspection request.
                            final TokenCredential tokenCred = request.getToken();
                            JsonObject tokenJson = event.result().accessToken();
                            if (tokenJson == null) {
                                // JSON token representation may be null not only if it is an opaque access token
                                // but also if it is JWT and no JWK with a matching kid is available, asynchronous
                                // JWK refresh has not finished yet, but the fallback introspection request has succeeded.
                                tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken());
                            }
                            if (tokenJson != null) {
                                try {
                                    uniEmitter.complete(
                                            validateAndCreateIdentity(tokenCred, resolvedContext.oidcConfig, tokenJson));
                                } catch (Throwable ex) {
                                    uniEmitter.fail(ex);
                                }
                            } else if (tokenCred instanceof IdTokenCredential
                                    || tokenCred instanceof AccessTokenCredential
                                            && !((AccessTokenCredential) tokenCred).isOpaque()) {
                                uniEmitter
                                        .fail(new AuthenticationFailedException("JWT token can not be converted to JSON"));
                            } else {
                                // Opaque access token
                                QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
                                builder.addCredential(tokenCred);
                                if (event.result().principal().containsKey("username")) {
                                    final String userName = event.result().principal().getString("username");
                                    builder.setPrincipal(new Principal() {
                                        @Override
                                        public String getName() {
                                            return userName;
                                        }
                                    });
                                }
                                uniEmitter.complete(builder.build());
                            }
                        }
                    });
        }
    });
}
 
Example #12
Source File: UniOnItemOrFailureFlatMapTest.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testThatMapperIsNotNull() {
    one.onItemOrFailure().produceUni(
            (Functions.TriConsumer<? super Integer, Throwable, UniEmitter<? super Object>>) null);
}
 
Example #13
Source File: MultiRepetitionTest.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testThatFunctionCannotBeNullWithEmitter() {
    Multi.createBy().repeating().uni((Consumer<UniEmitter<? super Object>>) null);
}
 
Example #14
Source File: MultiRepetitionTest.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testThatFunctionCannotBeNullWithEmitterWithSharedState() {
    Multi.createBy().repeating().uni(() -> "hello",
            (BiConsumer<String, UniEmitter<? super String>>) null);
}
 
Example #15
Source File: UniCreateWithEmitter.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
public UniCreateWithEmitter(Consumer<UniEmitter<? super T>> consumer) {
    this.consumer = nonNull(consumer, "consumer");
}
 
Example #16
Source File: UniCreate.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a {@link Uni} deferring the logic to the given consumer. The consumer can be used with callback-based
 * APIs to fire at most one item (potentially {@code null}), or a failure event.
 * <p>
 * Using this method, you can produce a {@link Uni} based on listener or callbacks APIs. You register the listener
 * in the consumer and emits the item / failure events when the listener is invoked. Don't forget to unregister
 * the listener on cancellation.
 * <p>
 * Note that the emitter only forwards the first event, subsequent events are dropped.
 * <p>
 * If the consumer throws an exception, a failure event with the exception is fired if the first event was already
 * fired.
 * This variant of {@link #emitter(Consumer)} allows passing a state supplier. This supplier allows
 * sharing some <em>state</em> between the subscribers. It is particularly useful when using {@link Uni#repeat()}
 * as you can pass a shared state (for example a page counter, like an AtomicInteger, if you implement pagination).
 * The state supplier is called once, during the first subscription. Note that the mapper is called for every
 * subscription.
 * <p>
 * The state supplier should produce a container wrapping the shared state. This shared state must be thread-safe.
 *
 * @param stateSupplier the state supplier, must not return {@code null}, must not be {@code null}
 * @param consumer callback receiving the {@link UniEmitter} and events downstream. The callback is
 *        called for each subscriber (at subscription time). Must not be {@code null}
 * @param <T> the type of item
 * @param <S> the type of the state
 * @return the produced {@link Uni}
 */
public <T, S> Uni<T> emitter(Supplier<S> stateSupplier, BiConsumer<S, UniEmitter<? super T>> consumer) {
    BiConsumer<S, UniEmitter<? super T>> actual = ParameterValidation.nonNull(consumer, "consumer");
    ParameterValidation.nonNull(stateSupplier, "stateSupplier");
    // Flag checking that the state supplier is only called once.
    AtomicBoolean once = new AtomicBoolean();
    // The shared state container.
    AtomicReference<S> state = new AtomicReference<>();

    return Uni.createFrom().deferred(() -> {
        try {
            invokeOnce(once, state, stateSupplier);
        } catch (Throwable e) {
            return Uni.createFrom().failure(e);
        }
        S sharedState = state.get();
        if (sharedState == null) {
            // The state supplier failed or produced null.
            return Uni.createFrom().failure(new IllegalStateException("Invalid shared state"));
        }
        return Uni.createFrom().emitter(e -> actual.accept(sharedState, e));
    });
}
 
Example #17
Source File: UniOnNotNull.java    From smallrye-mutiny with Apache License 2.0 3 votes vote down vote up
/**
 * Transforms the received item asynchronously, forwarding the events emitted an {@link UniEmitter} consumes by
 * the given consumer.
 * <p>
 * The consumer is called with the item event of the current {@link Uni} and an emitter uses to fire events.
 * These events are these propagated by the produced {@link Uni}.
 * <p>
 * If the incoming item is {@code null}, the {@code consumer} is not called and a {@code null} item is propagated
 * downstream.
 *
 * @param consumer the function called with the item of the this {@link Uni} and an {@link UniEmitter}.
 *        It must not be {@code null}.
 * @param <R> the type of item emitted by the emitter
 * @return a new {@link Uni} that would fire events from the emitter consumed by the mapper function, possibly
 *         in an asynchronous manner.
 */
public <R> Uni<R> produceUni(BiConsumer<? super T, UniEmitter<? super R>> consumer) {
    return upstream.onItem().produceUni((item, emitter) -> {
        if (item != null) {
            consumer.accept(item, emitter);
        } else {
            emitter.complete(null);
        }
    });
}
 
Example #18
Source File: UniOnItemOrFailure.java    From smallrye-mutiny with Apache License 2.0 3 votes vote down vote up
/**
 * Transforms the received item or failure asynchronously, forwarding the events emitted by the {@link UniEmitter}
 * provided to the given consumer.
 * <p>
 * The consumer is called with the item event or failure event emitted by the current {@link Uni} and an emitter
 * used to fire events downstream.
 * <p>
 * As the item received from upstream can be {@code null}, detecting a failure must be done by checking whether the
 * failure passed to the consumer is {@code null}.
 *
 * @param consumer the function called with the item of the this {@link Uni} and an {@link UniEmitter}.
 *        It must not be {@code null}.
 * @param <R> the type of item emitted by the emitter
 * @return a new {@link Uni} that would fire events from the emitter consumed by the mapper function, possibly
 *         in an asynchronous manner.
 */
public <R> Uni<R> produceUni(Functions.TriConsumer<? super T, Throwable, UniEmitter<? super R>> consumer) {
    nonNull(consumer, "consumer");
    return this.produceUni((item, failure) -> Uni.createFrom().emitter(emitter -> {
        try {
            consumer.accept(item, failure, emitter);
        } catch (Throwable e) {
            if (failure != null) {
                emitter.fail(new CompositeException(failure, e));
            } else {
                emitter.fail(e);
            }
        }
    }));
}
 
Example #19
Source File: MultiRepetition.java    From smallrye-mutiny with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link io.smallrye.mutiny.Multi} by repeating the items fired by the produced {@link BiConsumer}.
 * The bi-consumer receives the shared state and an {@link UniEmitter} that allow firing the item (or failure).
 *
 * @param stateSupplier the state supplier, must not be {@code null}, must not return {@code null}.
 * @param consumer the consumer called for every requested repetition
 * @param <S> the type of the shared state
 * @param <T> the type of emitted item
 * @return the object to configure the repetition
 */
public <S, T> UniRepeat<T> uni(Supplier<S> stateSupplier,
        BiConsumer<S, UniEmitter<? super T>> consumer) {
    ParameterValidation.nonNull(consumer, "consumer");
    return uni(stateSupplier, s -> Uni.createFrom().emitter(e -> consumer.accept(s, e)));
}
 
Example #20
Source File: UniOnItem.java    From smallrye-mutiny with Apache License 2.0 2 votes vote down vote up
/**
 * Transforms the received item asynchronously, forwarding the events emitted by an {@link UniEmitter} provided to
 * the given consumer.
 * <p>
 * The consumer is called with the item event of the current {@link Uni} and an emitter used to fire events.
 * These events are these propagated by the produced {@link Uni}.
 *
 * @param consumer the function called with the item of the this {@link Uni} and an {@link UniEmitter}.
 *        It must not be {@code null}.
 * @param <R> the type of item emitted by the emitter
 * @return a new {@link Uni} that would fire events from the emitter consumed by the mapper function, possibly
 *         in an asynchronous manner.
 */
public <R> Uni<R> produceUni(BiConsumer<? super T, UniEmitter<? super R>> consumer) {
    nonNull(consumer, "consumer");
    return this.produceUni(x -> Uni.createFrom().emitter(emitter -> consumer.accept(x, emitter)));
}
 
Example #21
Source File: UniCreate.java    From smallrye-mutiny with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link Uni} deferring the logic to the given consumer. The consumer can be used with callback-based
 * APIs to fire at most one item (potentially {@code null}), or a failure event.
 * <p>
 * Using this method, you can produce a {@link Uni} based on listener or callbacks APIs. You register the listener
 * in the consumer and emits the item / failure events when the listener is invoked. Don't forget to unregister
 * the listener on cancellation.
 * <p>
 * Note that the emitter only forwards the first event, subsequent events are dropped.
 * <p>
 * If the consumer throws an exception, a failure event with the exception is fired if the first event was already
 * fired.
 *
 * @param consumer callback receiving the {@link UniEmitter} and events downstream. The callback is
 *        called for each subscriber (at subscription time). Must not be {@code null}
 * @param <T> the type of item
 * @return the produced {@link Uni}
 */
public <T> Uni<T> emitter(Consumer<UniEmitter<? super T>> consumer) {
    Consumer<UniEmitter<? super T>> actual = ParameterValidation.nonNull(consumer, "consumer");
    return Infrastructure.onUniCreation(new UniCreateWithEmitter<>(actual));
}
 
Example #22
Source File: MultiRepetition.java    From smallrye-mutiny with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link io.smallrye.mutiny.Multi} by repeating the items fired by the produced {@link Consumer}
 * receiving an {@link UniEmitter} to fire the item or failure.
 *
 * @param consumer the consumer called for every requested repetition
 * @param <T> the type of emitted item
 * @return the object to configure the repetition
 */
public <T> UniRepeat<T> uni(Consumer<UniEmitter<? super T>> consumer) {
    ParameterValidation.nonNull(consumer, "consumer");
    return uni(() -> Uni.createFrom().emitter(consumer));
}