List of usage examples for io.vertx.core Future setHandler
@Fluent
default Future<T> setHandler(Handler<AsyncResult<T>> handler)
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 {// w ww. ja v a 2 s .c om 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.VertxBasedAdapterApplication.java
License:Open Source License
@PostConstruct public void registerVerticles() { if (running.compareAndSet(false, true)) { final int instanceCount = honoConfig.getMaxInstances(); try {/*from w w w . jav a 2 s . c om*/ 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.application.HonoApplication.java
License:Open Source License
/** * Deploys all verticles the Hono server consists of. * /*w ww . j a v a 2 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.client.impl.AbstractHonoClient.java
License:Open Source License
/** * Closes this client's sender and receiver links to Hono. * /*from ww w . ja v a 2 s. com*/ * @param closeHandler the handler to be notified about the outcome. * @throws NullPointerException if the given handler is {@code null}. */ protected void closeLinks(final Handler<AsyncResult<Void>> closeHandler) { Objects.requireNonNull(closeHandler); final Future<ProtonSender> senderCloseHandler = Future.future(); final Future<ProtonReceiver> receiverCloseHandler = Future.future(); receiverCloseHandler.setHandler(closeAttempt -> { if (closeAttempt.succeeded()) { closeHandler.handle(Future.succeededFuture()); } else { closeHandler.handle(Future.failedFuture(closeAttempt.cause())); } }); senderCloseHandler.compose(closedSender -> { if (receiver != null && receiver.isOpen()) { receiver.closeHandler(closeAttempt -> { LOG.debug("closed message consumer for [{}]", receiver.getSource().getAddress()); receiverCloseHandler.complete(receiver); }).close(); } else { receiverCloseHandler.complete(); } }, receiverCloseHandler); context.runOnContext(close -> { if (sender != null && sender.isOpen()) { sender.closeHandler(closeAttempt -> { LOG.debug("closed message sender for [{}]", sender.getTarget().getAddress()); senderCloseHandler.complete(sender); }).close(); } else { senderCloseHandler.complete(); } }); }
From source file:org.eclipse.hono.client.impl.AbstractRequestResponseClient.java
License:Open Source License
/** * Creates a client for a vert.x context. * * @param context The context to run all interactions with the server on. * @param con The connection to use for interacting with the service. * @param tenantId The tenant that the client will be scoped to. * @param creationHandler The handler to invoke with the created client. *///from w w w . j av a 2 s . co m protected AbstractRequestResponseClient(final Context context, final ProtonConnection con, final String tenantId, final Handler<AsyncResult<C>> creationHandler) { super(context); requestResponseAddressTemplate = String.format("%s/%%s", getName()); requestResponseReplyToAddressTemplate = String.format("%s/%%s/%%s", getName()); this.replyToAddress = String.format(requestResponseReplyToAddressTemplate, Objects.requireNonNull(tenantId), UUID.randomUUID()); final Future<ProtonSender> senderTracker = Future.future(); senderTracker.setHandler(r -> { if (r.succeeded()) { LOG.debug("request response client created"); this.sender = r.result(); creationHandler.handle(Future.succeededFuture((C) this)); } else { creationHandler.handle(Future.failedFuture(r.cause())); } }); final Future<ProtonReceiver> receiverTracker = Future.future(); context.runOnContext(create -> { final ProtonReceiver receiver = con.createReceiver(replyToAddress); receiver.setAutoAccept(true).setPrefetch(DEFAULT_SENDER_CREDITS).handler((delivery, message) -> { final Handler<AsyncResult<R>> handler = replyMap.remove(message.getCorrelationId()); if (handler != null) { R result = getRequestResponseResult(message); LOG.debug("received response [correlation ID: {}, status: {}]", message.getCorrelationId(), result.getStatus()); handler.handle(Future.succeededFuture(result)); } else { LOG.debug("discarding unexpected response [correlation ID: {}]", message.getCorrelationId()); } }).openHandler(receiverTracker.completer()).open(); receiverTracker.compose(openReceiver -> { this.receiver = openReceiver; ProtonSender sender = con.createSender(String.format(requestResponseAddressTemplate, tenantId)); sender.setQoS(ProtonQoS.AT_LEAST_ONCE).openHandler(senderTracker.completer()).open(); }, senderTracker); }); }
From source file:org.eclipse.hono.client.impl.AuthenticationServerClient.java
License:Open Source License
/** * Verifies username/password credentials with a remote authentication server using SASL PLAIN. * /*ww w. j a va2s . c o m*/ * @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 authenticated user's claims. */ public void verifyPlain(final String authzid, final String authcid, final String password, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) { final 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 service")); } 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())); } final ProtonConnection con = conAttempt.result(); if (con != null) { LOG.debug("closing connection to Authentication service"); con.close(); } }); vertx.setTimer(5000, tid -> { if (!userTracker.isComplete()) { userTracker.fail("time out reached while waiting for token from Authentication service"); } }); getToken(openCon, userTracker); } }); }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
License:Open Source License
private HonoClient createTelemetrySender(final String tenantId, final String deviceId, final Handler<AsyncResult<MessageSender>> creationHandler) { Future<MessageSender> senderTracker = Future.future(); senderTracker.setHandler(creationHandler); checkConnection().compose(/* w w w . jav a2s .c o m*/ connected -> TelemetrySenderImpl.create(context, connection, tenantId, deviceId, onSenderClosed -> { activeSenders.remove(TelemetrySenderImpl.getTargetAddress(tenantId, deviceId)); }, senderTracker.completer()), senderTracker); return this; }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
License:Open Source License
@Override public HonoClient createTelemetryConsumer(final String tenantId, final int prefetch, final Consumer<Message> telemetryConsumer, final Handler<AsyncResult<MessageConsumer>> creationHandler) { // register a handler to be notified if the underlying connection to the server fails // so that we can fail the result handler passed in final Handler<Void> connectionFailureHandler = connectionLost -> { creationHandler.handle(Future.failedFuture("connection to server lost")); };//from w w w . j a v a2s .c o m creationRequests.add(connectionFailureHandler); Future<MessageConsumer> consumerTracker = Future.future(); consumerTracker.setHandler(attempt -> { creationRequests.remove(connectionFailureHandler); creationHandler.handle(attempt); }); checkConnection().compose(connected -> TelemetryConsumerImpl.create(context, connection, tenantId, connectionFactory.getPathSeparator(), prefetch, telemetryConsumer, consumerTracker.completer()), consumerTracker); return this; }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
License:Open Source License
@Override public HonoClient createEventConsumer(final String tenantId, final int prefetch, final BiConsumer<ProtonDelivery, Message> eventConsumer, final Handler<AsyncResult<MessageConsumer>> creationHandler) { // register a handler to be notified if the underlying connection to the server fails // so that we can fail the result handler passed in final Handler<Void> connectionFailureHandler = connectionLost -> { creationHandler.handle(Future.failedFuture("connection to server lost")); };//from ww w . j a v a 2 s . c o m creationRequests.add(connectionFailureHandler); Future<MessageConsumer> consumerTracker = Future.future(); consumerTracker.setHandler(attempt -> { creationRequests.remove(connectionFailureHandler); creationHandler.handle(attempt); }); checkConnection().compose( connected -> EventConsumerImpl.create(context, connection, tenantId, connectionFactory.getPathSeparator(), prefetch, eventConsumer, consumerTracker.completer()), consumerTracker); return this; }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
License:Open Source License
private HonoClient createEventSender(final String tenantId, final String deviceId, final Handler<AsyncResult<MessageSender>> creationHandler) { Future<MessageSender> senderTracker = Future.future(); senderTracker.setHandler(creationHandler); checkConnection().compose(/*from ww w . j ava2 s . co m*/ connected -> EventSenderImpl.create(context, connection, tenantId, deviceId, onSenderClosed -> { activeSenders.remove(EventSenderImpl.getTargetAddress(tenantId, deviceId)); }, senderTracker.completer()), senderTracker); return this; }