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

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

Introduction

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

Prototype

void onSuccess(@Nullable V result);

Source Link

Document

Invoked with the result of the Future computation when it is successful.

Usage

From source file:com.github.zhongl.api.Storage.java

private static void onSuccess(Collection<? extends FutureCallback<Void>> callbacks) {
    for (FutureCallback<Void> callback : callbacks)
        callback.onSuccess(null);
}

From source file:io.github.trulyfree.easyaspi.lib.util.Utils.java

/**
 * Generates an OnClickListener from a given FutureCallback.
 *
 * @param callback The callback to execute when the click event occurs.
 * @return listener The OnClickListener.
 *//*from   w  ww  .  j  a  v a2 s .  c  om*/
public static View.OnClickListener generateOnClickListener(final FutureCallback<View> callback) {
    return new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view instanceof Button) {
                System.out.println(((Button) view).getText() + " pressed");
            }
            try {
                callback.onSuccess(view);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                callback.onFailure(throwable);
            }
        }
    };
}

From source file:io.airlift.discovery.client.CachingServiceSelector.java

private static <V> ListenableFuture<V> chainedCallback(ListenableFuture<V> future,
        final FutureCallback<? super V> callback, Executor executor) {
    final SettableFuture<V> done = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override/*from  w w  w . j  av a2s.  c  om*/
        public void onSuccess(V result) {
            try {
                callback.onSuccess(result);
            } finally {
                done.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                callback.onFailure(t);
            } finally {
                done.setException(t);
            }
        }
    }, executor);
    return done;
}

From source file:com.vmware.photon.controller.common.dcp.TaskUtils.java

public static <T extends ServiceDocument> void checkProgress(final Service service, final String serviceLink,
        final Predicate<T> predicate, final Class<T> type, final int taskPollDelay,
        final FutureCallback<T> callback) {

    Operation.CompletionHandler completionHandler = new Operation.CompletionHandler() {
        @Override/* ww w . ja  va  2  s.  c  om*/
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                callback.onFailure(throwable);
                return;
            }
            T state = operation.getBody(type);

            if (predicate.apply(state)) {
                callback.onSuccess(state);
                return;
            }

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        checkProgress(service, serviceLink, predicate, type, taskPollDelay, callback);
                    } catch (Throwable t) {
                        callback.onFailure(t);
                    }
                }
            };
            service.getHost().schedule(runnable, taskPollDelay, TimeUnit.MILLISECONDS);
        }
    };

    Operation get = Operation.createGet(UriUtils.buildUri(service.getHost(), serviceLink))
            .setCompletion(completionHandler);
    service.sendRequest(get);
}

From source file:com.tinspx.util.concurrent.FutureUtils.java

/**
 * Returns a {@code FutureCallback} that forwards to {@code callback} but
 * suppresses and notifies {@code handler} of any uncaught
 * {@code Throwable}.//from www .ja  v  a 2 s . c o  m
 * 
 * @since 2.0
 */
public static <T> FutureCallback<T> notifyAndSuppress(final @NonNull FutureCallback<T> callback,
        final @NonNull Thread.UncaughtExceptionHandler handler) {
    return new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            try {
                callback.onSuccess(result);
            } catch (Throwable ex) {
                handler.uncaughtException(Thread.currentThread(), ex);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                callback.onFailure(t);
            } catch (Throwable ex) {
                handler.uncaughtException(Thread.currentThread(), ex);
            }
        }
    };
}

From source file:de.xaniox.heavyspleef.core.persistence.MoreFutures.java

/**
 * Add a callback to a {@link ListenableFuture}
 * to be run on the bukkit main thread/*  w  ww  .  jav  a  2 s.co  m*/
 * 
 * @param plugin The plugin registering the callback
 * @param future The {@link ListenableFuture} to add this callback
 * @param callback The callback to be called
 */
public static <T> void addBukkitSyncCallback(final Plugin plugin, ListenableFuture<T> future,
        final FutureCallback<T> callback) {
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onFailure(final Throwable cause) {
            Bukkit.getScheduler().runTask(plugin, new Runnable() {

                @Override
                public void run() {
                    callback.onFailure(cause);
                }
            });
        }

        @Override
        public void onSuccess(final T result) {
            Bukkit.getScheduler().runTask(plugin, new Runnable() {

                @Override
                public void run() {
                    callback.onSuccess(result);
                }
            });
        }
    });
}

From source file:com.vmware.photon.controller.deployer.helpers.xenon.MockHelper.java

@SuppressWarnings("unchecked")
public static Answer<FutureCallback<TransportZone>> mockGetTransportZone(String transportZoneId) {
    return (invocation) -> {
        TransportZone transportZone = new TransportZone();
        transportZone.setId(transportZoneId);

        FutureCallback<TransportZone> callback = (FutureCallback<TransportZone>) invocation.getArguments()[1];
        callback.onSuccess(transportZone);

        return null;
    };//from   w w w. j a v a  2s.  com
}

From source file:org.jenkinsci.plugins.workflow.support.concurrent.Futures.java

/**
 * Registers separate success and failure callbacks to be run when the {@code
 * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
 * complete} or, if the computation is already complete, immediately.
 *
 * <p>The callback is run in {@code executor}.
 * There is no guaranteed ordering of execution of callbacks, but any
 * callback added through this method is guaranteed to be called once the
 * computation is complete./*from  w w  w  .  java  2 s . com*/
 *
 * Example: <pre> {@code
 * ListenableFuture<QueryResult> future = ...;
 * Executor e = ...
 * addCallback(future, e,
 *     new FutureCallback<QueryResult> {
 *       public void onSuccess(QueryResult result) {
 *         storeInCache(result);
 *       }
 *       public void onFailure(Throwable t) {
 *         reportError(t);
 *       }
 *     });}</pre>
 *
 * When the callback is fast and lightweight consider {@linkplain
 * Futures#addCallback(ListenableFuture, FutureCallback) the other overload}
 * or explicit use of {@link MoreExecutors#sameThreadExecutor
 * sameThreadExecutor}. For heavier callbacks, this choice carries some
 * caveats: First, the thread that the callback runs in depends on whether
 * the input {@code Future} is done at the time {@code addCallback} is called
 * and on whether the input {@code Future} is ever cancelled. In particular,
 * {@code addCallback} may execute the callback in the thread that calls
 * {@code addCallback} or {@code Future.cancel}. Second, callbacks may run in
 * an internal thread of the system responsible for the input {@code Future},
 * such as an RPC network thread. Finally, during the execution of a {@code
 * sameThreadExecutor} callback, all other registered but unexecuted
 * listeners are prevented from running, even if those listeners are to run
 * in other executors.
 *
 * <p>For a more general interface to attach a completion listener to a
 * {@code Future}, see {@link ListenableFuture#addListener addListener}.
 *
 * @param future The future attach the callback to.
 * @param callback The callback to invoke when {@code future} is completed.
 * @param executor The executor to run {@code callback} when the future
 *    completes.
 * @since 10.0
 */
public static <V> void addCallback(final ListenableFuture<V> future, final FutureCallback<? super V> callback,
        Executor executor) {
    Preconditions.checkNotNull(callback);
    Runnable callbackListener = new Runnable() {
        @Override
        public void run() {
            try {
                // TODO(user): (Before Guava release), validate that this
                // is the thing for IE.
                V value = getUninterruptibly(future);
                callback.onSuccess(value);
            } catch (ExecutionException e) {
                callback.onFailure(e.getCause());
            } catch (RuntimeException e) {
                callback.onFailure(e);
            } catch (Error e) {
                callback.onFailure(e);
            }
        }
    };
    future.addListener(callbackListener, executor);
}

From source file:com.vmware.photon.controller.deployer.dcp.util.MiscUtils.java

private static void processTask(Service service, final Integer taskPollDelay, Task task,
        final FutureCallback<Task> callback) throws Throwable {
    ServiceUtils.logInfo(service, "Process task %s - %s..", task.getId(), task.getState().toUpperCase());
    switch (task.getState().toUpperCase()) {
    case "QUEUED":
    case "STARTED":
        scheduleGetTaskCall(service, taskPollDelay, task.getId(), callback);
        break;//  w  ww. jav  a  2s. c  om
    case "COMPLETED":
        ServiceUtils.logInfo(service, "Task completed %s..", task.getId());
        callback.onSuccess(task);
        break;
    case "ERROR":
        if (ApiUtils.getErrors(task).contains("NotFound")) {
            // Swallow this error since VM/Image or object is removed from the host already and since
            // we are already on remove path, notFound errors are safe to ignore
            ServiceUtils.logInfo(service, "Swallowing error %s..", ApiUtils.getErrors(task));
            callback.onSuccess(task);
            break;
        } else {
            throw new RuntimeException(ApiUtils.getErrors(task));
        }
    default:
        throw new RuntimeException("Unexpected task status " + task.getState());
    }
}

From source file:com.vmware.photon.controller.clustermanager.utils.ApiUtils.java

/**
 * This method polls the tasks status asynchronously until all the tasks completes or fails.
 *
 * @param tasks             Supplies a list of task objects.
 * @param client            Supplies the API client object.
 * @param service           Supplies the Xenon micro-service which is waiting on the task completion.
 * @param queryTaskInterval Supplies the time interval between the task status query.
 * @param callback          Supplies the callback to be invoked when the task completes or fails.
 *///from  w ww .j  a v a 2  s .c  o m
public static void pollTasksAsync(final List<Task> tasks, final ApiClient client, final Service service,
        final int queryTaskInterval, final FutureCallback<List<Task>> callback) {

    final AtomicInteger latch = new AtomicInteger(tasks.size());
    final List<Task> finalTasks = new ArrayList<>();
    final List<Throwable> failures = new ArrayList<>();

    FutureCallback<Task> internalCallback = new FutureCallback<Task>() {
        @Override
        public void onSuccess(Task result) {
            synchronized (finalTasks) {
                finalTasks.add(result);
            }

            if (0 == latch.decrementAndGet()) {
                if (!failures.isEmpty()) {
                    callback.onFailure(ExceptionUtils.createMultiException(failures));
                } else {
                    callback.onSuccess(finalTasks);
                }
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            synchronized (failures) {
                failures.add(throwable);
            }

            if (0 == latch.decrementAndGet()) {
                callback.onFailure(ExceptionUtils.createMultiException(failures));
            }
        }
    };

    for (Task task : tasks) {
        pollTaskAsync(task, client, service, queryTaskInterval, internalCallback);
    }
}