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.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

private Future<HttpServer> bindSecureHttpServer(final Router router) {

    if (isSecurePortEnabled()) {
        Future<HttpServer> result = Future.future();
        final String bindAddress = server == null ? getConfig().getBindAddress() : "?";
        if (server == null) {
            server = vertx.createHttpServer(getHttpServerOptions());
        }//from w  ww  . j a  v  a2s  .  com
        server.requestHandler(router::accept).listen(done -> {
            if (done.succeeded()) {
                LOG.info("secure http server listening on {}:{}", bindAddress, server.actualPort());
                result.complete(done.result());
            } else {
                LOG.error("error while starting up secure http server", done.cause());
                result.fail(done.cause());
            }
        });
        return result;
    } else {
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

private Future<HttpServer> bindInsecureHttpServer(final Router router) {

    if (isInsecurePortEnabled()) {
        Future<HttpServer> result = Future.future();
        final String bindAddress = insecureServer == null ? getConfig().getInsecurePortBindAddress() : "?";
        if (insecureServer == null) {
            insecureServer = vertx.createHttpServer(getInsecureHttpServerOptions());
        }/*from w w  w.  j a  va  2 s  .c  o  m*/
        insecureServer.requestHandler(router::accept).listen(done -> {
            if (done.succeeded()) {
                LOG.info("insecure http server listening on {}:{}", bindAddress, insecureServer.actualPort());
                result.complete(done.result());
            } else {
                LOG.error("error while starting up insecure http server", done.cause());
                result.fail(done.cause());
            }
        });
        return result;
    } else {
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

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

    try {//from  w ww  . j  av  a  2s  .c  o  m
        preShutdown();
    } catch (Exception e) {
        LOG.error("error in preShutdown", e);
    }

    Future<Void> shutdownTracker = Future.future();
    shutdownTracker.setHandler(done -> {
        if (done.succeeded()) {
            LOG.info("HTTP adapter has been shut down successfully");
            stopFuture.complete();
        } else {
            LOG.info("error while shutting down adapter", done.cause());
            stopFuture.fail(done.cause());
        }
    });

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

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

    CompositeFuture.all(serverStopTracker, insecureServerStopTracker).compose(v -> {
        Future<Void> honoClientStopTracker = Future.future();
        closeClients(honoClientStopTracker.completer());
        return honoClientStopTracker;
    }).compose(v -> postShutdown()).compose(s -> shutdownTracker.complete(), shutdownTracker);
}

From source file:org.eclipse.hono.adapter.kura.KuraProtocolAdapter.java

License:Open Source License

Future<ResourceIdentifier> mapTopic(final MqttContext ctx) {

    final Future<ResourceIdentifier> result = Future.future();
    try {//  w  w w.  ja  v  a 2  s . c  o  m
        final ResourceIdentifier topic = ResourceIdentifier.fromString(ctx.message().topicName());
        ResourceIdentifier mappedTopic = null;

        if (getConfig().getControlPrefix().equals(topic.getEndpoint())) {

            // this is a "control" message
            ctx.setContentType(getConfig().getCtrlMsgContentType());
            final String[] mappedPath = Arrays.copyOf(topic.getResourcePath(), topic.getResourcePath().length);
            mappedPath[0] = getEndpoint(ctx.message().qosLevel());
            mappedTopic = ResourceIdentifier.fromPath(mappedPath);

        } else {

            // map "data" messages based on QoS
            ctx.setContentType(getConfig().getDataMsgContentType());
            final String[] mappedPath = new String[topic.getResourcePath().length + 1];
            System.arraycopy(topic.getResourcePath(), 0, mappedPath, 1, topic.getResourcePath().length);
            mappedPath[0] = getEndpoint(ctx.message().qosLevel());
            mappedTopic = ResourceIdentifier.fromPath(mappedPath);
        }

        if (mappedTopic.getResourcePath().length < 3) {
            // topic does not contain account_name and client_id
            result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "topic does not comply with Kura format"));
        } else {
            LOG.debug(
                    "mapped Kura message [topic: {}, QoS: {}] to Hono message [to: {}, device_id: {}, content-type: {}]",
                    topic, ctx.message().qosLevel(), mappedTopic.getBasePath(), mappedTopic.getResourceId(),
                    ctx.contentType());
            result.complete(mappedTopic);
        }
    } catch (final IllegalArgumentException e) {
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed topic name"));
    }
    return result;
}

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

License:Open Source License

private Future<MqttServer> bindMqttServer(final MqttServerOptions options, final MqttServer mqttServer) {

    final Future<MqttServer> result = Future.future();
    final MqttServer createdMqttServer = mqttServer == null ? MqttServer.create(this.vertx, options)
            : mqttServer;//from w w  w  .  jav  a2  s .  c  o  m

    createdMqttServer.endpointHandler(this::handleEndpointConnection).listen(done -> {

        if (done.succeeded()) {
            LOG.info("MQTT server running on {}:{}", getConfig().getBindAddress(),
                    createdMqttServer.actualPort());
            result.complete(createdMqttServer);
        } else {
            LOG.error("error while starting up MQTT server", done.cause());
            result.fail(done.cause());
        }
    });
    return result;
}

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

License:Open Source License

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

    final Future<Void> serverTracker = Future.future();
    if (this.server != null) {
        this.server.close(serverTracker.completer());
    } else {// w  ww .  j a  v  a2s . co m
        serverTracker.complete();
    }

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

    CompositeFuture.all(serverTracker, insecureServerTracker).compose(d -> stopFuture.complete(), stopFuture);
}

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

License:Open Source License

private Future<Device> handleEndpointConnectionWithAuthentication(final MqttEndpoint endpoint) {

    if (endpoint.auth() == null) {

        LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(),
                "device did not provide credentials in CONNECT packet");

        return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);

    } else {//from   www .j  a  v  a2 s  .  com

        final DeviceCredentials credentials = getCredentials(endpoint.auth());

        if (credentials == null) {

            LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(),
                    "device provided malformed credentials in CONNECT packet");
            return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);

        } else {

            return getTenantConfiguration(credentials.getTenantId()).compose(tenantConfig -> {
                if (tenantConfig.isAdapterEnabled(getTypeName())) {
                    LOG.debug("protocol adapter [{}] is enabled for tenant [{}]", getTypeName(),
                            credentials.getTenantId());
                    return Future.succeededFuture(tenantConfig);
                } else {
                    LOG.debug("protocol adapter [{}] is disabled for tenant [{}]", getTypeName(),
                            credentials.getTenantId());
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN,
                            "adapter disabled for tenant"));
                }
            }).compose(tenantConfig -> {
                final Future<Device> result = Future.future();
                usernamePasswordAuthProvider.authenticate(credentials, result.completer());
                return result;
            }).compose(authenticatedDevice -> {
                LOG.debug("successfully authenticated device [tenant-id: {}, auth-id: {}, device-id: {}]",
                        authenticatedDevice.getTenantId(), credentials.getAuthId(),
                        authenticatedDevice.getDeviceId());
                return triggerLinkCreation(authenticatedDevice.getTenantId()).map(done -> {
                    onAuthenticationSuccess(endpoint, authenticatedDevice);
                    return null;
                }).compose(ok -> accepted(authenticatedDevice));
            }).recover(t -> {
                LOG.debug("cannot establish connection with device [tenant-id: {}, auth-id: {}]",
                        credentials.getTenantId(), credentials.getAuthId(), t);
                if (t instanceof ServerErrorException) {
                    // one of the services we depend on might not be available (yet)
                    return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
                } else {
                    // validation of credentials has failed
                    return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
                }
            });

        }
    }
}

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

License:Open Source License

private Future<Void> triggerLinkCreation(final String tenantId) {

    final Future<Void> result = Future.future();
    LOG.debug("providently trying to open downstream links for tenant [{}]", tenantId);
    CompositeFuture/*from w  ww. ja  v a 2  s .co  m*/
            .join(getRegistrationClient(tenantId), getTelemetrySender(tenantId), getEventSender(tenantId))
            .setHandler(attempt -> {
                result.complete();
            });
    return result;
}

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

License:Open Source License

Future<ResourceIdentifier> checkAddress(final MqttContext ctx, final ResourceIdentifier address) {

    final Future<ResourceIdentifier> result = Future.future();

    if (ctx.authenticatedDevice() == null) {
        if (address.getTenantId() == null || address.getResourceId() == null) {
            result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "topic of unauthenticated message must contain tenant and device ID"));
        } else {//from w w w. jav a2s . co  m
            result.complete(address);
        }
    } else {
        if (address.getTenantId() != null && address.getResourceId() == null) {
            result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "topic of authenticated message must not contain tenant ID only"));
        } else if (address.getTenantId() == null && address.getResourceId() == null) {
            // use authenticated device's tenant to fill in missing information
            final ResourceIdentifier downstreamAddress = ResourceIdentifier.from(address.getEndpoint(),
                    ctx.authenticatedDevice().getTenantId(), ctx.authenticatedDevice().getDeviceId());
            result.complete(downstreamAddress);
        } else {
            result.complete(address);
        }
    }
    return result;
}

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

License:Open Source License

private Future<MqttServer> bindSecureMqttServer() {

    if (isSecurePortEnabled()) {
        MqttServerOptions options = new MqttServerOptions();
        options.setHost(getConfig().getBindAddress()).setPort(determineSecurePort())
                .setMaxMessageSize(getConfig().getMaxPayloadSize());
        addTlsKeyCertOptions(options);/*from  w  ww  .  ja v  a2 s .  c om*/
        addTlsTrustOptions(options);

        Future<MqttServer> result = Future.future();
        result.setHandler(mqttServerAsyncResult -> {
            server = mqttServerAsyncResult.result();
        });
        bindMqttServer(options, server, result);
        return result;
    } else {
        return Future.succeededFuture();
    }
}