Example usage for com.google.common.util.concurrent Futures addCallback

List of usage examples for com.google.common.util.concurrent Futures addCallback

Introduction

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

Prototype

public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) 

Source Link

Document

Registers separate success and failure callbacks to be run when the Future 's computation is java.util.concurrent.Future#isDone() complete or, if the computation is already complete, immediately.

Usage

From source file:com.salesforce.grpc.contrib.spring.GuavaLFReturnValueHandler.java

@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;/*from  w ww. ja  v a 2s.  c o m*/
    }

    final DeferredResult<Object> deferredResult = new DeferredResult<>();
    @SuppressWarnings("unchecked")
    ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue;
    Futures.addCallback(futureValue, new FutureCallback<Object>() {
        @Override
        public void onSuccess(@Nullable Object result) {
            deferredResult.setResult(result);
        }

        @Override
        public void onFailure(Throwable ex) {
            deferredResult.setErrorResult(ex);
        }
    });

    startDeferredResultProcessing(mavContainer, webRequest, deferredResult);
}

From source file:com.continuuity.weave.internal.zookeeper.RewatchOnExpireZKClient.java

@Override
public OperationFuture<NodeData> getData(String path, Watcher watcher) {
    final RewatchOnExpireWatcher wrappedWatcher = new RewatchOnExpireWatcher(this, ActionType.DATA, path,
            watcher);/*from  ww w. j a  v  a  2  s.  co m*/
    OperationFuture<NodeData> result = super.getData(path, wrappedWatcher);
    Futures.addCallback(result, new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            wrappedWatcher.setLastResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op
        }
    });
    return result;

}

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

public void run() throws Exception {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }//from  w ww  . ja  v  a  2  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 ListenableFuture<GenericJson> futureReqBlockChain = pool.submit(new Callable<GenericJson>() {
        public GenericJson call() throws Exception {
            GenericJson json = requestBlockChain.execute().parseAs(GenericJson.class);
            return json;
        }
    });

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

        public void onSuccess(GenericJson result) {
            GenericJson json = result;
            System.out.println(json);
            Map ntdJson = (Map) json.get("USD");
            System.out.println(ntdJson.put("buy", 119.001));
            json.put("NTD", ntdJson);
            System.out.println(json);
        }

        public void onFailure(Throwable t) {
            // TODO Auto-generated method stub

        }
    });

    final HttpRequest requestYahoo = requestFactory.buildGetRequest(urlYahooTwd);
    final ListenableFuture<GenericJson> futureYahoo = pool.submit(new Callable<GenericJson>() {
        public GenericJson call() throws Exception {
            GenericJson json = requestYahoo.execute().parseAs(GenericJson.class);
            return json;
        }
    });

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

        public void onSuccess(GenericJson result) {
            GenericJson jsonYahoo = result;
            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(twd);
        }

        public void onFailure(Throwable t) {
            // TODO Auto-generated method stub

        }
    });

}

From source file:org.hawkular.metrics.api.jaxrs.TenantsHandler.java

@POST
@ApiOperation(value = "Create a new tenant. ", notes = "Clients are not required to create explicitly create a "
        + "tenant before starting to store metric data. It is recommended to do so however to ensure that there "
        + "are no tenant id naming collisions and to provide default data retention settings. ")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tenant has been succesfully created."),
        @ApiResponse(code = 400, message = "Retention properties are invalid. ", response = Error.class),
        @ApiResponse(code = 409, message = "Given tenant id has already been created.", response = Error.class),
        @ApiResponse(code = 500, message = "An unexpected error occured while trying to create a tenant.", response = Error.class) })
public void createTenant(@Suspended AsyncResponse asyncResponse, @ApiParam(required = true) Tenant params) {
    ListenableFuture<Void> insertFuture = metricsService.createTenant(params);
    Futures.addCallback(insertFuture, new FutureCallback<Void>() {
        @Override//from w  w  w. j a v a 2 s.  c  om
        public void onSuccess(Void result) {
            asyncResponse.resume(Response.ok().type(APPLICATION_JSON_TYPE).build());
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof TenantAlreadyExistsException) {
                TenantAlreadyExistsException exception = (TenantAlreadyExistsException) t;
                Error errors = new Error("A tenant with id [" + exception.getTenantId() + "] already exists");
                asyncResponse.resume(
                        Response.status(Status.CONFLICT).entity(errors).type(APPLICATION_JSON_TYPE).build());
                return;
            }
            Error errors = new Error("Failed to create tenant due to an " + "unexpected error: "
                    + Throwables.getRootCause(t).getMessage());
            asyncResponse.resume(Response.status(Status.INTERNAL_SERVER_ERROR).entity(errors)
                    .type(APPLICATION_JSON_TYPE).build());
        }
    });
}

From source file:com.sk89q.worldedit.command.util.AsyncCommandHelper.java

public AsyncCommandHelper thenTellErrorsOnly(String failure) {
    // Send a response message
    Futures.addCallback(future, new MessageFutureCallback.Builder(sender).exceptionConverter(exceptionConverter)
            .onFailure(format(failure)).build());
    return this;
}

From source file:org.apache.twill.internal.zookeeper.RewatchOnExpireWatcher.java

private void exists() {
    Futures.addCallback(client.exists(path, this), new FutureCallback<Stat>() {
        @Override/*from  w  ww  .  j a  v  a 2s . c  om*/
        public void onSuccess(Stat stat) {
            // Since we know all callbacks and watcher are triggered from single event thread, there is no race condition.
            Object oldResult = lastResult.getReference();
            lastResult.compareAndSet(oldResult, null, true, false);

            if (stat != oldResult && (stat == null || !stat.equals(oldResult))) {
                if (stat == null) {
                    // previous stat is not null, means node deleted
                    process(new WatchedEvent(Event.EventType.NodeDeleted, Event.KeeperState.SyncConnected,
                            path));
                } else if (oldResult == null) {
                    // previous stat is null, means node created
                    process(new WatchedEvent(Event.EventType.NodeCreated, Event.KeeperState.SyncConnected,
                            path));
                } else {
                    // Otherwise, something changed on the node
                    process(new WatchedEvent(Event.EventType.NodeDataChanged, Event.KeeperState.SyncConnected,
                            path));
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (RetryUtils.canRetry(t)) {
                exists();
            } else {
                lastResult.set(null, false);
                LOG.error("Fail to re-set watch on exists for path " + path, t);
            }
        }
    });
}

From source file:de.schildbach.wallet.util.ChainServiceTransactionBroadcaster.java

private synchronized void doBroadcast(final Transaction tx) {
    log.info("Doing channel close broadcast for transaction with hash " + tx.getHashAsString());
    final ListenableFuture<Transaction> broadcastFuture;
    if (service != null)
        broadcastFuture = service.broadcastTransaction(tx);
    else//w w  w  . j  av a2 s.com
        broadcastFuture = null;
    if (broadcastFuture != null) {
        setBroadcastFutures.add(broadcastFuture);
        Futures.addCallback(broadcastFuture, new FutureCallback<Transaction>() {
            @Override
            public void onSuccess(Transaction result) {
                log.info("Channel close transaction broadcast successfully: " + tx.getHashAsString());
                setBroadcastFutures.remove(broadcastFuture);
                checkAllTransactionsBroadcasted();
            }

            @Override
            public void onFailure(Throwable t) {
                log.error("Channel close transaction failed to broadcast: " + tx.getHashAsString());
            }
        });
    } else
        log.info("Blockchain service is not connected, skipping channel close broadcast of transaction "
                + tx.getHashAsString());

    try {
        application.getWallet().receivePending(tx, new LinkedList<Transaction>());
    } catch (VerificationException e) {
        log.error("Channel close broadcast failed to commit to wallet.");
    }
}

From source file:io.v.moments.v23.impl.V23ManagerImpl.java

@Override
public synchronized void init(Activity activity, FutureCallback<Blessings> blessingCallback) {
    Log.d(TAG, "init");
    if (mAndroidCtx != null) {
        if (mAndroidCtx == activity.getApplicationContext()) {
            Log.d(TAG, "Initialization already started.");
            return;
        } else {/*from www .jav  a2 s. co m*/
            Log.d(TAG, "Initialization with new context.");
            shutdown();
        }
    }
    mAndroidCtx = activity.getApplicationContext();
    // Must call V.init before attempting to load blessings, so that proper
    // code is loaded.
    mV23Ctx = V.init(mAndroidCtx);
    Log.d(TAG, "Attempting to get blessings.");
    ListenableFuture<Blessings> f = BlessingsManager.getBlessings(mV23Ctx, activity, BLESSINGS_KEY, true);
    Futures.addCallback(f, blessingCallback);
    try {
        mDiscovery = V.newDiscovery(mV23Ctx);
    } catch (VException e) {
        Log.d(TAG, "Unable to get discovery object.", e);
    }
}

From source file:org.opendaylight.toaster.impl.OpendaylightToaster.java

private void setToasterStatusUp(final Function<Boolean, Void> resultCallback) {

    WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
    tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Up));

    ListenableFuture<RpcResult<TransactionStatus>> commitFuture = tx.commit();

    Futures.addCallback(commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
        @Override//  w  w  w.j  a v a2s .  c  o  m
        public void onSuccess(RpcResult<TransactionStatus> result) {
            if (result.getResult() != TransactionStatus.COMMITED) {
                LOG.error("Failed to update toaster status: " + result.getErrors());
            }

            notifyCallback(result.getResult() == TransactionStatus.COMMITED);
        }

        @Override
        public void onFailure(Throwable t) {
            // We shouldn't get an OptimisticLockFailedException (or any ex) as no
            // other component should be updating the operational state.
            LOG.error("Failed to update toaster status", t);

            notifyCallback(false);
        }

        void notifyCallback(boolean result) {
            if (resultCallback != null) {
                resultCallback.apply(result);
            }
        }
    });
}

From source file:com.github.nethad.clustermeister.example.async.AsyncTasks.java

private void execute() {
    try {/* ww  w  . j  a va  2s  .c  om*/
        if (clustermeister == null) {
            clustermeister = ClustermeisterFactory.create();
        }
        Job<String> job = JobFactory.create("CM AsyncTasks", null);
        for (int i = 0; i < NUMBER_OF_TASKS; i++) {
            job.addTask(new ReturnNumberTaskWithSleep(i, 2000));
        }
        List<ListenableFuture<String>> resultFutures = clustermeister.executeJobAsyncTasks(job);
        FutureCallback<String> callback = new FutureCallback<String>() {
            public void onSuccess(String result) {
                logger.info("Got result {}", result);
                monitor.enter();
                try {
                    callbackCounter.incrementAndGet();
                } finally {
                    monitor.leave();
                }
            }

            public void onFailure(Throwable t) {
                logger.warn("Failure.", t);
                monitor.enter();
                try {
                    callbackCounter.incrementAndGet();
                } finally {
                    monitor.leave();
                }
            }
        };

        for (ListenableFuture<String> listenableFuture : resultFutures) {
            Futures.addCallback(listenableFuture, callback);
        }

        logger.info("Registered callback, waiting for it to be finished.");
        monitor.enter();
        try {
            monitor.waitFor(futureCallbackGuard);
            logger.info("Future callback done.");
        } finally {
            monitor.leave();
        }
    } catch (Exception ex) {
        logger.warn("Exception while executing example.", ex);
    } finally {
        if (clustermeister != null) {
            logger.info("Shutting down.");
            clustermeister.shutdown();
        }
    }
}