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.service.AbstractProtocolAdapterBase.java

License:Open Source License

/**
 * Gets a registration status assertion for a device.
 * /*from  w ww  .j  a  va 2s.c o m*/
 * @param tenantId The tenant that the device belongs to.
 * @param logicalDeviceId The device to get the assertion for.
 * @return The assertion.
 */
protected final Future<String> getRegistrationAssertion(final String tenantId, final String logicalDeviceId) {
    Future<String> result = Future.future();
    getRegistrationClient(tenantId).compose(client -> {
        Future<RegistrationResult> tokenTracker = Future.future();
        client.assertRegistration(logicalDeviceId, tokenTracker.completer());
        return tokenTracker;
    }).compose(regResult -> {
        if (regResult.getStatus() == HttpURLConnection.HTTP_OK) {
            result.complete(regResult.getPayload().getString(RegistrationConstants.FIELD_ASSERTION));
        } else {
            result.fail("cannot assert device registration status");
        }
    }, result);
    return result;
}

From source file:org.eclipse.hono.service.AbstractProtocolAdapterBase.java

License:Open Source License

private Future<CredentialsObject> getCredentialsForDevice(final String tenantId, final String type,
        final String authId) {

    Future<CredentialsObject> result = Future.future();
    getCredentialsClient(tenantId).compose(client -> {
        Future<CredentialsResult<CredentialsObject>> credResultFuture = Future.future();
        client.get(type, authId, credResultFuture.completer());
        return credResultFuture;
    }).compose(credResult -> {//from   w  ww . j  av  a 2 s  .  co  m
        if (credResult.getStatus() == HttpURLConnection.HTTP_OK) {
            CredentialsObject payload = credResult.getPayload();
            result.complete(payload);
        } else if (credResult.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
            result.fail(String.format("cannot retrieve credentials (not found for type <%s>, authId <%s>)",
                    type, authId));
        } else {
            result.fail("cannot retrieve credentials");
        }
    }, result);

    return result;
}

From source file:org.eclipse.hono.service.AbstractProtocolAdapterBase.java

License:Open Source License

/**
 * Validates an authentication object against credentials secrets available by the get operation of the
 *  <a href="https://www.eclipse.org/hono/api/Credentials-API/">Credentials API</a>.
 * <p>The credentials are first retrieved from the credentials service, and then all matching validators are
 * invoked until one is successful or all failed. The authentication object is validated iff at least
 * one validator was successful.//from ww w  .  ja v  a2  s .  c om
 *
 * @param tenantId The tenantId to which the device belongs.
 * @param type The type of credentials that are to be used for validation.
 * @param authId The authId of the credentials that are to be used for validation.
 * @param authenticationObject The authentication object to be validated, e.g. a password, a preshared-key, etc.
        
 * @return Future The future object carrying the logicalDeviceId that was resolved by the credentials get operation, if successful.
 */
protected final Future<String> approveCredentialsAndResolveLogicalDeviceId(final String tenantId,
        final String type, final String authId, final Object authenticationObject) {
    return getCredentialsForDevice(tenantId, type, authId).compose(payload -> {
        Future<String> resultDeviceId = Future.future();
        SecretsValidator<Object> validator = CredentialsUtils.findAppropriateValidators(type);
        try {
            if (validator != null && validator.validate(payload, authenticationObject)) {
                resultDeviceId.complete(payload.getDeviceId());
            } else {
                resultDeviceId.fail("credentials invalid - not validated");
            }
        } catch (IllegalArgumentException e) {
            resultDeviceId.fail(String.format("credentials invalid : %s", e.getMessage()));
        }
        return resultDeviceId;
    });
}

From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java

License:Open Source License

private Future<Void> startEndpoints() {

    @SuppressWarnings("rawtypes")
    List<Future> endpointFutures = new ArrayList<>(endpoints.size());
    for (AmqpEndpoint ep : endpoints.values()) {
        LOG.info("starting endpoint [name: {}, class: {}]", ep.getName(), ep.getClass().getName());
        Future<Void> endpointFuture = Future.future();
        endpointFutures.add(endpointFuture);
        ep.start(endpointFuture);//from w  w w .j av a 2 s .c  om
    }
    final Future<Void> startFuture = Future.future();
    CompositeFuture.all(endpointFutures).setHandler(startup -> {
        if (startup.succeeded()) {
            startFuture.complete();
        } else {
            startFuture.fail(startup.cause());
        }
    });
    return startFuture;
}

From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java

License:Open Source License

private Future<Void> startInsecureServer() {

    if (isInsecurePortEnabled()) {
        int insecurePort = determineInsecurePort();
        final Future<Void> result = Future.future();
        final ProtonServerOptions options = createInsecureServerOptions();
        insecureServer = createProtonServer(options).connectHandler(this::onRemoteConnectionOpenInsecurePort)
                .listen(insecurePort, getConfig().getInsecurePortBindAddress(), bindAttempt -> {
                    if (bindAttempt.succeeded()) {
                        if (getInsecurePort() == getInsecurePortDefaultValue()) {
                            LOG.info("server listens on standard insecure port [{}:{}]",
                                    getInsecurePortBindAddress(), getInsecurePort());
                        } else {
                            LOG.warn("server listens on non-standard insecure port [{}:{}], default is {}",
                                    getInsecurePortBindAddress(), getInsecurePort(),
                                    getInsecurePortDefaultValue());
                        }//  w ww. j a  v  a  2  s.c o  m
                        result.complete();
                    } else {
                        LOG.error("cannot bind to insecure port", bindAttempt.cause());
                        result.fail(bindAttempt.cause());
                    }
                });
        return result;
    } else {
        LOG.info("insecure port is not enabled");
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java

License:Open Source License

private Future<Void> startSecureServer() {

    if (isSecurePortEnabled()) {
        int securePort = determineSecurePort();
        final Future<Void> result = Future.future();
        final ProtonServerOptions options = createServerOptions();
        server = createProtonServer(options).connectHandler(this::onRemoteConnectionOpen).listen(securePort,
                getConfig().getBindAddress(), bindAttempt -> {
                    if (bindAttempt.succeeded()) {
                        if (getPort() == getPortDefaultValue()) {
                            LOG.info("server listens on standard secure port [{}:{}]", getBindAddress(),
                                    getPort());
                        } else {
                            LOG.warn("server listens on non-standard secure port [{}:{}], default is {}",
                                    getBindAddress(), getPort(), getPortDefaultValue());
                        }/*ww w  .  ja  v  a2s . c  o  m*/
                        result.complete();
                    } else {
                        LOG.error("cannot bind to secure port", bindAttempt.cause());
                        result.fail(bindAttempt.cause());
                    }
                });
        return result;
    } else {
        LOG.info("secure port is not enabled");
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java

License:Open Source License

@Override
public final Future<Void> stopInternal() {

    Future<Void> shutdownHandler = Future.future();
    Future<Void> tracker = Future.future();
    if (server != null) {
        server.close(tracker.completer());
    } else {/*w  w  w . j a  va2s. com*/
        LOG.info("service has been already shut down");
        tracker.complete();
    }
    tracker.compose(t -> {
        if (insecureServer != null) {
            insecureServer.close(shutdownHandler.completer());
        } else {
            shutdownHandler.complete();
        }
    }, shutdownHandler);
    return shutdownHandler;
}

From source file:org.eclipse.hono.service.amqp.RequestResponseEndpoint.java

License:Open Source License

/**
 * Handles a request message received from a client.
 * <p>/*from w ww . j a  v  a  2  s .  c  o m*/
 * The message gets rejected if
 * <ul>
 * <li>the message does not pass {@linkplain #passesFormalVerification(ResourceIdentifier, Message) formal verification}
 * or</li>
 * <li>the client is not {@linkplain #isAuthorized(HonoUser, ResourceIdentifier, String) authorized to execute the operation}
 * indicated by the message's <em>subject</em> or</li>
 * <li>its payload cannot be parsed</li>
 * </ul>
 * 
 * @param con The connection with the client.
 * @param receiver The link over which the message has been received.
 * @param targetAddress The address the message is sent to.
 * @param delivery The message's delivery status.
 * @param message The message.
 */
protected final void handleMessage(final ProtonConnection con, final ProtonReceiver receiver,
        final ResourceIdentifier targetAddress, ProtonDelivery delivery, Message message) {

    Future<Void> requestTracker = Future.future();
    requestTracker.setHandler(s -> {
        if (s.succeeded()) {
            ProtonHelper.accepted(delivery, true);
        } else if (s.cause() instanceof AmqpErrorException) {
            AmqpErrorException cause = (AmqpErrorException) s.cause();
            MessageHelper.rejected(delivery, cause.asErrorCondition());
        } else {
            logger.debug("error processing request [resource: {}, op: {}]: {}", targetAddress,
                    message.getSubject(), s.cause().getMessage());
            MessageHelper.rejected(delivery,
                    ProtonHelper.condition(AmqpError.INTERNAL_ERROR, "internal error"));
        }
    });

    if (passesFormalVerification(targetAddress, message)) {

        final HonoUser clientPrincipal = Constants.getClientPrincipal(con);
        isAuthorized(clientPrincipal, targetAddress, message.getSubject()).compose(authorized -> {
            logger.debug("client [{}] is {}authorized to {}:{}", clientPrincipal.getName(),
                    authorized ? "" : "not ", targetAddress, message.getSubject());
            if (authorized) {
                try {
                    processRequest(message, targetAddress, Constants.getClientPrincipal(con));
                    requestTracker.complete();
                } catch (DecodeException e) {
                    requestTracker.fail(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload"));
                }
            } else {
                requestTracker.fail(new AmqpErrorException(AmqpError.UNAUTHORIZED_ACCESS, "unauthorized"));
            }
        }, requestTracker);
    } else {
        requestTracker.fail(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload"));
    }
}

From source file:org.eclipse.hono.service.auth.delegating.AuthenticationServerClient.java

License:Open Source License

/**
 * Verifies username/password credentials with a remote authentication server using SASL PLAIN.
 * //from   w  w  w . j a v a 2s  .  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 the authenticated user's claims.
 */
public void verifyPlain(final String authzid, final String authcid, final String password,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    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 server"));
        } 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()));
                }
                ProtonConnection con = conAttempt.result();
                if (con != null) {
                    LOG.debug("closing connection to authentication server");
                    con.close();
                }
            });

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

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

From source file:org.eclipse.hono.service.auth.delegating.AuthenticationServerClient.java

License:Open Source License

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