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:org.opendaylight.restconf.restful.utils.FutureCallbackTx.java

/**
 * Add callback to the future object/*from ww w.  j ava  2 s  . c om*/
 *
 * @param listenableFuture
 *            - future object
 * @param txType
 *            - type of operation (READ, POST, PUT, DELETE)
 * @param dataFactory
 *            - factory setting result
 */
static <T, X extends Exception> void addCallback(final CheckedFuture<T, X> listenableFuture,
        final String txType, final FutureDataFactory<T> dataFactory) {
    final CountDownLatch responseWaiter = new CountDownLatch(1);
    Futures.addCallback(listenableFuture, new FutureCallback<T>() {

        @Override
        public void onFailure(final Throwable t) {
            responseWaiter.countDown();
            handlingLoggerAndValues(t, txType, null, dataFactory);
        }

        @Override
        public void onSuccess(final T result) {
            handlingLoggerAndValues(null, txType, result, dataFactory);
            responseWaiter.countDown();
        }

    });
    try {
        responseWaiter.await();
    } catch (final Exception e) {
        final String msg = "Problem while waiting for response";
        LOG.warn(msg);
        throw new RestconfDocumentedException(msg, e);
    }
}

From source file:org.opendaylight.vpnservice.elan.utils.ElanClusterUtils.java

public static void runOnlyInLeaderNode(final Runnable job, final String jobDescription) {
    ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner(eos,
            HwvtepSouthboundConstants.ELAN_ENTITY_TYPE, HwvtepSouthboundConstants.ELAN_ENTITY_NAME);
    Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() {
        @Override/*  ww w  . jav  a  2s  .c  o  m*/
        public void onSuccess(Boolean isOwner) {
            if (isOwner) {
                job.run();
            } else {
                logger.trace("job is not run as i m not cluster owner desc :{} ", jobDescription);
            }
        }

        @Override
        public void onFailure(Throwable error) {
            logger.error("Failed to identity cluster owner ", error);
        }
    });
}

From source file:global.PlayAsync.java

public static <T> Future<T> asFuture(ListenableFuture<T> future) {
    final scala.concurrent.Promise<T> promise = new DefaultPromise<T>();
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override/*from  ww  w. java  2s  .  c  om*/
        public void onSuccess(T result) {
            promise.success(result);
        }

        @Override
        public void onFailure(Throwable t) {
            promise.failure(t);
        }
    });
    return promise.future();
}

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

public static <T extends DataObject> void asyncWrite(final DataBroker broker,
        final LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data,
        FutureCallback<Void> callback) {
    WriteTransaction tx = broker.newWriteOnlyTransaction();
    tx.put(datastoreType, path, data, true);
    Futures.addCallback(tx.submit(), callback);
}

From source file:org.opendaylight.faas.fabricmgr.FabMgrDatastoreUtil.java

public static <T extends DataObject> void deleteData(final LogicalDatastoreType storeType,
        final InstanceIdentifier<T> path) {
    final WriteTransaction tx = FabMgrDatastoreDependency.getDataProvider().newWriteOnlyTransaction();
    tx.delete(storeType, path);// w w w  .  j  ava  2s  .c om
    Futures.addCallback(tx.submit(), new FutureCallback<Void>() {

        @Override
        public void onSuccess(final Void result) {
            LOG.trace("FABMGR: Data has deleted from datastore {} {}", storeType, path);
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error(
                    "FABMGR: ERROR: Can not delete data from datastore [store: {}] [path: {}] [exception: {}]",
                    storeType, path, t);
        }

    });
}

From source file:se.softhouse.common.testlib.Concurrently.java

/**
 * Returns a {@link ListenableFuture} running {@code callable} asynchronously. When this method
 * returns the {@link Callable#call()} may have been run or it may not. Call
 * {@link Future#get()} on the returned {@link Future} to get the result from the calculation.
 * The {@link Executor} running the returned {@link Future} is automatically shutdown when it's
 * done. If threads should be reused and performance is critical you should roll your own and
 * reuse the executor instead./*from ww w.j  ava2  s.co m*/
 */
public static <T> ListenableFuture<T> run(Callable<T> callable) {
    final ListeningExecutorService executor = listeningDecorator(newSingleThreadExecutor());
    ListenableFuture<T> futureForCallable = executor.submit(callable);
    Futures.addCallback(futureForCallable, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            executor.shutdownNow();
        }

        @Override
        public void onFailure(Throwable t) {
            executor.shutdownNow();
        }
    });
    return futureForCallable;
}

From source file:org.robotninjas.barge.state.MajorityCollector.java

@Nonnull
public static <U> ListenableFuture<Boolean> majorityResponse(@Nonnull List<ListenableFuture<U>> responses,
        @Nonnull Predicate<U> isSuccess) {
    MajorityCollector collector = new MajorityCollector(responses.size(), isSuccess);
    for (ListenableFuture<U> response : responses) {
        Futures.addCallback(response, collector);
    }//  ww  w  .j  ava2  s  .  com
    if (responses.isEmpty()) {
        collector.checkComplete();
    }
    return collector;
}

From source file:com.spotify.helios.agent.Result.java

public Result(final ListenableFuture<V> future) {
    Futures.addCallback(future, this);
}

From source file:com.microsoft.office.integration.test.CalendarsAsyncTestCase.java

public void testSize() {
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.getCalendars().fetchAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);//  w  ww.  j a va  2 s  .co  m
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                assertTrue(Me.getCalendars().size() > 0); // at least one calendar always exists
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testSize() timed out");
        }
    } catch (InterruptedException e) {
        fail("testSize() has been interrupted");
    }
}

From source file:com.microsoft.office.integration.test.SingletonAsyncTestCase.java

public void testMeRetrieving() {
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.init(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);/*from  www  .  ja  v  a  2  s  . c  o m*/
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                assertTrue(Me.getId().equalsIgnoreCase(TestRunner.getUsername())); // as per spec  
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testSize() timed out");
        }
    } catch (InterruptedException e) {
        fail("testSize() has been interrupted");
    }
}