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

License:Open Source License

/**
 * Connects to the Hono Messaging component using the configured client.
 * //from  w  ww.  jav a 2s .c  o m
 * @param connectHandler The handler to invoke with the outcome of the connection attempt.
 *                       If {@code null} and the connection attempt failed, this method
 *                       tries to re-connect until a connection is established.
 */
protected final void connectToMessaging(final Handler<AsyncResult<HonoClient>> connectHandler) {

    if (messaging == null) {
        if (connectHandler != null) {
            connectHandler.handle(Future.failedFuture("Hono Messaging client not set"));
        }
    } else if (messaging.isConnected()) {
        LOG.debug("already connected to Hono Messaging");
        if (connectHandler != null) {
            connectHandler.handle(Future.succeededFuture(messaging));
        }
    } else {
        messaging.connect(createClientOptions(), connectAttempt -> {
            if (connectHandler != null) {
                connectHandler.handle(connectAttempt);
            } else {
                LOG.debug("connected to Hono Messaging");
            }
        }, this::onDisconnectMessaging);
    }
}

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

License:Open Source License

/**
 * Connects to the Device Registration service using the configured client.
 * //  w  ww.j a va 2  s  .  c o  m
 * @param connectHandler The handler to invoke with the outcome of the connection attempt.
 *                       If {@code null} and the connection attempt failed, this method
 *                       tries to re-connect until a connection is established.
 */
protected final void connectToDeviceRegistration(final Handler<AsyncResult<HonoClient>> connectHandler) {

    if (registration == null) {
        if (connectHandler != null) {
            connectHandler.handle(Future.failedFuture("Device Registration client not set"));
        }
    } else if (registration.isConnected()) {
        LOG.debug("already connected to Device Registration service");
        if (connectHandler != null) {
            connectHandler.handle(Future.succeededFuture(registration));
        }
    } else {
        registration.connect(createClientOptions(), connectAttempt -> {
            if (connectHandler != null) {
                connectHandler.handle(connectAttempt);
            } else {
                LOG.debug("connected to Device Registration service");
            }
        }, this::onDisconnectDeviceRegistry);
    }
}

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

License:Open Source License

/**
 * Connects to the Credentials service using the configured client.
 *
 * @param connectHandler The handler to invoke with the outcome of the connection attempt.
 *                       If {@code null} and the connection attempt failed, this method
 *                       tries to re-connect until a connection is established.
 *///from   w  w  w . j a  va  2  s.com
protected final void connectToCredentialsService(final Handler<AsyncResult<HonoClient>> connectHandler) {

    if (credentials == null) {
        if (connectHandler != null) {
            if (registration != null) {
                // give back registration client if credentials client is not configured
                connectHandler.handle(Future.succeededFuture(registration));
            } else {
                connectHandler.handle(Future
                        .failedFuture("Neither Credentials client nor Device Registration client is set"));
            }
        }
    } else if (credentials.isConnected()) {
        LOG.debug("already connected to Credentials service");
        if (connectHandler != null) {
            connectHandler.handle(Future.succeededFuture(credentials));
        }
    } else {
        credentials.connect(createClientOptions(), connectAttempt -> {
            if (connectHandler != null) {
                connectHandler.handle(connectAttempt);
            } else {
                LOG.debug("connected to Credentials service");
            }
        }, this::onDisconnectCredentialsService);
    }
}

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

License:Open Source License

/**
 * Closes the connections to the Hono Messaging component and the Device Registration service.
 * //  w w  w  . j av a 2s  .c  o  m
 * @param closeHandler The handler to notify about the result.
 */
protected final void closeClients(final Handler<AsyncResult<Void>> closeHandler) {

    Future<Void> messagingTracker = Future.future();
    Future<Void> registrationTracker = Future.future();
    Future<Void> credentialsTracker = Future.future();

    if (messaging == null) {
        messagingTracker.complete();
    } else {
        messaging.shutdown(messagingTracker.completer());
    }

    if (registration == null) {
        registrationTracker.complete();
    } else {
        registration.shutdown(registrationTracker.completer());
    }

    if (credentials == null) {
        credentialsTracker.complete();
    } else {
        credentials.shutdown(credentialsTracker.completer());
    }

    CompositeFuture.all(messagingTracker, registrationTracker, credentialsTracker).setHandler(s -> {
        if (closeHandler != null) {
            if (s.succeeded()) {
                closeHandler.handle(Future.succeededFuture());
            } else {
                closeHandler.handle(Future.failedFuture(s.cause()));
            }
        }
    });
}

From source file:org.eclipse.hono.service.auth.AbstractHonoAuthenticationService.java

License:Open Source License

/**
 * The authentication request is required to contain the SASL mechanism in property {@link AuthenticationConstants#FIELD_MECHANISM}
 * and the client's SASL response (Base64 encoded byte array) in property {@link AuthenticationConstants#FIELD_SASL_RESPONSE}.
 * When the mechanism is {@linkplain AuthenticationConstants#MECHANISM_EXTERNAL EXTERNAL}, the request must also contain
 * the <em>subject</em> distinguished name of the verified client certificate in property {@link AuthenticationConstants#FIELD_SUBJECT_DN}.
 * <p>/*from www  .ja  v  a2 s .c  om*/
 * An example request for a client using SASL EXTERNAL wishing to act as <em>NEW_IDENTITY</em> instead of <em>ORIG_IDENTITY</em>
 * looks like this:
 * <pre>
 * {
 *   "mechanism": "EXTERNAL",
 *   "sasl-response": "TkVXX0lERU5USVRZ",  // the Base64 encoded UTF-8 representation of "NEW_IDENTITY"
 *   "subject-dn": "CN=ORIG_IDENTITY" // the subject Distinguished Name from the verified client certificate
 * }
 * </pre>
 */
@Override
public final void authenticate(final JsonObject authRequest,
        final Handler<AsyncResult<HonoUser>> resultHandler) {

    final String mechanism = Objects.requireNonNull(authRequest)
            .getString(AuthenticationConstants.FIELD_MECHANISM);
    log.debug("received authentication request [mechanism: {}]", mechanism);

    if (AuthenticationConstants.MECHANISM_PLAIN.equals(mechanism)) {

        byte[] saslResponse = authRequest.getBinary(AuthenticationConstants.FIELD_SASL_RESPONSE, new byte[0]);

        try {
            String[] fields = readFields(saslResponse);
            String authzid = fields[0];
            String authcid = fields[1];
            String pwd = fields[2];
            log.debug("processing PLAIN authentication request [authzid: {}, authcid: {}, pwd: *****]", authzid,
                    authcid);
            verifyPlain(authzid, authcid, pwd, resultHandler);
        } catch (CredentialException e) {
            // response did not contain expected values
            resultHandler.handle(Future.failedFuture(e));
        }

    } else if (AuthenticationConstants.MECHANISM_EXTERNAL.equals(mechanism)) {

        final String authzid = new String(authRequest.getBinary(AuthenticationConstants.FIELD_SASL_RESPONSE),
                StandardCharsets.UTF_8);
        final String subject = authRequest.getString(AuthenticationConstants.FIELD_SUBJECT_DN);
        log.debug("processing EXTERNAL authentication request [Subject DN: {}]", subject);
        verifyExternal(authzid, subject, resultHandler);

    } else {
        resultHandler.handle(Future.failedFuture("unsupported SASL mechanism"));
    }
}

From source file:org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService.java

License:Open Source License

@Override
public Future<Boolean> isAuthorized(final HonoUser user, final ResourceIdentifier resource,
        final Activity intent) {

    Objects.requireNonNull(user);
    Objects.requireNonNull(resource);
    Objects.requireNonNull(intent);

    if (user.isExpired()) {
        return Future.failedFuture("user information expired");
    } else {//from   www.  ja va 2  s.  c o m
        return Future.succeededFuture(user.getAuthorities().isAuthorized(resource, intent));
    }
}

From source file:org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService.java

License:Open Source License

@Override
public Future<Boolean> isAuthorized(final HonoUser user, final ResourceIdentifier resource,
        final String operation) {

    Objects.requireNonNull(user);
    Objects.requireNonNull(resource);
    Objects.requireNonNull(operation);

    if (user.isExpired()) {
        return Future.failedFuture("user information expired");
    } else {//from   w  ww  .ja  v  a  2 s .c o  m
        return Future.succeededFuture(user.getAuthorities().isAuthorized(resource, operation));
    }
}

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  2 s.c om*/
 * @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.device.CredentialsApiAuthProvider.java

License:Open Source License

/**
 * Gets a client for the Credentials service.
 * // w w  w . j a va  2s  .  c o  m
 * @param tenantId The tenant to get the client for.
 * @return A future containing the client.
 */
protected final Future<CredentialsClient> getCredentialsClient(final String tenantId) {
    if (credentialsServiceClient == null) {
        return Future.failedFuture(new IllegalStateException("no credentials client set"));
    } else {
        return credentialsServiceClient.getOrCreateCredentialsClient(tenantId);
    }
}

From source file:org.eclipse.hono.service.auth.device.CredentialsApiAuthProvider.java

License:Open Source License

/**
 * Retrieves credentials from the Credentials service.
 * //w ww  .  ja  v  a2  s . c o  m
 * @param deviceCredentials The credentials provided by the device.
 * @return A future containing the credentials on record as retrieved from
 *         Hono's <em>Credentials</em> API.
 * @throws NullPointerException if device credentials is {@code null}.
 */
protected final Future<CredentialsObject> getCredentialsForDevice(final DeviceCredentials deviceCredentials) {

    Objects.requireNonNull(deviceCredentials);
    if (credentialsServiceClient == null) {
        return Future.failedFuture(new IllegalStateException("Credentials API client is not set"));
    } else {
        return getCredentialsClient(deviceCredentials.getTenantId())
                .compose(client -> client.get(deviceCredentials.getType(), deviceCredentials.getAuthId()));
    }
}