Example usage for io.vertx.core Future future

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

Introduction

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

Prototype

future

Source Link

Usage

From source file:org.eclipse.hono.application.HonoApplication.java

License:Open Source License

private Future<String> deployAuthorizationService() {
    LOG.info("Starting authorization service {}", authorizationService);
    Future<String> result = Future.future();
    vertx.deployVerticle(authorizationService, result.completer());
    return result;
}

From source file:org.eclipse.hono.application.HonoApplication.java

License:Open Source License

@SuppressWarnings("rawtypes")
private void deployServerInstance(final HonoServer instance, final List<Future> deployResults) {
    Future<String> result = Future.future();
    vertx.deployVerticle(instance, result.completer());
    deployResults.add(result);/* www.j  a v a  2 s .co m*/
}

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

License:Open Source License

/**
 * Closes this client's sender and receiver links to Hono.
 * /*from w ww  . j a  v  a2  s  .c  o 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  ww  w .  j  av  a2 s  .  c om
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

/**
 * Creates a sender link.//w ww .  j  av  a  2 s.  c o m
 * 
 * @param ctx The vertx context to use for establishing the link.
 * @param con The connection to create the link for.
 * @param targetAddress The target address of the link.
 * @param qos The quality of service to use for the link.
 * @param closeHook The handler to invoke when the link is closed by the peer.
 * @return A future for the created link.
 */
protected static final Future<ProtonSender> createSender(final Context ctx, final ProtonConnection con,
        final String targetAddress, final ProtonQoS qos, final Handler<String> closeHook) {

    final Future<ProtonSender> result = Future.future();

    ctx.runOnContext(create -> {
        final ProtonSender sender = con.createSender(targetAddress);
        sender.setQoS(qos);
        sender.openHandler(senderOpen -> {
            if (senderOpen.succeeded()) {
                LOG.debug("sender open [{}]", sender.getRemoteTarget());
                result.complete(senderOpen.result());
            } else {
                LOG.debug("opening sender [{}] failed: {}", targetAddress, senderOpen.cause().getMessage());
                result.fail(senderOpen.cause());
            }
        });
        sender.closeHandler(senderClosed -> {
            if (senderClosed.succeeded()) {
                LOG.debug("sender [{}] closed", targetAddress);
            } else {
                LOG.debug("sender [{}] closed: {}", targetAddress, senderClosed.cause().getMessage());
            }
            sender.close();
            if (closeHook != null) {
                closeHook.handle(targetAddress);
            }
        });
        sender.open();
    });

    return result;
}

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.
 * /* w w  w  .j av a  2 s  .  c  o  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.AuthenticationServerClient.java

License:Open Source License

private static Future<ProtonReceiver> openReceiver(final ProtonConnection openConnection,
        final ProtonMessageHandler messageHandler) {
    final Future<ProtonReceiver> result = Future.future();
    openConnection.createReceiver(AuthenticationConstants.ENDPOINT_NAME_AUTHENTICATION)
            .openHandler(result.completer()).handler(messageHandler).open();
    return result;
}

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

License:Open Source License

/**
 * {@inheritDoc}/*from   w w w  . ja v  a 2s  .c o  m*/
 */
@Override
public Future<Buffer> sendCommand(final String command, final Buffer data) {

    Objects.requireNonNull(command);
    Objects.requireNonNull(data);

    final Future<BufferResult> responseTracker = Future.future();
    createAndSendRequest(command, null, data, null, responseTracker.completer(), null);

    return responseTracker.map(response -> {
        if (response.isOk()) {
            return response.getPayload();
        } else {
            throw StatusCodeMapper.from(response);
        }
    });
}

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

License:Open Source License

private HonoClient createTelemetrySender(final String tenantId, final String deviceId,
        final Handler<AsyncResult<MessageSender>> creationHandler) {

    Future<MessageSender> senderTracker = Future.future();
    senderTracker.setHandler(creationHandler);
    checkConnection().compose(/*from  w w w.ja v  a2 s  . c  om*/
            connected -> TelemetrySenderImpl.create(context, connection, tenantId, deviceId, onSenderClosed -> {
                activeSenders.remove(TelemetrySenderImpl.getTargetAddress(tenantId, deviceId));
            }, senderTracker.completer()), senderTracker);
    return this;
}

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

License:Open Source License

@Override
public HonoClient createTelemetryConsumer(final String tenantId, final int prefetch,
        final Consumer<Message> telemetryConsumer,
        final Handler<AsyncResult<MessageConsumer>> creationHandler) {

    // register a handler to be notified if the underlying connection to the server fails
    // so that we can fail the result handler passed in
    final Handler<Void> connectionFailureHandler = connectionLost -> {
        creationHandler.handle(Future.failedFuture("connection to server lost"));
    };//  ww w.j av a  2 s  .c  om
    creationRequests.add(connectionFailureHandler);

    Future<MessageConsumer> consumerTracker = Future.future();
    consumerTracker.setHandler(attempt -> {
        creationRequests.remove(connectionFailureHandler);
        creationHandler.handle(attempt);
    });
    checkConnection().compose(connected -> TelemetryConsumerImpl.create(context, connection, tenantId,
            connectionFactory.getPathSeparator(), prefetch, telemetryConsumer, consumerTracker.completer()),
            consumerTracker);
    return this;
}