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:ubic.gemma.job.executor.common.TaskPostProcessingImpl.java

@Override
public void addEmailNotification(ListenableFuture<TaskResult> future, EmailNotificationContext context) {
    FutureCallback<TaskResult> emailNotificationCallback = createEmailNotificationFutureCallback(context);
    // This will be called when future with our running task is done.
    Futures.addCallback(future, emailNotificationCallback);
}

From source file:org.opendaylight.vtn.manager.it.ofmock.impl.DeleteDataTask.java

/**
 * Construct a new instance./* w w  w.  j a va2  s .  c om*/
 *
 * @param broker  The data broker service.
 * @param path    The path to the target data.
 */
public DeleteDataTask(DataBroker broker, InstanceIdentifier<T> path) {
    super(broker);
    targetPath = path;
    Futures.addCallback(getFuture(), this);
}

From source file:ubic.gemma.core.job.executor.common.TaskPostProcessingImpl.java

@Override
public void addEmailNotification(ListenableFuture<TaskResult> future, EmailNotificationContext context) {
    FutureCallback<TaskResult> emailNotificationCallback = this.createEmailNotificationFutureCallback(context);
    // This will be called when future with our running task is done.
    Futures.addCallback(future, emailNotificationCallback);
}

From source file:org.opendaylight.genius.mdsalutil.MDSALDataStoreUtils.java

public static <T extends DataObject> void asyncRemove(final DataBroker broker,
        final LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, FutureCallback<Void> callback) {
    WriteTransaction tx = broker.newWriteOnlyTransaction();
    tx.delete(datastoreType, path);/*www. ja va2 s  .c o  m*/
    Futures.addCallback(tx.submit(), callback);
}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

/**
 * Watch for data changes of the given path. The callback will be triggered whenever changes has been
 * detected. Note that the callback won't see every single changes, as that's not the guarantee of ZooKeeper.
 * If the node doesn't exists, it will watch for its creation then starts watching for data changes.
 * When the node is deleted afterwards,//ww  w. ja  v  a  2 s  .  c o  m
 *
 * @param zkClient The {@link ZKClient} for the operation
 * @param path Path to watch
 * @param callback Callback to be invoked when data changes is detected.
 * @return A {@link Cancellable} to cancel the watch.
 */
public static Cancellable watchData(final ZKClient zkClient, final String path, final DataCallback callback) {
    final AtomicBoolean cancelled = new AtomicBoolean(false);
    Futures.addCallback(zkClient.getData(path, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (!cancelled.get()) {
                watchData(zkClient, path, callback);
            }
        }
    }), new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            if (!cancelled.get()) {
                callback.updated(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException && ((KeeperException) t).code() == KeeperException.Code.NONODE) {
                final SettableFuture<String> existCompletion = SettableFuture.create();
                existCompletion.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!cancelled.get()) {
                                watchData(zkClient, existCompletion.get(), callback);
                            }
                        } catch (Exception e) {
                            LOG.error("Failed to watch data for path " + path, e);
                        }
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
                watchExists(zkClient, path, existCompletion);
                return;
            }
            LOG.error("Failed to watch data for path " + path + " " + t, t);
        }
    });
    return new Cancellable() {
        @Override
        public void cancel() {
            cancelled.set(true);
        }
    };
}

From source file:com.vmware.photon.controller.common.zookeeper.ServiceNodeUtils.java

private static void handleLeaseExpiration(ServiceNode.Lease lease, final ServiceNode serviceNode,
        final long retryIntervalMsec, final ServiceNodeEventHandler serviceNodeEventHandler) {
    Futures.addCallback(lease.getExpirationFuture(), new FutureCallback<Void>() {
        @Override/*from w  ww.  j  a v  a2s.c om*/
        public void onSuccess(Void result) {
            rejoin();
        }

        @Override
        public void onFailure(Throwable t) {
            // Could happen if the expiration future gets cancelled: in that case
            // we can't reliably detect when we need to expire the connection anymore,
            // so it probably makes sense to leave and attempt to re-join immediately.
            logger.error("The expiration future has failed", t);
            rejoin();
        }

        public void rejoin() {
            if (serviceNodeEventHandler != null) {
                serviceNodeEventHandler.onLeave();
            }
            joinService(serviceNode, retryIntervalMsec, serviceNodeEventHandler);
        }
    });
}

From source file:crud.http.ListenerInvokingAnswer.java

@Override
public Future<ClientResponse> answer(final InvocationOnMock invocation) {
    @SuppressWarnings("unchecked")
    final ITypeListener<ClientResponse> listener = (ITypeListener<ClientResponse>) invocation.getArguments()[0];

    Futures.addCallback(this.mockFuture, new FutureCallback<ClientResponse>() {
        @Override//from  w  ww. ja v a2  s.  c  o  m
        public void onSuccess(final ClientResponse result) {
            try {
                listener.onComplete(ListenerInvokingAnswer.this.mockFuture);
            } catch (final InterruptedException ex) {
                Throwables.propagate(ex);
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            try {
                listener.onComplete(ListenerInvokingAnswer.this.mockFuture);
            } catch (final InterruptedException ex) {
                Throwables.propagate(ex);
            }
        }
    });
    return this.mockFuture;
}

From source file:io.v.v23.syncbase.Batch.java

@CheckReturnValue
private static ListenableFuture<Boolean> tryBatch(final VContext ctx, final Database db,
        final BatchOptions opts, final BatchOperation op) {
    final SettableFuture<Boolean> ret = SettableFuture.create();
    Futures.addCallback(db.beginBatch(ctx, opts), new FutureCallback<BatchDatabase>() {
        @Override/*  ww w  .j a  v  a  2 s .  c o m*/
        public void onFailure(Throwable t) {
            ret.setException(t);
        }

        @Override
        public void onSuccess(final BatchDatabase batch) {
            Futures.addCallback(op.run(batch), new FutureCallback<Void>() {
                @Override
                public void onFailure(final Throwable t) {
                    Futures.addCallback(batch.abort(ctx), new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(Void result) {
                            ret.setException(t);
                        }

                        @Override
                        public void onFailure(Throwable newT) {
                            ret.setException(t);
                        }
                    });
                }

                @Override
                public void onSuccess(Void result) {
                    Futures.addCallback(opts.getReadOnly() ? batch.abort(ctx) : batch.commit(ctx),
                            new FutureCallback<Void>() {
                                @Override
                                public void onSuccess(Void result) {
                                    ret.set(true); // success
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    if (t instanceof ConcurrentBatchException) {
                                        // retry
                                        ret.set(false);
                                    } else {
                                        ret.setException(t);
                                    }
                                }
                            });
                }
            });
        }
    });
    return ret;
}

From source file:org.opendaylight.controller.mdsal.DataStore.java

private static void execPut(WriteTransaction tx, FutureCallback<Void> callback) {
    Futures.addCallback(tx.submit(), callback);
}

From source file:org.opendaylight.controller.cluster.datastore.DebugThreePhaseCommitCohort.java

private <V> ListenableFuture<V> addFutureCallback(ListenableFuture<V> future) {
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override/*  www . j av  a 2s  .c  o m*/
        public void onSuccess(V result) {
            // no-op
        }

        @Override
        public void onFailure(Throwable t) {
            log.warn("Transaction {} failed with error \"{}\" - was allocated in the following context",
                    transactionId, t, debugContext);
        }
    });

    return future;
}