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.deviceregistry.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.ja v a 2s . c om stopFuture.complete(); }); if (getConfig().isSaveToFile()) { saveToFile(stopTracker); } else { stopTracker.complete(); } } else { stopFuture.complete(); } }
From source file:org.eclipse.hono.example.ExampleReceiver.java
License:Open Source License
@PostConstruct private void start() { final Future<MessageConsumer> startupTracker = Future.future(); startupTracker.setHandler(startup -> { if (startup.succeeded()) { String consumerType = activeProfiles.contains(PROFILE_EVENT) ? PROFILE_EVENT : PROFILE_TELEMETRY; LOG.info("Receiver [tenant: {}, type: {}] created successfully, hit ctrl-c to exit", tenantId, consumerType);/*w ww .j av a 2 s.c o m*/ } else { LOG.error("Error occurred during initialization of receiver: {}", startup.cause().getMessage()); vertx.close(); } }); final Future<HonoClient> connectionTracker = Future.future(); client.connect(getClientOptions(), connectionTracker.completer(), this::onDisconnect); connectionTracker.compose(honoClient -> { onConnectionEstablished(startupTracker.completer()); }, startupTracker); }
From source file:org.eclipse.hono.example.ExampleSender.java
License:Open Source License
/** * Connects to the Hono server./*from ww w . j a v a2s .com*/ */ @PostConstruct public void prepare() { LOG.info("starting sender"); final CountDownLatch startup = new CountDownLatch(1); ctx = vertx.getOrCreateContext(); final Future<RegistrationResult> startupTracker = Future.future(); startupTracker.setHandler(done -> { if (done.succeeded()) { startup.countDown(); } else { LOG.error("Error occurred during initialization: {}", done.cause().getMessage()); } }); ctx.runOnContext(go -> { /* step 1: connect Hono client */ final Future<HonoClient> connectionTracker = Future.future(); client.connect(getClientOptions(), connectionTracker.completer()); connectionTracker.compose(v -> { /* step 2: create a registration client */ return getRegistrationClient(); }).compose(regClient -> { /* step 3: register a device */ Future<RegistrationResult> regResultTracker = Future.future(); regClient.register(deviceId, null, regResultTracker.completer()); return regResultTracker; }).compose(regResult -> { /* step 4: handle result of registration */ if (regResult.getStatus() == HTTP_CREATED || regResult.getStatus() == HTTP_CONFLICT) { LOG.info("device registered"); startupTracker.complete(); } else { startupTracker.fail(String.format("Failed to register device [%s]: %s", deviceId, regResult)); } }, startupTracker); }); try { if (!startup.await(5, TimeUnit.SECONDS)) { LOG.error("shutting down"); vertx.close(); } } catch (InterruptedException e) { // nothing to do } }
From source file:org.eclipse.hono.example.ExampleSender.java
License:Open Source License
/** * Reads user input from the console and sends it to the Hono server. *//*from w ww. j a v a 2s .c o m*/ @EventListener(classes = { ApplicationReadyEvent.class }) public void readMessagesFromStdin() { Runnable reader = new Runnable() { public void run() { try { // give Spring Boot some time to log its startup messages Thread.sleep(50); } catch (InterruptedException e) { } LOG.info("sender for tenant [{}] created successfully", tenantId); LOG.info("Enter some message(s) (hit return to send, ctrl-c to quit)"); String input; Scanner scanner = new Scanner(System.in); do { input = scanner.nextLine(); final String msg = input; if (!msg.isEmpty()) { final Map<String, Object> properties = new HashMap<>(); properties.put("my_prop_string", "I'm a string"); properties.put("my_prop_int", 10); final CountDownLatch latch = new CountDownLatch(1); Future<Boolean> sendTracker = Future.future(); sendTracker.setHandler(s -> { if (s.failed()) { LOG.info(s.cause().getMessage()); } }); getRegistrationAssertion().compose(token -> { return send(msg, properties, token); }).compose(sent -> { latch.countDown(); sendTracker.complete(); }, sendTracker); try { if (!latch.await(2, TimeUnit.SECONDS)) { sendTracker.fail("cannot connect to server"); } } catch (InterruptedException e) { // nothing to do } } } while (!input.isEmpty()); scanner.close(); }; }; new Thread(reader).start(); }
From source file:org.eclipse.hono.messaging.ForwardingDownstreamAdapter.java
License:Open Source License
@Override public final void onClientAttach(final UpstreamReceiver client, final Handler<AsyncResult<Void>> resultHandler) { if (!running) { throw new IllegalStateException("adapter must be started first"); }//from w w w .j a va 2s .c o m Objects.requireNonNull(client); Objects.requireNonNull(resultHandler); ProtonSender sender = activeSenders.get(client); if (sender != null && sender.isOpen()) { logger.info("reusing existing downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId()); resultHandler.handle(Future.succeededFuture()); } else { removeSender(client); // register the result handler to be failed if the connection to the downstream container fails during // the attempt to create a downstream sender clientAttachHandlers.add(resultHandler); Future<Void> tracker = Future.future(); tracker.setHandler(attempt -> { if (attempt.succeeded()) { logger.info("created downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId()); } else { logger.warn("can't create downstream sender [con: {}, link: {}]: {}", client.getConnectionId(), client.getLinkId(), attempt.cause().getMessage()); } clientAttachHandlers.remove(resultHandler); resultHandler.handle(attempt); }); final ResourceIdentifier targetAddress = ResourceIdentifier.fromString(client.getTargetAddress()); createSender(targetAddress, replenishedSender -> handleFlow(replenishedSender, client)) .compose(createdSender -> { addSender(client, createdSender); tracker.complete(); }, tracker); } }
From source file:org.eclipse.hono.messaging.HonoMessagingApplication.java
License:Open Source License
/** * Deploys the additional service implementations that are * required by the HonoServer./*from w w w. j ava 2 s.co m*/ * */ @Override protected Future<Void> deployRequiredVerticles(final int maxInstances) { Future<Void> result = Future.future(); Future<String> authFuture = deployAuthenticationService();// we only need 1 authentication service authFuture.setHandler(ar -> { if (ar.succeeded()) { result.complete(); } else { result.fail(ar.cause()); } }); return result; }
From source file:org.eclipse.hono.server.ForwardingDownstreamAdapter.java
License:Open Source License
@Override public final void onClientAttach(final UpstreamReceiver client, final Handler<AsyncResult<Void>> resultHandler) { if (!running) { throw new IllegalStateException("adapter must be started first"); }// w w w .jav a 2 s. com Objects.requireNonNull(client); Objects.requireNonNull(resultHandler); ProtonSender sender = activeSenders.get(client); if (sender != null && sender.isOpen()) { logger.info("reusing existing downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId()); resultHandler.handle(Future.succeededFuture()); } else { removeSender(client); // register the result handler to be failed if the connection to the downstream container fails during // the attempt to create a downstream sender clientAttachHandlers.add(resultHandler); Future<Void> tracker = Future.future(); tracker.setHandler(attempt -> { if (attempt.succeeded()) { logger.info("created downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId()); } else { logger.warn("can't create downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId(), attempt.cause()); } clientAttachHandlers.remove(resultHandler); resultHandler.handle(attempt); }); createSender(client.getTargetAddress(), replenishedSender -> handleFlow(replenishedSender, client)) .compose(createdSender -> { addSender(client, createdSender); tracker.complete(); }, tracker); } }
From source file:org.eclipse.hono.service.AbstractApplication.java
License:Open Source License
/** * Starts up this application.//from www . j av a 2 s.co m * <p> * The start up process entails the following steps: * <ol> * <li>invoke <em>deployRequiredVerticles</em> to deploy the verticle(s) implementing the service's functionality</li> * <li>invoke <em>deployServiceVerticles</em> to deploy the protocol specific service endpoints</li> * <li>invoke <em>postRegisterServiceVerticles</em> to perform any additional post deployment steps</li> * <li>start the health check server</li> * </ol> * * @param args The command line arguments provided to the application. */ public void run(final ApplicationArguments args) { if (vertx == null) { throw new IllegalStateException("no Vert.x instance has been configured"); } else if (serviceFactories.isEmpty()) { throw new IllegalStateException("no service factory has been configured"); } healthCheckServer = new HealthCheckServer(vertx, config); final CountDownLatch startupLatch = new CountDownLatch(1); final int startupTimeoutSeconds = config.getStartupTimeout(); Future<Void> started = Future.future(); started.setHandler(s -> { if (s.failed()) { log.error("cannot start up application", s.cause()); } else { startupLatch.countDown(); } }); deployRequiredVerticles(config.getMaxInstances()).compose(s -> deployServiceVerticles()) .compose(s -> postRegisterServiceVerticles()).compose(s -> healthCheckServer.start()) .compose(s -> started.complete(), started); try { if (startupLatch.await(startupTimeoutSeconds, TimeUnit.SECONDS)) { log.info("application startup completed successfully"); } else { log.error("startup timed out after {} seconds, shutting down ...", startupTimeoutSeconds); shutdown(); } } catch (InterruptedException e) { log.error("startup process has been interrupted, shutting down ..."); Thread.currentThread().interrupt(); shutdown(); } }
From source file:org.eclipse.hono.service.amqp.RequestResponseEndpoint.java
License:Open Source License
/** * Handles a request message received from a client. * <p>// w ww. j a v a2 s . c om * The message gets rejected if * <ul> * <li>the message does not pass {@linkplain #passesFormalVerification(ResourceIdentifier, Message) formal verification} * or</li> * <li>the client is not {@linkplain #isAuthorized(HonoUser, ResourceIdentifier, String) authorized to execute the operation} * indicated by the message's <em>subject</em> or</li> * <li>its payload cannot be parsed</li> * </ul> * * @param con The connection with the client. * @param receiver The link over which the message has been received. * @param targetAddress The address the message is sent to. * @param delivery The message's delivery status. * @param message The message. */ protected final void handleMessage(final ProtonConnection con, final ProtonReceiver receiver, final ResourceIdentifier targetAddress, ProtonDelivery delivery, Message message) { Future<Void> requestTracker = Future.future(); requestTracker.setHandler(s -> { if (s.succeeded()) { ProtonHelper.accepted(delivery, true); } else if (s.cause() instanceof AmqpErrorException) { AmqpErrorException cause = (AmqpErrorException) s.cause(); MessageHelper.rejected(delivery, cause.asErrorCondition()); } else { logger.debug("error processing request [resource: {}, op: {}]: {}", targetAddress, message.getSubject(), s.cause().getMessage()); MessageHelper.rejected(delivery, ProtonHelper.condition(AmqpError.INTERNAL_ERROR, "internal error")); } }); if (passesFormalVerification(targetAddress, message)) { final HonoUser clientPrincipal = Constants.getClientPrincipal(con); isAuthorized(clientPrincipal, targetAddress, message.getSubject()).compose(authorized -> { logger.debug("client [{}] is {}authorized to {}:{}", clientPrincipal.getName(), authorized ? "" : "not ", targetAddress, message.getSubject()); if (authorized) { try { processRequest(message, targetAddress, Constants.getClientPrincipal(con)); requestTracker.complete(); } catch (DecodeException e) { requestTracker.fail(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload")); } } else { requestTracker.fail(new AmqpErrorException(AmqpError.UNAUTHORIZED_ACCESS, "unauthorized")); } }, requestTracker); } else { requestTracker.fail(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload")); } }
From source file:org.eclipse.hono.service.auth.delegating.AuthenticationServerClient.java
License:Open Source License
/** * Verifies username/password credentials with a remote authentication server using SASL PLAIN. * /* w w w. java2 s. c om*/ * @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 the authenticated user's claims. */ public void verifyPlain(final String authzid, final String authcid, final String password, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) { 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 server")); } 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())); } ProtonConnection con = conAttempt.result(); if (con != null) { LOG.debug("closing connection to authentication server"); con.close(); } }); vertx.setTimer(5000, tid -> { if (!userTracker.isComplete()) { userTracker.fail("time out reached while waiting for token from authentication server"); } }); getToken(openCon, userTracker); } }); }