Example usage for io.vertx.core Future failedFuture

List of usage examples for io.vertx.core Future failedFuture

Introduction

In this page you can find the example usage for io.vertx.core Future failedFuture.

Prototype

static <T> Future<T> failedFuture(String failureMessage) 

Source Link

Document

Create a failed future with the specified failure message.

Usage

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<MessageSender> getSenderTracker(final MqttPublishMessage message,
        final ResourceIdentifier resource, final String tenantId) {

    if (resource.getEndpoint().equals(TELEMETRY_ENDPOINT)) {
        if (!MqttQoS.AT_MOST_ONCE.equals(message.qosLevel())) {
            // client tries to send telemetry message using QoS 1 or 2
            return Future.failedFuture("Only QoS 0 supported for telemetry messages");
        } else {/*from   www.j  a  v a2  s  .  com*/
            return getTelemetrySender(tenantId);
        }
    } else if (resource.getEndpoint().equals(EVENT_ENDPOINT)) {
        if (!MqttQoS.AT_LEAST_ONCE.equals(message.qosLevel())) {
            // client tries to send event message using QoS 0 or 2
            return Future.failedFuture("Only QoS 1 supported for event messages");
        } else {
            return getEventSender(tenantId);
        }
    } else {
        // MQTT client is trying to publish on a not supported endpoint
        LOG.debug("no such endpoint [{}]", resource.getEndpoint());
        return Future.failedFuture("no such endpoint");
    }
}

From source file:org.eclipse.hono.authentication.impl.AbstractPlainAuthenticationService.java

License:Open Source License

@Override
public final void validateResponse(final String mechanism, final byte[] response,
        final Handler<AsyncResult<String>> resultHandler) {

    if (!isSupported(mechanism)) {
        throw new IllegalArgumentException("unsupported SASL mechanism");
    } else {// w  w  w  .jav  a  2 s  . c  om
        try {
            String[] fields = readFields(response);
            String authzid = fields[0];
            String authcid = fields[1];
            String pwd = fields[2];
            log.debug("client provided [authzid: {}, authcid: {}, pwd: *****] in PLAIN response", authzid,
                    authcid);
            verify(authzid, authcid, pwd, resultHandler);

        } catch (CredentialException e) {
            // response did not contain expected values
            resultHandler.handle(Future.failedFuture(e));
        }
    }
}

From source file:org.eclipse.hono.client.impl.AbstractHonoClient.java

License:Open Source License

/**
 * Closes this client's sender and receiver links to Hono.
 * //ww w. j  a v a 2 s.co m
 * @param closeHandler the handler to be notified about the outcome.
 * @throws NullPointerException if the given handler is {@code null}.
 */
protected void closeLinks(final Handler<AsyncResult<Void>> closeHandler) {

    Objects.requireNonNull(closeHandler);

    final Future<ProtonSender> senderCloseHandler = Future.future();
    final Future<ProtonReceiver> receiverCloseHandler = Future.future();
    receiverCloseHandler.setHandler(closeAttempt -> {
        if (closeAttempt.succeeded()) {
            closeHandler.handle(Future.succeededFuture());
        } else {
            closeHandler.handle(Future.failedFuture(closeAttempt.cause()));
        }
    });

    senderCloseHandler.compose(closedSender -> {
        if (receiver != null && receiver.isOpen()) {
            receiver.closeHandler(closeAttempt -> {
                LOG.debug("closed message consumer for [{}]", receiver.getSource().getAddress());
                receiverCloseHandler.complete(receiver);
            }).close();
        } else {
            receiverCloseHandler.complete();
        }
    }, receiverCloseHandler);

    context.runOnContext(close -> {

        if (sender != null && sender.isOpen()) {
            sender.closeHandler(closeAttempt -> {
                LOG.debug("closed message sender for [{}]", sender.getTarget().getAddress());
                senderCloseHandler.complete(sender);
            }).close();
        } else {
            senderCloseHandler.complete();
        }
    });
}

From source file:org.eclipse.hono.client.impl.AbstractRequestResponseClient.java

License:Open Source License

/**
 * Creates a client for a vert.x context.
 *
 * @param context The context to run all interactions with the server on.
 * @param con The connection to use for interacting with the service.
 * @param tenantId The tenant that the client will be scoped to.
 * @param creationHandler The handler to invoke with the created client.
 *//*from www  .  j a  va2s .  co m*/
protected AbstractRequestResponseClient(final Context context, final ProtonConnection con,
        final String tenantId, final Handler<AsyncResult<C>> creationHandler) {

    super(context);
    requestResponseAddressTemplate = String.format("%s/%%s", getName());
    requestResponseReplyToAddressTemplate = String.format("%s/%%s/%%s", getName());
    this.replyToAddress = String.format(requestResponseReplyToAddressTemplate, Objects.requireNonNull(tenantId),
            UUID.randomUUID());

    final Future<ProtonSender> senderTracker = Future.future();
    senderTracker.setHandler(r -> {
        if (r.succeeded()) {
            LOG.debug("request response client created");
            this.sender = r.result();
            creationHandler.handle(Future.succeededFuture((C) this));
        } else {
            creationHandler.handle(Future.failedFuture(r.cause()));
        }
    });

    final Future<ProtonReceiver> receiverTracker = Future.future();
    context.runOnContext(create -> {
        final ProtonReceiver receiver = con.createReceiver(replyToAddress);
        receiver.setAutoAccept(true).setPrefetch(DEFAULT_SENDER_CREDITS).handler((delivery, message) -> {
            final Handler<AsyncResult<R>> handler = replyMap.remove(message.getCorrelationId());
            if (handler != null) {
                R result = getRequestResponseResult(message);
                LOG.debug("received response [correlation ID: {}, status: {}]", message.getCorrelationId(),
                        result.getStatus());
                handler.handle(Future.succeededFuture(result));
            } else {
                LOG.debug("discarding unexpected response [correlation ID: {}]", message.getCorrelationId());
            }
        }).openHandler(receiverTracker.completer()).open();

        receiverTracker.compose(openReceiver -> {
            this.receiver = openReceiver;
            ProtonSender sender = con.createSender(String.format(requestResponseAddressTemplate, tenantId));
            sender.setQoS(ProtonQoS.AT_LEAST_ONCE).openHandler(senderTracker.completer()).open();
        }, senderTracker);
    });
}

From source file:org.eclipse.hono.client.impl.AbstractSender.java

License:Open Source License

@Override
public final void setErrorHandler(final Handler<AsyncResult<Void>> errorHandler) {

    sender.closeHandler(s -> {//from   w  w w.ja v  a2 s  .  c o  m
        if (s.failed()) {
            LOG.debug("server closed link with error condition: {}", s.cause().getMessage());
            sender.close();
            if (closeHook != null) {
                closeHook.handle(targetAddress);
            }
            errorHandler.handle(Future.failedFuture(s.cause()));
        } else {
            LOG.debug("server closed link");
            sender.close();
            if (closeHook != null) {
                closeHook.handle(targetAddress);
            }
        }
    });
}

From source file:org.eclipse.hono.client.impl.AuthenticationServerClient.java

License:Open Source License

/**
 * Verifies a Subject DN with a remote authentication server using SASL EXTERNAL.
 * <p>//from   w w w .  j a  v a  2 s.  c o m
 * This method currently always fails the handler because there is no way (yet) in vertx-proton
 * to perform a SASL EXTERNAL exchange including an authorization id.
 * 
 * @param authzid The identity to act as.
 * @param subjectDn The Subject DN.
 * @param authenticationResultHandler The handler to invoke with the authentication result. On successful authentication,
 *                                    the result contains a JWT with the the authenticated user's claims.
 */
public void verifyExternal(final String authzid, final String subjectDn,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {
    // unsupported mechanism (until we get better control over client SASL params in vertx-proton)
    authenticationResultHandler.handle(Future.failedFuture("unsupported mechanism"));
}

From source file:org.eclipse.hono.client.impl.AuthenticationServerClient.java

License:Open Source License

/**
 * Verifies username/password credentials with a remote authentication server using SASL PLAIN.
 * //from  www  .ja v a  2s .  co  m
 * @param authzid The identity to act as.
 * @param authcid The username.
 * @param password The password.
 * @param authenticationResultHandler The handler to invoke with the authentication result. On successful authentication,
 *                                    the result contains a JWT with the authenticated user's claims.
 */
public void verifyPlain(final String authzid, final String authcid, final String password,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    final ProtonClientOptions options = new ProtonClientOptions();
    options.setReconnectAttempts(3).setReconnectInterval(50);
    options.addEnabledSaslMechanism(AuthenticationConstants.MECHANISM_PLAIN);
    factory.connect(options, authcid, password, null, null, conAttempt -> {
        if (conAttempt.failed()) {
            authenticationResultHandler.handle(Future.failedFuture("cannot connect to Authentication service"));
        } else {
            final ProtonConnection openCon = conAttempt.result();

            final Future<HonoUser> userTracker = Future.future();
            userTracker.setHandler(s -> {
                if (s.succeeded()) {
                    authenticationResultHandler.handle(Future.succeededFuture(s.result()));
                } else {
                    authenticationResultHandler.handle(Future.failedFuture(s.cause()));
                }
                final ProtonConnection con = conAttempt.result();
                if (con != null) {
                    LOG.debug("closing connection to Authentication service");
                    con.close();
                }
            });

            vertx.setTimer(5000, tid -> {
                if (!userTracker.isComplete()) {
                    userTracker.fail("time out reached while waiting for token from Authentication service");
                }
            });

            getToken(openCon, userTracker);
        }
    });
}

From source file:org.eclipse.hono.client.impl.CommandClientImpl.java

License:Open Source License

/**
 * Creates a new command client for a tenant and device.
 *
 * @param tenantId The tenant to create the client for.
 * @param deviceId The device to create the client for.
 * @param context The vert.x context to run all interactions with the server on.
 * @param clientConfig The configuration properties to use.
 * @param con The AMQP connection to the server.
 * @param senderCloseHook A handler to invoke if the peer closes the sender link unexpectedly.
 * @param receiverCloseHook A handler to invoke if the peer closes the receiver link unexpectedly.
 * @param creationHandler The handler to invoke with the outcome of the creation attempt.
 * @throws NullPointerException if any of the parameters is {@code null}.
 *//*from   ww  w  .ja va2 s.c o m*/
public static final void create(final String tenantId, final String deviceId, final Context context,
        final ClientConfigProperties clientConfig, final ProtonConnection con,
        final Handler<String> senderCloseHook, final Handler<String> receiverCloseHook,
        final Handler<AsyncResult<CommandClient>> creationHandler) {

    final CommandClientImpl client = new CommandClientImpl(context, clientConfig, tenantId, deviceId);
    client.createLinks(con, senderCloseHook, receiverCloseHook).setHandler(s -> {
        if (s.succeeded()) {
            LOG.debug("successfully created command client for [{}]", tenantId);
            creationHandler.handle(Future.succeededFuture(client));
        } else {
            LOG.debug("failed to create command client for [{}]", tenantId, s.cause());
            creationHandler.handle(Future.failedFuture(s.cause()));
        }
    });
}

From source file:org.eclipse.hono.client.impl.EventConsumerImpl.java

License:Open Source License

/**
 * Creates a new event consumer for a tenant.
 * /*from w w w.  j  ava 2 s .c  o m*/
 * @param context The vert.x context to run all interactions with the server on.
 * @param con The AMQP connection to the server.
 * @param tenantId The tenant to consumer events for.
 * @param pathSeparator The address path separator character used by the server.
 * @param prefetch the number of message credits the consumer grants and replenishes automatically as messages are
 *                 delivered. To manage credit manually, you can instead set prefetch to 0.
 * @param eventConsumer The consumer to invoke with each event received.
 * @param creationHandler The handler to invoke with the outcome of the creation attempt.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public static void create(final Context context, final ProtonConnection con, final String tenantId,
        final String pathSeparator, final int prefetch, final BiConsumer<ProtonDelivery, Message> eventConsumer,
        final Handler<AsyncResult<MessageConsumer>> creationHandler) {

    Objects.requireNonNull(context);
    Objects.requireNonNull(con);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(pathSeparator);
    Objects.requireNonNull(eventConsumer);
    Objects.requireNonNull(creationHandler);
    createConsumer(context, con, tenantId, pathSeparator, EVENT_ADDRESS_TEMPLATE, ProtonQoS.AT_LEAST_ONCE,
            prefetch, eventConsumer).setHandler(created -> {
                if (created.succeeded()) {
                    creationHandler
                            .handle(Future.succeededFuture(new EventConsumerImpl(context, created.result())));
                } else {
                    creationHandler.handle(Future.failedFuture(created.cause()));
                }
            });
}

From source file:org.eclipse.hono.client.impl.EventSenderImpl.java

License:Open Source License

/**
 * Creates a new sender for publishing events to a Hono server.
 * //from  w  w  w  .ja  va  2s  .com
 * @param context The vertx context to run all interactions with the server on.
 * @param con The connection to the Hono server.
 * @param tenantId The tenant that the events will be published for.
 * @param deviceId The device that the events will be published for or {@code null}
 *                 if the events are going to be be produced by arbitrary devices of the
 *                 tenant.
 * @param closeHook The handler to invoke when the Hono server closes the sender. The sender's
 *                  target address is provided as an argument to the handler.
 * @param creationHandler The handler to invoke with the result of the creation attempt.
 * @throws NullPointerException if any of context, connection, tenant or handler is {@code null}.
 */
public static void create(final Context context, final ProtonConnection con, final String tenantId,
        final String deviceId, final Handler<String> closeHook,
        final Handler<AsyncResult<MessageSender>> creationHandler) {

    Objects.requireNonNull(context);
    Objects.requireNonNull(con);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(creationHandler);

    final String targetAddress = getTargetAddress(tenantId, deviceId);
    createSender(context, con, targetAddress, ProtonQoS.AT_LEAST_ONCE, closeHook).setHandler(created -> {
        if (created.succeeded()) {
            creationHandler.handle(Future.succeededFuture(
                    new EventSenderImpl(created.result(), tenantId, targetAddress, context, closeHook)));
        } else {
            creationHandler.handle(Future.failedFuture(created.cause()));
        }
    });
}