List of usage examples for io.vertx.core Future compose
default <U> Future<U> compose(Function<T, Future<U>> successMapper,
Function<Throwable, Future<U>> failureMapper)
When this future (the one on which compose is called) succeeds, the successMapper will be called with the completed value and this mapper returns another future object.
From source file:com.themonkee.vertx.web.impl.MongoSessionStoreImpl.java
License:Open Source License
public MongoSessionStoreImpl(Vertx vertx, MongoClient mongoClient, JsonObject options, Future<MongoSessionStore> resultHandler) { this.random = new PRNG(vertx); this.vertx = vertx; this.mongoClient = mongoClient; if (options != null) { if (options.containsKey("collection")) this.sessionCollection = options.getString("collection"); }/* ww w . j a va 2s. com*/ Future<Void> futCreateColl = Future.future(); // try to create collection, if it is created or already exists its OK this.mongoClient.createCollection(this.sessionCollection, (AsyncResult<Void> res) -> { if (res.succeeded() || res.cause().getMessage().contains("collection already exists")) { futCreateColl.complete(); } else { futCreateColl.fail(res.cause()); } }); futCreateColl.compose(v -> { // create the session expiry index // SessionImpl sets _expire field to Date when session document must be deleted on save // so we set expireAfterSeconds to 0 so its deleted when that Date is hit // see https://docs.mongodb.com/manual/tutorial/expire-data/ this.mongoClient.createIndexWithOptions(this.sessionCollection, new JsonObject().put(SessionImpl.EXPIRE_FIELD, 1), new IndexOptions().expireAfter(0L, TimeUnit.SECONDS), res -> { if (res.succeeded()) { resultHandler.complete(this); } else { resultHandler.fail(res.cause()); } }); }, resultHandler); }
From source file:examples.CoreExamples.java
License:Open Source License
public void exampleFuture6(Vertx vertx) { FileSystem fs = vertx.fileSystem(); Future<Void> startFuture = Future.future(); Future<Void> fut1 = Future.future(); fs.createFile("/foo", fut1.completer()); fut1.compose(v -> { // When the file is created (fut1), execute this: Future<Void> fut2 = Future.future(); fs.writeFile("/foo", Buffer.buffer(), fut2.completer()); return fut2; }).compose(v -> {/* w w w. j a v a2 s.c o m*/ // When the file is written (fut2), execute this: fs.move("/foo", "/bar", startFuture.completer()); }, // mark startFuture it as failed if any step fails. startFuture); }
From source file:io.apiman.gateway.engine.vertx.shareddata.SharedGlobalDataRegistry.java
License:Apache License
@SuppressWarnings("rawtypes") // CompositeFuture.all(list) requires raw futures. @Override/*from www .ja v a 2 s . co m*/ public void registerClient(Client client, IAsyncResultHandler<Void> resultHandler) { List<Future> futures = new ArrayList<>(client.getContracts().size()); List<Contract> contracts = new ArrayList<>(client.getContracts()); String clientIndex = getClientIndex(client); // Future for each contract and execute get. for (Contract contract : contracts) { Future future = Future.future(); futures.add(future); String apiIndex = getApiIndex(contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion()); objectMap.get(apiIndex, future.completer()); } CompositeFuture.all(futures).setHandler(compositeResult -> { if (compositeResult.succeeded()) { // If any contract didn't correspond to a stored API. Contract failedContract = null; for (int i = 0; i < futures.size(); i++) { if (futures.get(i).result() == null) { failedContract = contracts.get(0); break; } } // If we found an invalid contract. if (failedContract != null) { Exception ex = new RegistrationException( Messages.i18n.format("InMemoryRegistry.ApiNotFoundInOrg", failedContract.getApiId(), failedContract.getApiOrgId())); resultHandler.handle(AsyncResultImpl.create(ex)); } else { Future<Object> putNewApiKeyFuture = Future.future(); Future<Object> endFuture = Future.future(); // Order: Create new API Key reference; Replace old ID -> API mapping; Delete old key reference) // This should ensure no breaking/irreconcilable behaviour. objectMap.putIfAbsent(client.getApiKey(), client, putNewApiKeyFuture.completer()); // Replace API Key reference putNewApiKeyFuture.compose(clientWithSameApiKey -> { Future<Object> replaceClientFuture = Future.future(); // There's a small chance the same key will replace the old one, usually // only in hard-coded tests. Generally sameKeyReplace will be null. if (clientWithSameApiKey != null) { //System.err.println("!!!!! Same API Key -- Replacing. Must not delete later. !!!!!!"); objectMap.replace(client.getApiKey(), client, replaceClientFuture.completer()); } else { objectMap.putIfAbsent(clientIndex, client, replaceClientFuture.completer()); } return replaceClientFuture; // Remove old API key reference }).compose(oldClientRaw -> { Client oldClient = (Client) oldClientRaw; if (oldClientRaw != null && !oldClient.getApiKey().equals(client.getApiKey())) { objectMap.remove(oldClient.getApiKey(), endFuture.completer()); } else { endFuture.complete(); } }, endFuture) // When finished, call this handler and then resultHandler .setHandler(handleResult(resultHandler)); } } else { resultHandler.handle(AsyncResultImpl.create(compositeResult.cause())); } }); }
From source file:org.eclipse.hono.client.impl.AbstractHonoClient.java
License:Open Source License
/** * Closes this client's sender and receiver links to Hono. * /* w w w. j a va 2s. c om*/ * @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 www. j ava2 s.com 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.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);//from ww w . j a v 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 w w w.java2 s.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
private Future<Void> send(final String msg, final Map<String, Object> props, final String registrationAssertion) { Future<Void> result = Future.future(); Future<MessageSender> senderTracker = Future.future(); if (activeProfiles.contains("event")) { client.getOrCreateEventSender(tenantId, senderTracker.completer()); } else {//from w w w . j a va 2 s .c om client.getOrCreateTelemetrySender(tenantId, senderTracker.completer()); } senderTracker.compose(sender -> { if (!sender.send(deviceId, props, msg, "text/plain", registrationAssertion)) { LOG.info("sender has no credit (yet), maybe no consumers attached? Try again ..."); } result.complete(); }, result); return result; }
From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java
License:Open Source License
@Override public final Future<Void> stopInternal() { Future<Void> shutdownHandler = Future.future(); Future<Void> tracker = Future.future(); if (server != null) { server.close(tracker.completer()); } else {/*from ww w.ja va 2 s . c o m*/ LOG.info("service has been already shut down"); tracker.complete(); } tracker.compose(t -> { if (insecureServer != null) { insecureServer.close(shutdownHandler.completer()); } else { shutdownHandler.complete(); } }, shutdownHandler); return shutdownHandler; }