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.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<MqttServer> bindInsecureMqttServer() {

    if (isInsecurePortEnabled()) {
        MqttServerOptions options = new MqttServerOptions();
        options.setHost(getConfig().getInsecurePortBindAddress()).setPort(determineInsecurePort())
                .setMaxMessageSize(getConfig().getMaxPayloadSize());

        Future<MqttServer> result = Future.future();
        result.setHandler(mqttServerAsyncResult -> {
            insecureServer = mqttServerAsyncResult.result();
        });//from ww w. ja  va  2s.  c  om
        bindMqttServer(options, insecureServer, result);
        return result;
    } else {
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

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

    Future<Void> shutdownTracker = Future.future();
    shutdownTracker.setHandler(done -> {
        if (done.succeeded()) {
            LOG.info("MQTT adapter has been shut down successfully");
            stopFuture.complete();/*from www. jav a2  s .c  o m*/
        } else {
            LOG.info("error while shutting down MQTT adapter", done.cause());
            stopFuture.fail(done.cause());
        }
    });

    Future<Void> serverTracker = Future.future();
    if (this.server != null) {
        this.server.close(serverTracker.completer());
    } else {
        serverTracker.complete();
    }

    Future<Void> insecureServerTracker = Future.future();
    if (this.insecureServer != null) {
        this.insecureServer.close(insecureServerTracker.completer());
    } else {
        insecureServerTracker.complete();
    }

    CompositeFuture.all(serverTracker, insecureServerTracker).compose(d -> {
        closeClients(shutdownTracker.completer());
    }, shutdownTracker);
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private void publishMessage(final MqttEndpoint endpoint, final String tenantId, final String logicalDeviceId,
        final MqttPublishMessage message, final ResourceIdentifier resource) {
    LOG.trace("received message [client ID: {}, topic: {}, QoS: {}, payload {}]", endpoint.clientIdentifier(),
            message.topicName(), message.qosLevel(), message.payload().toString(Charset.defaultCharset()));

    try {/*from  ww w  .  j  av a 2  s.  c  o  m*/
        Future<Void> messageTracker = Future.future();
        messageTracker.setHandler(s -> {
            if (s.failed()) {
                LOG.debug("cannot process message [client ID: {}, deviceId: {}, topic: {}, QoS: {}]: {}",
                        endpoint.clientIdentifier(), logicalDeviceId, resource, message.qosLevel(),
                        s.cause().getMessage());
                metrics.incrementUndeliverableMqttMessages(resource.getEndpoint(), tenantId);
                close(endpoint);
            } else {
                LOG.trace("successfully processed message [client ID: {}, deviceId: {}, topic: {}, QoS: {}]",
                        endpoint.clientIdentifier(), logicalDeviceId, resource, message.qosLevel());
                metrics.incrementProcessedMqttMessages(resource.getEndpoint(), tenantId);
            }
        });

        // check that MQTT client tries to publish on topic with device_id same as on connection
        if (!getConfig().isAuthenticationRequired()
                && !resource.getResourceId().equals(endpoint.clientIdentifier())) {
            // MQTT client is trying to publish on a different device_id used on connection (MQTT has no way for
            // errors)
            messageTracker.fail("client not authorized");
        } else {
            Future<String> assertionTracker = getRegistrationAssertion(endpoint, tenantId, logicalDeviceId);
            Future<MessageSender> senderTracker = getSenderTracker(message, resource, tenantId);

            CompositeFuture.all(assertionTracker, senderTracker).compose(ok -> {
                doUploadMessage(logicalDeviceId, assertionTracker.result(), endpoint, message,
                        senderTracker.result(), messageTracker);
            }, messageTracker);
        }

    } catch (IllegalArgumentException e) {

        // MQTT client is trying to publish on invalid topic; it does not contain at least two segments
        LOG.debug("client [ID: {}] tries to publish on unsupported topic", endpoint.clientIdentifier());
        close(endpoint);
    }
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<String> getRegistrationAssertion(final MqttEndpoint endpoint, final String tenantId,
        final String logicalDeviceId) {
    String token = registrationAssertions.get(endpoint);
    if (token != null && !RegistrationAssertionHelperImpl.isExpired(token, 10)) {
        return Future.succeededFuture(token);
    } else {/*from   w ww  .j  ava2 s  .co m*/
        registrationAssertions.remove(endpoint);
        Future<String> result = Future.future();
        getRegistrationAssertion(tenantId, logicalDeviceId).compose(t -> {
            // if the client closes the connection right after publishing the messages and before that
            // the registration assertion has been returned, avoid to put it into the map
            if (endpoint.isConnected()) {
                LOG.trace("caching registration assertion for client [{}]", endpoint.clientIdentifier());
                registrationAssertions.put(endpoint, t);
            }
            result.complete(t);
        }, result);
        return result;
    }
}

From source file:org.eclipse.hono.adapter.VertxBasedAdapterApplication.java

License:Open Source License

@PostConstruct
public void registerVerticles() {

    if (running.compareAndSet(false, true)) {
        final int instanceCount = honoConfig.getMaxInstances();

        try {//from   w  ww.  j a va2  s. com
            final CountDownLatch latch = new CountDownLatch(1);
            final Future<Void> startFuture = Future.future();
            startFuture.setHandler(done -> {
                if (done.succeeded()) {
                    latch.countDown();
                } else {
                    LOG.error("could not start '{}' adapter", this.getName(), done.cause());
                }
            });

            deployVerticle(instanceCount, startFuture);

            if (latch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
                LOG.info("'{}' adapter startup completed successfully", this.getName());
            } else {
                LOG.error("startup timed out after {} seconds, shutting down ...",
                        honoConfig.getStartupTimeout());
                shutdown();
            }
        } catch (InterruptedException e) {
            LOG.error("startup process has been interrupted, shutting down ...");
            Thread.currentThread().interrupt();
            shutdown();
        }
    }
}

From source file:org.eclipse.hono.adapter.VertxBasedAdapterApplication.java

License:Open Source License

private void deployVerticle(final int instanceCount, final Future<Void> resultHandler) {

    LOG.debug("starting up {} instances of '{}' adapter verticle", instanceCount, this.getName());
    @SuppressWarnings("rawtypes")
    List<Future> results = new ArrayList<>();
    for (int i = 1; i <= instanceCount; i++) {
        final int instanceId = i;
        final Future<String> result = Future.future();
        results.add(result);//from w  ww  .j  av a 2 s.  c  o m
        vertx.deployVerticle(this.getAdapter(), d -> {
            if (d.succeeded()) {
                LOG.debug("verticle instance {} deployed", instanceId);
                result.complete();
            } else {
                LOG.debug("failed to deploy verticle instance {}", instanceId, d.cause());
                result.fail(d.cause());
            }
        });
    }
    CompositeFuture.all(results).setHandler(done -> {
        if (done.succeeded()) {
            resultHandler.complete();
        } else {
            resultHandler.fail(done.cause());
        }
    });
}

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

License:Open Source License

/**
 * Deploys all verticles the Hono server consists of.
 * // w ww.j  av a2  s. c  om
 * @return true if deployment was successful
 */
private boolean registerVerticles() {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    }

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final AtomicBoolean startupSucceeded = new AtomicBoolean(false);

    // without creating a first instance here, deployment of the HonoServer verticles fails
    // TODO: find out why
    HonoServer firstInstance = serverFactory.getHonoServer();

    final int instanceCount = honoConfig.getMaxInstances();

    Future<Void> started = Future.future();
    started.setHandler(ar -> {
        if (ar.failed()) {
            LOG.error("cannot start up HonoServer", ar.cause());
        } else {
            startupSucceeded.set(true);
        }
        startupLatch.countDown();
    });

    CompositeFuture.all(deployAuthenticationService(), // we only need 1 authentication service
            deployAuthorizationService(), // we only need 1 authorization service
            deployCredentialsService(), deployRegistrationService()).setHandler(ar -> {
                if (ar.succeeded()) {
                    deployServer(firstInstance, instanceCount, started);
                } else {
                    started.fail(ar.cause());
                }
            });

    try {
        if (startupLatch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
            if (startupSucceeded.get()) {
                LOG.info("Hono startup completed successfully");
            } else {
                shutdown();
            }
        } else {
            LOG.error("startup timed out after {} seconds, shutting down ...", honoConfig.getStartupTimeout());
            shutdown();
            startupSucceeded.set(false);
        }
    } catch (InterruptedException e) {
        LOG.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
        startupSucceeded.set(false);
    }
    return startupSucceeded.get();
}

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

License:Open Source License

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

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

License:Open Source License

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

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

License:Open Source License

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