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:com.themonkee.vertx.web.MongoSessionStore.java

License:Open Source License

/**
 * Create a session store//from   w  w  w  .ja v a  2s  .  co m
 *
 * @param vertx  the Vert.x instance
 * @param mongoClient  client for accessing MongoDB
 * @param options  session store options, see README
 * @return  Future that resolves to created session store
 */
static Future<MongoSessionStore> create(Vertx vertx, MongoClient mongoClient, JsonObject options) {
    Future<MongoSessionStore> f = Future.future();
    new MongoSessionStoreImpl(vertx, mongoClient, options, f);
    return f;
}

From source file:com.themonkee.vertx.web.MongoSessionStore.java

License:Open Source License

/**
 * Create a session store/*from  w ww. j  a  v a 2 s .  c o m*/
 *
 * @param vertx  the Vert.x instance
 * @param mongoClientPoolName  name for pool name if client was already created using provided vertx instance
 * @param options  session store options, see README
 * @return Future that resolves to created session store
 */
static Future<MongoSessionStore> create(Vertx vertx, String mongoClientPoolName, JsonObject options) {
    Future<MongoSessionStore> f = Future.future();
    new MongoSessionStoreImpl(vertx, mongoClientPoolName, options, f);
    return f;
}

From source file:de.braintags.netrelay.processor.impl.AbstractProcessor.java

License:Open Source License

@Override
public void handle(Long timerId) {
    if (running) {
        LOGGER.info("still running");
        return;/*w  ww.j  a  va2 s .  c o m*/
    } else {
        running = true;
        this.timerId = timerId;
        Future<Void> future = Future.future();
        future.setHandler(ar -> {
            if (ar.failed()) {
                if (finishOnError) {
                    LOGGER.warn("Finishing processor " + getClass().getName() + " cause of an error",
                            ar.cause());
                    vertx.cancelTimer(timerId);
                } else {
                    LOGGER.warn("Error occured in processor " + getClass().getName(), ar.cause());
                }
                running = false;
            } else {
                LOGGER.info("successfully finished processor");
                running = false;
            }
        });
        handleEvent(future);
    }
}

From source file:examples.CoreExamples.java

License:Open Source License

public void exampleFutureAll1(HttpServer httpServer, NetServer netServer) {
    Future<HttpServer> httpServerFuture = Future.future();
    httpServer.listen(httpServerFuture.completer());

    Future<NetServer> netServerFuture = Future.future();
    netServer.listen(netServerFuture.completer());

    CompositeFuture.all(httpServerFuture, netServerFuture).setHandler(ar -> {
        if (ar.succeeded()) {
            // All servers started
        } else {/*from w  w w.ja va2 s  .c  o  m*/
            // At least one server failed
        }
    });
}

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 -> {// w w  w  .jav  a 2 s.co  m
        // When the file is created (fut1), execute this:
        Future<Void> fut2 = Future.future();
        fs.writeFile("/foo", Buffer.buffer(), fut2.completer());
        return fut2;
    }).compose(v -> {
        // 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  w ww  .  ja v a 2s  .  c om
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:io.apiman.gateway.engine.vertx.shareddata.SharedGlobalDataRegistry.java

License:Apache License

@Override
public void unregisterClient(Client client, IAsyncResultHandler<Void> resultHandler) {
    String clientIndex = getClientIndex(client);
    objectMap.get(clientIndex, handleSuccessfulResult(resultHandler, oldClientRaw -> {
        Client oldClient = (Client) oldClientRaw;
        if (oldClient == null) {
            Exception ex = new RegistrationException(Messages.i18n.format("InMemoryRegistry.ClientNotFound"));
            resultHandler.handle(AsyncResultImpl.create(ex));
        } else {/*from   w w w  . j av  a2s . co  m*/
            Future<Object> future1 = Future.future();
            Future<Object> future2 = Future.future();

            objectMap.remove(clientIndex, future1.completer());
            objectMap.remove(oldClient.getApiKey(), future2.completer());

            CompositeFuture.all(future1, future2).setHandler(handleCompositeResult(resultHandler));
        }
    }));
}

From source file:io.apiman.gateway.engine.vertx.shareddata.SharedGlobalDataRegistry.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w ww . ja v a 2s .com
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey,
        IAsyncResultHandler<ApiContract> handler) {
    String apiIndex = getApiIndex(apiOrganizationId, apiId, apiVersion);

    Future apiFuture = Future.future();
    Future clientFuture = Future.future();

    objectMap.get(apiIndex, apiFuture.completer());
    objectMap.get(apiKey, clientFuture.completer());

    CompositeFuture.all(apiFuture, clientFuture).setHandler(compositeResult -> {
        if (compositeResult.succeeded()) {
            Api api = (Api) apiFuture.result();
            Client client = (Client) clientFuture.result();

            if (api == null) {
                Exception error = new InvalidContractException(
                        Messages.i18n.format("InMemoryRegistry.NoClientForAPIKey", apiKey));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else if (client == null) {
                Exception error = new InvalidContractException(
                        Messages.i18n.format("InMemoryRegistry.ApiWasRetired", apiId, apiOrganizationId));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else {
                Optional<Contract> matchedOpt = client.getContracts().stream()
                        .filter(contract -> contract.matches(apiOrganizationId, apiId, apiVersion)).findFirst();

                if (matchedOpt.isPresent()) {
                    Contract contract = matchedOpt.get();
                    ApiContract apiContract = new ApiContract(api, client, contract.getPlan(),
                            contract.getPolicies());
                    handler.handle(AsyncResultImpl.create(apiContract));
                } else {
                    Exception error = new InvalidContractException(
                            Messages.i18n.format("InMemoryRegistry.NoContractFound", //$NON-NLS-1$
                                    client.getClientId(), api.getApiId()));
                    handler.handle(AsyncResultImpl.create(error, ApiContract.class));
                }
            }
        } else {
            handler.handle(AsyncResultImpl.create(compositeResult.cause()));
        }
    });
}

From source file:io.apiman.gateway.platforms.vertx3.verticles.InitVerticle.java

License:Apache License

private void deploy(String canonicalName, VerticleType verticleType,
        @SuppressWarnings("rawtypes") List<Future> deployList) {
    log.info("Will deploy {0} of type {1}", apimanConfig.getVerticleCount(verticleType), verticleType); //$NON-NLS-1$

    if (apimanConfig.getVerticleCount(verticleType) <= 0) {
        return;//w w w.j  av  a2s  . com
    }

    DeploymentOptions deploymentOptions = new DeploymentOptions(base)
            .setInstances(apimanConfig.getVerticleCount(verticleType));
    // Future for this deployment.
    Future<String> future = Future.future();
    // Do deployment
    vertx.deployVerticle(canonicalName, deploymentOptions, future.completer());
    // Set the future associated with the deployment so #all can wait for it.
    deployList.add(future);
}

From source file:io.engagingspaces.vertx.dataloader.DataLoader.java

License:Open Source License

/**
 * Requests to load the data with the specified key asynchronously, and returns a future of the resulting value.
 * <p>//from   w  w w  . j a  v  a  2s .c  om
 * If batching is enabled (the default), you'll have to call {@link DataLoader#dispatch()} at a later stage to
 * start batch execution. If you forget this call the future will never be completed (unless already completed,
 * and returned from cache).
 *
 * @param key the key to load
 * @return the future of the value
 */
public Future<V> load(K key) {
    Objects.requireNonNull(key, "Key cannot be null");
    Object cacheKey = getCacheKey(key);
    if (loaderOptions.cachingEnabled() && futureCache.containsKey(cacheKey)) {
        return futureCache.get(cacheKey);
    }

    Future<V> future = Future.future();
    if (loaderOptions.batchingEnabled()) {
        loaderQueue.put(key, future);
    } else {
        CompositeFuture compositeFuture = batchLoadFunction.load(Collections.singleton(key));
        if (compositeFuture.succeeded()) {
            future.complete(compositeFuture.result().resultAt(0));
        } else {
            future.fail(compositeFuture.cause());
        }
    }
    if (loaderOptions.cachingEnabled()) {
        futureCache.set(cacheKey, future);
    }
    return future;
}