Example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction

List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction.

Prototype

AsyncFunction

Source Link

Usage

From source file:com.orangerhymelabs.helenus.cassandra.table.ViewService.java

public ListenableFuture<View> update(View view) {
    ListenableFuture<Boolean> tableFuture = tables.exists(view.databaseName(), view.tableName());
    return Futures.transformAsync(tableFuture, new AsyncFunction<Boolean, View>() {
        @Override/*from   w  w  w.  j a  v a  2  s  .c  o  m*/
        public ListenableFuture<View> apply(Boolean exists) throws Exception {
            if (exists) {
                try {
                    ValidationEngine.validateAndThrow(view);
                    return views.update(view);
                } catch (ValidationException e) {
                    return Futures.immediateFailedFuture(e);
                }
            } else {
                return Futures.immediateFailedFuture(
                        new ItemNotFoundException("Database not found: " + view.databaseName()));
            }
        }
    });
}

From source file:org.blackbananacoin.ext.curconvert.testlog.CurFutureMixChain.java

public void run() throws Exception {

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }//w  w  w.ja v  a2  s  .  co  m
    });
    final GenericUrl urlBlockchain = new GenericUrl(EXURL_BLOCKCHAIN);
    final GenericUrl urlYahooTwd = new GenericUrl(EXURL_YAHOO_USDTWD);
    final HttpRequest requestBlockChain = requestFactory.buildGetRequest(urlBlockchain);

    final HttpRequest requestYahoo = requestFactory.buildGetRequest(urlYahooTwd);

    final ListenableFuture<Double> futureYahoo = pool.submit(new Callable<Double>() {
        public Double call() throws Exception {
            GenericJson jsonYahoo = requestYahoo.execute().parseAs(GenericJson.class);
            System.out.println(jsonYahoo);
            Map query = (Map) jsonYahoo.get("query");
            Map results = (Map) query.get("results");
            Map row = (Map) results.get("row");
            double twd = Double.parseDouble((String) row.get("col1"));
            System.out.println("======== GET TWD/USD Rate =========");
            System.out.println(twd);
            return twd;
        }
    });

    final AsyncFunction<Double, GenericJson> relevanceAsyncFun = new AsyncFunction<Double, GenericJson>() {
        public ListenableFuture<GenericJson> apply(final Double twdPerUsd) throws Exception {

            final ListenableFuture<GenericJson> futureReqBlockChain = pool.submit(new Callable<GenericJson>() {
                public GenericJson call() throws Exception {
                    GenericJson json = requestBlockChain.execute().parseAs(GenericJson.class);
                    handleTwdAppend(twdPerUsd, json);
                    return json;
                }

                private void handleTwdAppend(final Double twdPerUsd, GenericJson json) {
                    System.out.println(json);
                    Map usdJson = (Map) json.get("USD");
                    Map ntdJson = new HashMap<String, Object>();
                    BigDecimal usdBuy = (BigDecimal) usdJson.get("buy");
                    BigDecimal usdLast = (BigDecimal) usdJson.get("last");
                    BigDecimal usd15m = (BigDecimal) usdJson.get("15m");
                    BigDecimal usdSell = (BigDecimal) usdJson.get("sell");
                    BigDecimal twdBuy = usdBuy.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twdSell = usdSell.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twd15m = usd15m.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twdLast = usdLast.multiply(BigDecimal.valueOf(twdPerUsd));
                    ntdJson.put("buy", twdBuy);
                    ntdJson.put("sell", twdSell);
                    ntdJson.put("last", twdLast);
                    ntdJson.put("15m", twd15m);
                    ntdJson.put("symbol", "NT$");
                    json.put(YAHOO_CUR_TAG, ntdJson);
                    // System.out.println(json);
                }
            });

            return futureReqBlockChain;
        }
    };

    ListenableFuture<GenericJson> futureMix = Futures.transform(futureYahoo, relevanceAsyncFun);

    Futures.addCallback(futureMix, new FutureCallback<GenericJson>() {

        public void onSuccess(GenericJson result) {
            System.out.println("======== RESULT =========");
            System.out.println(result);
            pool.shutdown();
        }

        public void onFailure(Throwable t) {
            t.printStackTrace();
            pool.shutdown();
        }
    });

}

From source file:org.apache.cassandra.repair.RepairJob.java

/**
 * Runs repair job.//from  ww  w.j av a2s.  c o  m
 *
 * This sets up necessary task and runs them on given {@code taskExecutor}.
 * After submitting all tasks, waits until validation with replica completes.
 */
public void run() {
    List<InetAddress> allEndpoints = new ArrayList<>(session.endpoints);
    allEndpoints.add(FBUtilities.getBroadcastAddress());

    ListenableFuture<List<TreeResponse>> validations;
    // Create a snapshot at all nodes unless we're using pure parallel repairs
    if (parallelismDegree != RepairParallelism.PARALLEL) {
        // Request snapshot to all replica
        List<ListenableFuture<InetAddress>> snapshotTasks = new ArrayList<>(allEndpoints.size());
        for (InetAddress endpoint : allEndpoints) {
            SnapshotTask snapshotTask = new SnapshotTask(desc, endpoint);
            snapshotTasks.add(snapshotTask);
            taskExecutor.execute(snapshotTask);
        }
        // When all snapshot complete, send validation requests
        ListenableFuture<List<InetAddress>> allSnapshotTasks = Futures.allAsList(snapshotTasks);
        validations = Futures.transform(allSnapshotTasks,
                new AsyncFunction<List<InetAddress>, List<TreeResponse>>() {
                    public ListenableFuture<List<TreeResponse>> apply(List<InetAddress> endpoints)
                            throws Exception {
                        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)",
                                desc.sessionId, desc.columnFamily, endpoints));
                        if (parallelismDegree == RepairParallelism.SEQUENTIAL)
                            return sendSequentialValidationRequest(endpoints);
                        else
                            return sendDCAwareValidationRequest(endpoints);
                    }
                }, taskExecutor);
    } else {
        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)", desc.sessionId,
                desc.columnFamily, allEndpoints));
        // If not sequential, just send validation request to all replica
        validations = sendValidationRequest(allEndpoints);
    }

    // When all validations complete, submit sync tasks
    ListenableFuture<List<SyncStat>> syncResults = Futures.transform(validations,
            new AsyncFunction<List<TreeResponse>, List<SyncStat>>() {
                public ListenableFuture<List<SyncStat>> apply(List<TreeResponse> trees) throws Exception {
                    InetAddress local = FBUtilities.getLocalAddress();

                    List<SyncTask> syncTasks = new ArrayList<>();
                    // We need to difference all trees one against another
                    for (int i = 0; i < trees.size() - 1; ++i) {
                        TreeResponse r1 = trees.get(i);
                        for (int j = i + 1; j < trees.size(); ++j) {
                            TreeResponse r2 = trees.get(j);
                            SyncTask task;
                            if (r1.endpoint.equals(local) || r2.endpoint.equals(local)) {
                                task = new LocalSyncTask(desc, r1, r2, repairedAt);
                            } else {
                                task = new RemoteSyncTask(desc, r1, r2);
                                // RemoteSyncTask expects SyncComplete message sent back.
                                // Register task to RepairSession to receive response.
                                session.waitForSync(Pair.create(desc, new NodePair(r1.endpoint, r2.endpoint)),
                                        (RemoteSyncTask) task);
                            }
                            syncTasks.add(task);
                            taskExecutor.submit(task);
                        }
                    }
                    return Futures.allAsList(syncTasks);
                }
            }, taskExecutor);

    // When all sync complete, set the final result
    Futures.addCallback(syncResults, new FutureCallback<List<SyncStat>>() {
        public void onSuccess(List<SyncStat> stats) {
            logger.info(String.format("[repair #%s] %s is fully synced", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.successfulRepairJob(session.getId(), desc.keyspace, desc.columnFamily);
            set(new RepairResult(desc, stats));
        }

        /**
         * Snapshot, validation and sync failures are all handled here
         */
        public void onFailure(Throwable t) {
            logger.warn(String.format("[repair #%s] %s sync failed", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.failedRepairJob(session.getId(), desc.keyspace, desc.columnFamily, t);
            setException(t);
        }
    }, taskExecutor);

    // Wait for validation to complete
    Futures.getUnchecked(validations);
}

From source file:org.opendaylight.controller.sample.kitchen.impl.KitchenServiceImpl.java

@Override
public Future<RpcResult<Void>> makeBreakfast(EggsType eggsType, Class<? extends ToastType> toastType,
        int toastDoneness) {

    // Call makeToast and use JdkFutureAdapters to convert the Future to a ListenableFuture,
    // The OpendaylightToaster impl already returns a ListenableFuture so the conversion is
    // actually a no-op.

    ListenableFuture<RpcResult<Void>> makeToastFuture = JdkFutureAdapters
            .listenInPoolThread(makeToast(toastType, toastDoneness), executor);

    ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);

    // Combine the 2 ListenableFutures into 1 containing a list of RpcResults.

    ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures
            .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));

    // Then transform the RpcResults into 1.

    return Futures.transform(combinedFutures, new AsyncFunction<List<RpcResult<Void>>, RpcResult<Void>>() {
        @Override//w  w  w .  j a v  a  2s .  c o m
        public ListenableFuture<RpcResult<Void>> apply(List<RpcResult<Void>> results) throws Exception {
            boolean atLeastOneSucceeded = false;
            Builder<RpcError> errorList = ImmutableList.builder();
            for (RpcResult<Void> result : results) {
                if (result.isSuccessful()) {
                    atLeastOneSucceeded = true;
                }

                if (result.getErrors() != null) {
                    errorList.addAll(result.getErrors());
                }
            }

            return Futures.immediateFuture(RpcResultBuilder.<Void>status(atLeastOneSucceeded)
                    .withRpcErrors(errorList.build()).build());
        }
    });
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * This takes two futures of type {@link A} and {@link B} and works like
 * a valve on {@link A}, with validation executed on {@link B}.
 *
 * Returns a future with the result of {@link A} that will wait for a
 * condition on {@link B} to be validated first. Both futures can run in
 * parallel. If the condition fails validation, the {@link A} future will
 * be cancelled by a call to {@link ListenableFuture#cancel(boolean)} with
 * {@code false}.//from  w ww .j av  a  2s.c  om
 *
 * This is useful for when you want to optimistically run a time consuming
 * path while validating if it should be computed or not by a parallel
 * async computation.
 *
 * @param conditionValue  The future computing the value for validation.
 * @param future          The actual value future.
 * @param validator       A validator for the condition.
 *
 * @return a new {@link ListenableFuture} eventually either containing
 * {@param future} or any exception thrown by {@param validator}.
 */
public static <A, B> ListenableFuture<A> fastFail(final ListenableFuture<B> conditionValue,
        final ListenableFuture<A> future, final Validator<B> validator) {
    return Futures.transform(conditionValue, new AsyncFunction<B, A>() {
        @Override
        public ListenableFuture<A> apply(B value) throws Exception {
            try {
                validator.validate(value);
                return future;

            } catch (Exception e) {
                future.cancel(false);
                throw e;
            }
        }
    });
}

From source file:com.continuuity.weave.internal.AbstractServiceController.java

@Override
public ListenableFuture<State> stop() {
    State oldState = state.getAndSet(State.STOPPING);
    if (oldState == null || oldState == State.STARTING || oldState == State.RUNNING) {
        return Futures.transform(ZKMessages.sendMessage(zkClient, getZKPath("messages/msg"),
                SystemMessages.stopApplication(), State.TERMINATED), new AsyncFunction<State, State>() {
                    @Override/*  w w w .  j a v  a2s. c  o  m*/
                    public ListenableFuture<State> apply(State input) throws Exception {
                        // Wait for the instance ephemeral node goes away
                        return Futures.transform(ZKOperations.watchDeleted(zkClient, "/instances/" + runId),
                                new Function<String, State>() {
                                    @Override
                                    public State apply(String input) {
                                        LOG.info("Remote service stopped: " + runId);
                                        state.set(State.TERMINATED);
                                        fireStateChange(new StateNode(State.TERMINATED, null));
                                        return State.TERMINATED;
                                    }
                                });
                    }
                });
    }
    state.set(oldState);
    return Futures.immediateFuture(getState());
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<T> update(T entity) {
    ListenableFuture<ResultSet> future = submitUpdate(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, T>() {
        @Override/*from   www  .j  a  v a2  s  .  c  o  m*/
        public ListenableFuture<T> apply(ResultSet result) {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            return Futures.immediateFailedFuture(new ItemNotFoundException(entity.toString()));
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java

@Override
public Future<RpcResult<Void>> unregisterEndpoint(UnregisterEndpointInput input) {

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    if (input == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("Endpoint can not be empty!"));
    }//  ww  w  .j  a v  a 2s.com
    final List<Uuid> toBeDeletedList = input.getIds();

    if (toBeDeletedList == null || toBeDeletedList.isEmpty()) {
        return Futures.immediateFuture(result);
    }

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    for (Uuid ep : toBeDeletedList) {
        InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class,
                new EndpointKey(ep));
        trans.delete(LogicalDatastoreType.OPERATIONAL, eppath);
    }
    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            return Futures.immediateFuture(result);
        }
    }, executor);
}

From source file:com.continuuity.weave.internal.WeaveContainerMain.java

private static Service wrapService(final ZKClientService zkClientService, final Service containerService) {
    return new Service() {

        @Override//  w  ww .  j a va 2s . c om
        public ListenableFuture<State> start() {
            return Futures.transform(Services.chainStart(zkClientService, containerService),
                    new AsyncFunction<List<ListenableFuture<State>>, State>() {
                        @Override
                        public ListenableFuture<State> apply(List<ListenableFuture<State>> input)
                                throws Exception {
                            return input.get(1);
                        }
                    });
        }

        @Override
        public State startAndWait() {
            return Futures.getUnchecked(start());
        }

        @Override
        public boolean isRunning() {
            return containerService.isRunning();
        }

        @Override
        public State state() {
            return containerService.state();
        }

        @Override
        public ListenableFuture<State> stop() {
            return Futures.transform(Services.chainStop(containerService, zkClientService),
                    new AsyncFunction<List<ListenableFuture<State>>, State>() {
                        @Override
                        public ListenableFuture<State> apply(List<ListenableFuture<State>> input)
                                throws Exception {
                            return input.get(0);
                        }
                    });
        }

        @Override
        public State stopAndWait() {
            return Futures.getUnchecked(stop());
        }

        @Override
        public void addListener(Listener listener, Executor executor) {
            containerService.addListener(listener, executor);
        }
    };
}

From source file:io.vitess.client.VTGateConnection.java

/**
 * This method calls the VTGate to execute the query.
 *
 * @param ctx       Context on user and execution deadline if any.
 * @param query     Sql Query to be executed.
 * @param bindVars  Parameters to bind with sql.
 * @param vtSession Session to be used with the call.
 * @return SQL Future Cursor//w  ww .  ja v  a 2  s .co  m
 * @throws SQLException If anything fails on query execution.
 */
public SQLFuture<Cursor> execute(Context ctx, String query, @Nullable Map<String, ?> bindVars,
        final VTSession vtSession) throws SQLException {
    synchronized (this) {
        vtSession.checkCallIsAllowed("execute");
        ExecuteRequest.Builder requestBuilder = ExecuteRequest.newBuilder()
                .setQuery(Proto.bindQuery(checkNotNull(query), bindVars)).setSession(vtSession.getSession());

        if (ctx.getCallerId() != null) {
            requestBuilder.setCallerId(ctx.getCallerId());
        }

        SQLFuture<Cursor> call = new SQLFuture<>(transformAsync(client.execute(ctx, requestBuilder.build()),
                new AsyncFunction<ExecuteResponse, Cursor>() {
                    @Override
                    public ListenableFuture<Cursor> apply(ExecuteResponse response) throws Exception {
                        vtSession.setSession(response.getSession());
                        Proto.checkError(response.getError());
                        return Futures.<Cursor>immediateFuture(new SimpleCursor(response.getResult()));
                    }
                }, directExecutor()));
        vtSession.setLastCall(call);
        return call;
    }
}