Example usage for io.vertx.core Future setHandler

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

Introduction

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

Prototype

@Fluent
default Future<T> setHandler(Handler<AsyncResult<T>> handler) 

Source Link

Document

Like #onComplete(Handler) .

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 {/*  www.  java 2 s .  com*/
            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.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 {//  w  ww .j av  a2 s.com
        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.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;/*from w  w  w.  j  av a 2 s.  c  o m*/
            stopFuture.complete();
        });

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

From source file:org.eclipse.hono.service.registration.impl.FileBasedRegistrationService.java

License:Open Source License

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

    if (running) {
        Future<Void> stopTracker = Future.future();
        stopTracker.setHandler(stopAttempt -> {
            running = false;//from  w w w. j  av a2s . c  om
            stopFuture.complete();
        });

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

From source file:org.eclipse.hono.vertx.example.base.HonoConsumerBase.java

License:Open Source License

/**
 * Initiate the connection and set the message handling method to treat data that is received.
 *
 * @throws Exception Thrown if the latch is interrupted during waiting or if the read from System.in throws an IOException.
 *//*from   w  ww  .  ja v a2s.co m*/
protected void consumeData() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final Future<MessageConsumer> consumerFuture = Future.future();

    consumerFuture.setHandler(result -> {
        if (!result.succeeded()) {
            System.err.println("honoClient could not create telemetry consumer for "
                    + HonoExampleConstants.HONO_AMQP_CONSUMER_HOST + ":"
                    + HonoExampleConstants.HONO_AMQP_CONSUMER_PORT + " : " + result.cause());
        }
        latch.countDown();
    });

    honoClient.connect(this::onDisconnect).compose(connectedClient -> createConsumer())
            .setHandler(consumerFuture.completer());

    latch.await();

    if (consumerFuture.succeeded()) {
        System.in.read();
    }
    vertx.close();
}

From source file:pt.davidafsilva.slacker.api.AbstractSlackerExecutor.java

License:Open Source License

/**
 * Handles an incoming request from the event bus
 *
 * @param request the request message to be handled
 *///from  w ww  .  j a  v a2 s.c  om
private void handleExecutorEvent(final Message<SlackerRequest> request) {
    LOGGER.info("<=<= receiving incoming request <=<=");
    LOGGER.debug(request);

    // execute the request handling asynchronously
    context.runOnContext(a -> {
        final Future<SlackerResponse> future = futureFactory.future();
        execute(request.body(), future);
        future.setHandler(handler -> {
            if (handler.succeeded()) {
                LOGGER.info("=>=> successfully handled request =>=>");
                LOGGER.debug(handler.result());
                request.reply(handler.result(),
                        new DeliveryOptions().setCodecName(SlackerResponseMessageCodec.NAME));
            } else {
                request.fail(ResultCode.ERROR.ordinal(), handler.cause().getMessage());
                LOGGER.error("failed to handle request", handler.cause());
            }
        });
    });
}

From source file:se.liquidbytes.jel.JelStarter.java

License:Apache License

/**
 * Startup application verticles/*from  ww w .ja v a2s .c  o m*/
 */
private static void startServer() {

    logger.info("Starting JEL-server..." + (Settings.isDebug() ? " AND RUNNING IN DEBUG-MODE!" : ""));

    VertxOptions options = new VertxOptions();
    if (Settings.isDebug()) {
        options.setBlockedThreadCheckInterval(1000 * 60 * 60); // Disable errors about event-loop being blocked when stuck on breakpoints. This will clutter the console otherwise.
    }

    vertx = Vertx.vertx(options);

    Future<Void> future = Future.future();
    future.setHandler(res -> {
        if (res.failed()) {
            shutdownServer(); // If any of the vertices failed to deploy, shut down the application.
        } else {
            logger.debug("Done deploying main verticles.");
        }
    });

    // Start up verticles in turn. If one fails ignore the rest.
    deployDatabaseVerticle(future, (Future<Void> event1) -> {
        deployMainJelVerticle(future, (Future<Void> event2) -> {
            deployWebserverVerticle(future, null);
        });
    });
}

From source file:se.liquidbytes.jel.system.impl.JelServiceImpl.java

License:Apache License

/**
 * Method for stopping service, must be called upon during application shutdown.
 *//* w  w w.  j  av a  2 s .  co  m*/
@Override
public void stop() {
    if (JelService.deviceManager() != null) {
        JelService.deviceManager().stop();
    }

    JelService.vertx().setTimer(500, h -> {
        if (JelService.adapterManager() != null) {
            Future<Void> future = Future.future();
            future.setHandler(res -> {
                if (JelService.pluginManager() != null) {
                    JelService.pluginManager().stop();
                }
            });

            JelService.adapterManager().stop(future);
        }
    });
}

From source file:studio.lysid.scales.deploy.LauncherVerticle.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    DeploymentOptionsParser.parseVerticleDeploymentOptionsJsonFile();

    // We can safely deploy Command, EventStore, and Query in parallel.
    // Facade must be the last one.

    Future<Void> startEventStoreFuture = startVerticle(this.vertx, Verticle.EventStore);
    Future<Void> startCommandFuture = startVerticle(this.vertx, Verticle.Command);
    Future<Void> startQueryFuture = startVerticle(this.vertx, Verticle.Query);

    CompositeFuture.all(startCommandFuture, startEventStoreFuture, startQueryFuture).setHandler(ar -> {
        if (ar.succeeded()) {
            startFuture.setHandler(startVerticle(this.vertx, Verticle.Facade).completer());
        } else {/*from w  w  w  . j  a  v  a2 s  .c o  m*/
            startFuture.fail(ar.cause());
        }
    });
}