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(final ListenableFuture<V> future, final FutureCallback<? super V> callback,
        Executor executor) 

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:io.soliton.time.TimeClient.java

public static void main(String... args) throws Exception {
    // Parse arguments
    TimeClient timeClient = new TimeClient();
    new JCommander(timeClient, args);

    // Create client
    QuartzClient.Builder clientBuilder = QuartzClient
            .newClient(HostAndPort.fromParts(timeClient.hostname, timeClient.port));

    if (timeClient.ssl) {
        clientBuilder.setSslContext(getSslContext());
    }/* ww w  .j  av  a 2 s . c  o m*/

    QuartzClient client = clientBuilder.build();

    // Create service stub
    Time.TimeService.Interface timeService = Time.TimeService.newStub(client);

    CountDownLatch latch = new CountDownLatch(DateTimeZone.getAvailableIDs().size());

    // For each known timezone, request its current local time.
    for (String timeZoneId : DateTimeZone.getAvailableIDs()) {
        DateTimeZone timeZone = DateTimeZone.forID(timeZoneId);
        Time.TimeRequest request = Time.TimeRequest.newBuilder().setTimezone(timeZoneId).build();
        Futures.addCallback(timeService.getTime(request), new Callback(latch, timeZone), EXECUTOR);
    }

    latch.await();
    client.close();
}

From source file:org.opendaylight.infrautils.utils.concurrent.ListenableToCompletableFutureWrapper.java

public static <T> CompletionStage<T> create(ListenableFuture<T> guavaListenableFuture) {
    ListenableToCompletableFutureWrapper<T> instance = new ListenableToCompletableFutureWrapper<>(
            guavaListenableFuture);//from   w  w  w  .  ja v a 2  s. c o  m
    Futures.addCallback(guavaListenableFuture, instance, MoreExecutors.directExecutor());
    return instance;
}

From source file:info.archinnov.achilles.internals.futures.FutureUtils.java

public static <T> CompletableFuture<T> toCompletableFuture(ListenableFuture<T> listenableFuture,
        ExecutorService executor) {
    CompletableFuture<T> completable = new CompletableListenableFuture<>(listenableFuture);

    Futures.addCallback(listenableFuture, new FutureCallback<T>() {
        @Override//  w  w  w .jav  a2  s . c  om
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    }, executor);

    return completable;
}

From source file:de.leifaktor.robbie.controllers.clock.ClockCallBack.java

static <T> void addCallback(ListenableFuture<T> future, ClockCallBack<T> callBack, ExecutorService executor) {
    Futures.addCallback(future, callBack, executor);
}

From source file:org.thingsboard.rule.engine.api.util.DonAsynchron.java

public static <T> void withCallback(ListenableFuture<T> future, Consumer<T> onSuccess,
        Consumer<Throwable> onFailure, Executor executor) {
    FutureCallback<T> callback = new FutureCallback<T>() {
        @Override//from   w w  w .j  a  va  2s. c o m
        public void onSuccess(@Nullable T result) {
            try {
                onSuccess.accept(result);
            } catch (Throwable th) {
                onFailure(th);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            onFailure.accept(t);
        }
    };
    if (executor != null) {
        Futures.addCallback(future, callback, executor);
    } else {
        Futures.addCallback(future, callback);
    }
}

From source file:com.ecomnext.play.futures.GuavaFutures.java

/**
 * Converts a {@link ListenableFuture} into a {@link Future}.
 *
 * <p>Note: If the callback is slow or heavyweight, consider {@linkplain
 * #asPromise(ListenableFuture, Executor) supplying an executor}.
 * If you do not supply an executor, it will use the default executor,
 * the Play default thread pool will be used.
 *
 * @param lf the {@link ListenableFuture} to register a listener on.
 * @return a {@link Future} that emits the value when the future completes.
 *///from  w  w w.j a v  a2 s  . c  o  m
public static <V> Future<V> asScalaFuture(final ListenableFuture<V> lf) {
    Promise<V> promise = akka.dispatch.Futures.promise();
    Futures.addCallback(lf, new FutureCallbackAdapter<>(promise), getDefaultExecutor());
    return promise.future();
}

From source file:androidx.room.guava.GuavaRoom.java

/**
 * Returns a {@link ListenableFuture<T>} created by submitting the input {@code callable} to
 * {@link ArchTaskExecutor}'s background-threaded Executor.
 *//*ww w  . j a  va  2s .  co m*/
public static <T> ListenableFuture<T> createListenableFuture(final Callable<T> callable,
        final RoomSQLiteQuery query, final boolean releaseQuery) {
    ListenableFutureTask<T> listenableFutureTask = ListenableFutureTask.create(callable);
    ArchTaskExecutor.getInstance().executeOnDiskIO(listenableFutureTask);

    if (releaseQuery) {
        Futures.addCallback(listenableFutureTask, new FutureCallback<T>() {
            @Override
            public void onSuccess(T t) {
                query.release();
            }

            @Override
            public void onFailure(Throwable throwable) {
                query.release();
            }
        }, directExecutor());
    }

    return listenableFutureTask;
}

From source file:org.dcache.util.CompletableFutures.java

/**
 * Create a CompletableFuture from guava's ListenableFuture to
 * help migration from Guava to Java8./*from   w w w .j  a v a  2 s. co  m*/
 * @param listenable ListenableFuture to convert.
 * @return new CompletableFuture.
 */
public static <T> CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable) {

    final CompletableFuture<T> completable = new CompletableFuture<T>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            // propagate cancel to the listenable future
            boolean result = listenable.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return result;
        }
    };

    // propagate results to completable future
    Futures.addCallback(listenable, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    }, MoreExecutors.directExecutor());
    return completable;
}

From source file:com.facebook.presto.server.AsyncResponseUtils.java

public static void registerAsyncResponse(AsyncResponse asyncResponse, final ListenableFuture<?> futureResponse,
        Duration requestTimeout, Executor executor, final Response timeoutResponse) {
    // when the future completes, send the response
    Futures.addCallback(futureResponse, toAsyncResponse(asyncResponse), executor);

    // if the future does not complete in the specified time, send the timeout response
    asyncResponse.setTimeoutHandler(new AsyncTimeoutHandler(futureResponse, timeoutResponse));
    asyncResponse.setTimeout(requestTimeout.toMillis(), MILLISECONDS);
}

From source file:org.opendaylight.unimgr.mef.nrp.ovs.DataStoreTestUtils.java

public static <T extends DataObject> void write(T object, InstanceIdentifier<T> instanceIdentifier,
        DataBroker dataBroker) {//from  w  w w.j  a va 2 s. c om
    ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
    transaction.put(LogicalDatastoreType.OPERATIONAL, instanceIdentifier, object, true);

    Futures.addCallback(transaction.commit(), new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(@Nullable CommitInfo result) {
            LOG.debug("Object: {} created.", object.toString());
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.debug("Object: {} wasn't created due to a error: {}", object.toString(), t.getMessage());
            fail("Object  wasn't created due to a error: " + t.getMessage());
        }
    }, MoreExecutors.directExecutor());
}