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

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

Introduction

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

Prototype

FutureCallback

Source Link

Usage

From source file:io.bitsquare.trade.protocol.trade.tasks.buyer.SignAndPublishDepositTx.java

@Override
protected void run() {
    try {/*w  ww.  ja v  a 2 s . c o m*/
        runInterceptHook();
        Coin inputAmount = trade.getSecurityDeposit().add(FeePolicy.TX_FEE);

        processModel.getTradeWalletService().signAndPublishDepositTx(
                processModel.tradingPeer.getPreparedDepositTx(), processModel.getConnectedOutputsForAllInputs(),
                processModel.tradingPeer.getConnectedOutputsForAllInputs(), processModel.getOutputs(),
                inputAmount, processModel.getTradeWalletPubKey(),
                processModel.tradingPeer.getTradeWalletPubKey(), processModel.getArbitratorPubKey(),
                new FutureCallback<Transaction>() {
                    @Override
                    public void onSuccess(Transaction transaction) {
                        log.trace("takerSignAndPublishTx succeeded " + transaction);

                        trade.setDepositTx(transaction);

                        trade.setTradeState(TradeState.BuyerState.DEPOSIT_PUBLISHED);
                        trade.setTakeOfferDate(new Date());

                        complete();
                    }

                    @Override
                    public void onFailure(@NotNull Throwable t) {
                        failed(t);
                    }
                });
    } catch (Throwable t) {
        failed(t);
    }
}

From source file:io.crate.jobs.ProjectorChainContext.java

public ProjectorChainContext(int id, String name, UUID jobId, ProjectorFactory projectorFactory,
        List<Projection> projections, RowReceiver rowReceiver, RamAccountingContext ramAccountingContext) {
    super(id, LOGGER);
    this.name = name;
    ListenableRowReceiver listenableRowReceiver = RowReceivers.listenableRowReceiver(rowReceiver);
    Futures.addCallback(listenableRowReceiver.finishFuture(), new FutureCallback<Void>() {
        @Override/*from   w  w w .j a v  a 2 s.com*/
        public void onSuccess(@Nullable Void result) {
            ProjectorChainContext.this.close(null);
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            ProjectorChainContext.this.close(t);
        }
    });
    FlatProjectorChain projectorChain = FlatProjectorChain.withAttachedDownstream(projectorFactory,
            ramAccountingContext, projections, listenableRowReceiver, jobId);
    this.rowReceiver = projectorChain.firstProjector();
}

From source file:com.facebook.presto.util.MoreFutures.java

public static <T> ListenableFuture<T> addTimeout(final ListenableFuture<T> future,
        final Callable<T> timeoutTask, Duration timeout, ScheduledExecutorService executorService) {
    // if the future is already complete, just return it
    if (future.isDone()) {
        return future;
    }//from  w  ww  . j  a va 2s  .c om

    // wrap the future, so we can set the result directly
    final SettableFuture<T> settableFuture = SettableFuture.create();

    // schedule a task to complete the future when the time expires
    final ScheduledFuture<?> timeoutTaskFuture = executorService.schedule(
            new TimeoutFutureTask<>(settableFuture, timeoutTask, future), timeout.toMillis(),
            TimeUnit.MILLISECONDS);

    // add a listener to the core future, which simply updates the settable future
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(@Nullable T result) {
            settableFuture.set(result);
            timeoutTaskFuture.cancel(true);
        }

        @Override
        public void onFailure(Throwable t) {
            settableFuture.setException(t);
            timeoutTaskFuture.cancel(true);
        }
    }, executorService);

    return settableFuture;
}

From source file:com.google.devtools.build.lib.concurrent.MoreFutures.java

/**
 * Creates a new {@code ListenableFuture} whose value is a list containing the
 * values of all its input futures, if all succeed. If any input fails, the
 * returned future fails. If any of the futures fails, it cancels all the other futures.
 *
 * <p> This method is similar to {@code Futures.allAsList} but additionally it cancels all the
 * futures in case any of them fails./*from  w w  w.  j a v  a 2 s  .  c  o m*/
 */
public static <V> ListenableFuture<List<V>> allAsListOrCancelAll(
        final Iterable<? extends ListenableFuture<? extends V>> futures) {
    ListenableFuture<List<V>> combinedFuture = Futures.allAsList(futures);
    Futures.addCallback(combinedFuture, new FutureCallback<List<V>>() {
        @Override
        public void onSuccess(@Nullable List<V> vs) {
        }

        /**
         * In case of a failure of any of the futures (that gets propagated to combinedFuture) we
         * cancel all the futures in the list.
         */
        @Override
        public void onFailure(Throwable ignore) {
            for (ListenableFuture<? extends V> future : futures) {
                future.cancel(true);
            }
        }
    });
    return combinedFuture;
}

From source file:org.apache.flink.streaming.connectors.cassandra.CassandraSinkBase.java

@Override
public void open(Configuration configuration) {
    this.callback = new FutureCallback<V>() {
        @Override//from www.  j  a v  a 2  s. co  m
        public void onSuccess(V ignored) {
        }

        @Override
        public void onFailure(Throwable t) {
            exception = t;
            LOG.error("Error while sending value.", t);
        }
    };
    this.cluster = builder.getCluster();
    this.session = cluster.connect();
}

From source file:org.jclouds.compute.extensions.internal.DelegatingImageExtension.java

public ListenableFuture<Image> createImage(ImageTemplate template) {
    ListenableFuture<Image> future = delegate.createImage(template);
    Futures.addCallback(future, new FutureCallback<Image>() {
        @Override//  www.ja  va 2  s  . com
        public void onSuccess(Image result) {
            imageCache.registerImage(result);
        }

        @Override
        public void onFailure(Throwable t) {

        }
    });
    return future;
}

From source file:io.crate.executor.transport.task.UpdateTask.java

@Override
public void start() {
    if (subTasks.size() == 0) {
        result.set(RowCountResult.EMPTY_RESULT);
        return;/*from  ww w  . ja  v a 2s  .  c  o m*/
    }
    final List<ListenableFuture<TaskResult>> subTasksResult = transportExecutor.execute(subTasks);
    Futures.addCallback(Futures.allAsList(subTasksResult), new FutureCallback<List<TaskResult>>() {
        @Override
        public void onSuccess(@Nullable List<TaskResult> results) {
            if (results == null) {
                result.setException(new NullPointerException());
                return;
            }
            assert results.size() == 1 : "Last sub-task is expected to have 1 result only";
            result.set(new RowCountResult(((Number) results.get(0).rows()[0][0]).longValue()));
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            if (t == null) {
                t = new NullPointerException();
            }
            result.setException(t);
        }
    });
}

From source file:com.microsoft.office365.starter.FilesFolders.O365FileListModel.java

public void postUpdatedFileContents(final O365APIsStart_Application application, final Activity currentActivity,
        SharePointClient fileClient, final String updatedContents) {
    ListenableFuture<Void> future = fileClient.getfiles().getById(application.getDisplayedFile().getId())
            .asFile().putContent(updatedContents.getBytes());

    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override//from w w  w.ja v a2s  . c o  m
        public void onFailure(Throwable t) {
            Log.e("Asset", t.getMessage());
            // Notify caller that the Event update operation failed
            OperationResult opResult = new OperationResult("Post updated file contents",
                    "failed: " + APIErrorMessageHelper.getErrorMessage(t.getMessage()), "");
            mEventOperationCompleteListener.onOperationComplete(opResult);
        }

        @Override
        public void onSuccess(Void v) {
            // Update file contents in model
            O365FileModel fileItem = mApplication.getDisplayedFile();
            fileItem.setContents(currentActivity, updatedContents);
            // Notify caller that the Event update operation is complete and
            // succeeded
            OperationResult opResult = new OperationResult("Post updated file contents",
                    "Posted updated file contents", "FileContentsUpdate");
            mEventOperationCompleteListener.onOperationComplete(opResult);
        }
    });

}

From source file:org.opendaylight.ocpplugin.impl.services.SalFaultMgmtServiceImpl.java

@Override
public Future<RpcResult<GetFaultOutput>> getFault(final GetFaultInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetFaultOutput>> future = getFault
            .handleServiceCall(input);//from   w  w w .  j av a  2s.  c om
    final SettableFuture<RpcResult<GetFaultOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetFaultOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetFaultOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetFaultOutput output = result
                            .getResult();
                    GetFaultOutputBuilder builder = new GetFaultOutputBuilder();
                    builder.setObj(output.getObj());
                    builder.setResult(output.getResult());
                    RpcResultBuilder<GetFaultOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

                @Override
                public void onFailure(final Throwable t) {
                    RpcResultBuilder<GetFaultOutput> rpcResultBuilder = RpcResultBuilder.failed();
                    finalFuture.set(rpcResultBuilder.build());
                }
            });

    return finalFuture;
}

From source file:org.opendaylight.controller.config.yang.netconf.mdsal.monitoring.MonitoringToMdsalWriter.java

@Override
public void close() {
    final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
    tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(NetconfState.class));
    final CheckedFuture<Void, TransactionCommitFailedException> submit = tx.submit();

    Futures.addCallback(submit, new FutureCallback<Void>() {
        @Override/*  www .j a  v  a  2  s  .  c om*/
        public void onSuccess(final Void aVoid) {
            LOG.debug("Netconf state cleared successfully");
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.warn("Unable to clear netconf state", throwable);
        }
    });
}