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.auth.device.CredentialsApiAuthProvider.java

License:Open Source License

@Override
public final void authenticate(final DeviceCredentials deviceCredentials,
        final Handler<AsyncResult<Device>> resultHandler) {

    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    final Future<Device> validationResult = Future.future();
    validationResult.setHandler(resultHandler);

    getCredentialsForDevice(deviceCredentials).recover(t -> {
        final ServiceInvocationException e = (ServiceInvocationException) t;
        if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
        } else {//  ww  w.  j av  a2 s .co  m
            return Future.failedFuture(t);
        }
    }).map(credentialsOnRecord -> {
        if (deviceCredentials.validate(credentialsOnRecord)) {
            return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId());
        } else {
            throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials");
        }
    }).setHandler(resultHandler);
}

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

License:Open Source License

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

    final Future<Boolean> result = Future.future();
    final JsonObject authRequest = AuthorizationConstants.getAuthorizationMsg(user.getName(),
            resource.toString(), intent.toString());
    vertx.eventBus().send(AuthorizationConstants.EVENT_BUS_ADDRESS_AUTHORIZATION_IN, authRequest, res -> {
        result.complete(res.succeeded() && AuthorizationConstants.ALLOWED.equals(res.result().body()));
    });/*from w ww  .  j a v a2s  . c  o m*/
    return result;
}

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

License:Open Source License

@Override
public void process(final Handler<Boolean> completionHandler) {

    String[] remoteMechanisms = sasl.getRemoteMechanisms();

    if (remoteMechanisms.length == 0) {
        LOG.debug("client provided an empty list of SASL mechanisms [hostname: {}, state: {}]",
                sasl.getHostname(), sasl.getState().name());
        completionHandler.handle(false);
    } else {/*from  ww w . j a  va 2s . c om*/
        String chosenMechanism = remoteMechanisms[0];
        LOG.debug("client wants to authenticate using SASL [mechanism: {}, host: {}, state: {}]",
                chosenMechanism, sasl.getHostname(), sasl.getState().name());

        Future<HonoUser> authTracker = Future.future();
        authTracker.setHandler(s -> {
            if (s.succeeded()) {

                HonoUser user = s.result();
                LOG.debug("authentication of client [authorization ID: {}] succeeded", user.getName());
                Constants.setClientPrincipal(protonConnection, user);
                succeeded = true;
                registerTimerForHandlingExpiredToken(user, protonConnection);
                sasl.done(SaslOutcome.PN_SASL_OK);

            } else {

                LOG.debug("authentication failed: " + s.cause().getMessage());
                sasl.done(SaslOutcome.PN_SASL_AUTH);

            }
            completionHandler.handle(Boolean.TRUE);
        });

        byte[] saslResponse = new byte[sasl.pending()];
        sasl.recv(saslResponse, 0, saslResponse.length);

        verify(chosenMechanism, saslResponse, authTracker.completer());
    }
}

From source file:org.eclipse.hono.service.auth.impl.Application.java

License:Open Source License

/**
 * Deploys the (file-based) authentication service implementation.
 * // www . ja  v a 2s  .  com
 * @param maxInstances Ignored. This application always deploys a single instance of
 *                     the authentication service.
 */
@Override
protected Future<Void> deployRequiredVerticles(final int maxInstances) {

    Future<Void> result = Future.future();
    if (authenticationService == null) {
        result.fail("no authentication service implementation configured");
    } else {
        log.debug("deploying {}", authenticationService);
        getVertx().deployVerticle(authenticationService, s -> {
            if (s.succeeded()) {
                result.complete();
            } else {
                result.fail(s.cause());
            }
        });
    }
    return result;
}

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

License:Open Source License

private Future<Void> checkCertPath(final X509Certificate deviceCertificate, final TrustAnchor trustAnchor) {

    final Future<Void> result = Future.future();
    try {//w w w. j  ava  2 s. c  om
        final PKIXParameters params = new PKIXParameters(Collections.singleton(trustAnchor));
        // TODO do we need to check for revocation?
        params.setRevocationEnabled(false);
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final CertPath certPath = factory.generateCertPath(Collections.singletonList(deviceCertificate));
        final CertPathValidator validator = CertPathValidator.getInstance("PKIX");
        validator.validate(certPath, params);
        LOG.debug("validation of device certificate [subject DN: {}] succeeded",
                deviceCertificate.getSubjectX500Principal().getName());
        result.complete();
    } catch (GeneralSecurityException e) {
        LOG.debug("validation of device certificate [subject DN: {}] failed",
                deviceCertificate.getSubjectX500Principal().getName(), e);
        result.fail(e);
    }
    return result;
}

From source file:org.eclipse.hono.service.command.CommandConnectionImpl.java

License:Open Source License

private Future<MessageConsumer> newCommandConsumer(final String tenantId, final String deviceId,
        final BiConsumer<ProtonDelivery, Message> messageConsumer, final Handler<Void> closeHandler) {

    return checkConnected().compose(con -> {
        final Future<MessageConsumer> result = Future.future();
        CommandConsumer.create(context, clientConfigProperties, connection, tenantId, deviceId, messageConsumer,
                closeHook -> closeHandler.handle(null), result.completer());
        return result;
    });/*from   ww  w.  j  a  v  a2s .  c  o m*/
}

From source file:org.eclipse.hono.service.command.CommandConnectionImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from w  w  w  .  ja v  a2 s .c om*/
 */
public Future<CommandResponseSender> getOrCreateCommandResponseSender(final String tenantId,
        final String deviceId, final String replyId) {

    Objects.requireNonNull(tenantId);
    final Future<CommandResponseSender> result = Future.future();
    getOrCreateSender(CommandResponseSenderImpl.getTargetAddress(tenantId, deviceId, replyId),
            () -> createCommandResponseSender(tenantId, deviceId, replyId)).setHandler(h -> {
                if (h.succeeded()) {
                    result.complete((CommandResponseSender) h.result());
                } else {
                    result.fail(h.cause());
                }
            });
    return result;
}

From source file:org.eclipse.hono.service.command.CommandConnectionImpl.java

License:Open Source License

private Future<MessageSender> createCommandResponseSender(final String tenantId, final String deviceId,
        final String replyId) {

    return checkConnected().compose(connected -> {
        final Future<MessageSender> result = Future.future();
        CommandResponseSenderImpl.create(context, clientConfigProperties, connection, tenantId, deviceId,
                replyId, onSenderClosed -> {
                    activeSenders/*from  ww  w.ja v a 2 s  .c  o m*/
                            .remove(CommandResponseSenderImpl.getTargetAddress(tenantId, deviceId, replyId));
                }, result.completer());
        return result;
    });
}

From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java

License:Open Source License

@Override
protected void doStart(final Future<Void> startFuture) throws Exception {

    if (!running) {
        if (filename != null) {
            loadCredentialsData();//ww w.ja  v a 2  s .com
            if (saveToFile) {
                log.info("saving credentials to file every 3 seconds");
                vertx.setPeriodic(3000, saveIdentities -> {
                    saveToFile(Future.future());
                });
            } else {
                log.info("persistence is disabled, will not save credentials to file");
            }
        }
    }
    running = true;
    startFuture.complete();
}

From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java

License:Open Source License

@Override
protected void doStop(final Future<Void> stopFuture) {

    if (running) {
        Future<Void> stopTracker = Future.future();
        stopTracker.setHandler(stopAttempt -> {
            running = false;/*  w ww. j  a v a2  s. c  o m*/
            stopFuture.complete();
        });

        if (saveToFile) {
            saveToFile(stopTracker);
        } else {
            stopTracker.complete();
        }
    } else {
        stopFuture.complete();
    }
}