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:org.apache.hadoop.hdfs.qjournal.client.QuorumCall.java

static <KEY, RESULT> QuorumCall<KEY, RESULT> create(Map<KEY, ? extends ListenableFuture<RESULT>> calls) {
    final QuorumCall<KEY, RESULT> qr = new QuorumCall<KEY, RESULT>();
    for (final Entry<KEY, ? extends ListenableFuture<RESULT>> e : calls.entrySet()) {
        Preconditions.checkArgument(e.getValue() != null, "null future for key: " + e.getKey());
        Futures.addCallback(e.getValue(), new FutureCallback<RESULT>() {
            @Override/* www .j  av  a2s.c  o  m*/
            public void onFailure(Throwable t) {
                qr.addException(e.getKey(), t);
            }

            @Override
            public void onSuccess(RESULT res) {
                qr.addResult(e.getKey(), res);
            }
        });
    }
    return qr;
}

From source file:io.crate.executor.transport.DelayedTask.java

@Override
public void execute(final RowReceiver rowReceiver, final Row parameters) {
    Futures.addCallback(listenableFuture, new FutureCallback<Object>() {
        @Override//from   w  ww . jav  a 2  s . c  o m
        public void onSuccess(@Nullable Object result) {
            rootTask.get().execute(rowReceiver, parameters);
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            rowReceiver.fail(t);
        }
    });
}

From source file:com.vsct.strowgr.monitoring.aggregator.cassandra.ErrorRecordWriter.java

public void write(ErrorRecord payload) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Record message processing error. Payload=" + payload.getPayload());

    BoundStatement bound = writeRawPayloadPeparedStatement.bind(payload.getDate(), payload.getTimestamp(),
            payload.getReason(), payload.getPayload());

    Futures.addCallback(session.executeAsync(bound), new FutureCallback<ResultSet>() {
        @Override/*from ww  w  .j a v  a2 s .c o m*/
        public void onSuccess(ResultSet rows) {

        }

        @Override
        public void onFailure(Throwable throwable) {
            LOGGER.error("Could not send message processing error to cassandra. Everything relies on the log.");
        }
    });

}

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

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

        public void onSuccess(Void result) {
            try {
                FoldersAsyncTestCase.this.readAndCheck();
                FoldersAsyncTestCase.this.removeFolder();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

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

From source file:org.springframework.cassandra.core.GuavaListenableFutureAdapter.java

private static <T> ListenableFuture<T> adaptListenableFuture(
        com.google.common.util.concurrent.ListenableFuture<T> guavaFuture,
        PersistenceExceptionTranslator exceptionTranslator) {

    SettableListenableFuture<T> settableFuture = new SettableListenableFuture<>();

    Futures.addCallback(guavaFuture, new FutureCallback<T>() {
        @Override// ww w.  jav a  2 s.  c o  m
        public void onSuccess(T result) {
            settableFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof RuntimeException) {
                DataAccessException dataAccessException = exceptionTranslator
                        .translateExceptionIfPossible((RuntimeException) t);

                if (dataAccessException != null) {
                    settableFuture.setException(dataAccessException);
                    return;
                }
            }

            settableFuture.setException(t);
        }
    });

    return settableFuture;
}

From source file:com.vmware.photon.controller.clustermanager.statuschecks.KubernetesStatusChecker.java

@Override
public void checkNodeStatus(final String serverAddress, final FutureCallback<Boolean> callback) {
    Preconditions.checkNotNull(serverAddress, "serverAddress cannot be null");
    logger.info("Checking Kubernetes: {}", serverAddress);

    try {// w  ww.j  a v  a 2  s .  c om
        String connectionString = createConnectionString(serverAddress);
        kubernetesClient.getNodeAddressesAsync(connectionString, new FutureCallback<Set<String>>() {
            @Override
            public void onSuccess(@Nullable Set<String> nodes) {
                if (!nodes.contains(serverAddress)) {
                    logger.info("Node not registered with Kubernetes: {}", serverAddress);
                    callback.onSuccess(false);
                    return;
                }
                callback.onSuccess(true);
            }

            @Override
            public void onFailure(Throwable t) {
                logger.warn("Kubernetes call failed: ", t);
                callback.onSuccess(false);
            }
        });
    } catch (Exception e) {
        logger.warn("Kubernetes call failed: ", e);
        callback.onSuccess(false);
    }
}

From source file:com.kixeye.chassis.transport.http.ListenableFutureReturnValueHandler.java

@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;/*from ww  w  .  j a  v a  2 s.  com*/
    }
    final DeferredResult<Object> deferredResult = new DeferredResult<>();
    Futures.addCallback((ListenableFuture<?>) returnValue, new FutureCallback<Object>() {
        @Override
        public void onSuccess(@Nullable Object result) {
            deferredResult.setResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            deferredResult.setErrorResult(t);
        }
    });
    WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);
}

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

public static void runOnlyInLeaderNode(EntityOwnershipService entityOwnershipService, final String jobKey,
        final String jobDescription, final Callable<List<ListenableFuture<Void>>> dataStoreJob) {
    ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner(
            entityOwnershipService, HwvtepSouthboundConstants.ELAN_ENTITY_TYPE,
            HwvtepSouthboundConstants.ELAN_ENTITY_NAME);
    Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() {
        @Override//from  w  ww .ja  v a2s  .c o m
        public void onSuccess(Boolean isOwner) {
            if (isOwner) {
                LOG.trace("scheduling job {} ", jobDescription);
                DataStoreJobCoordinator.getInstance().enqueueJob(jobKey, dataStoreJob,
                        SystemPropertyReader.getDataStoreJobCoordinatorMaxRetries());
            } else {
                LOG.trace("job is not run as i m not cluster owner desc :{} ", jobDescription);
            }
        }

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Failed to identity cluster owner for job " + jobDescription, error);
        }
    });
}

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,/*from  w  ww.j a v a2  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:org.springframework.data.cassandra.core.cql.GuavaListenableFutureAdapter.java

private static <T> ListenableFuture<T> adaptListenableFuture(
        com.google.common.util.concurrent.ListenableFuture<T> guavaFuture,
        PersistenceExceptionTranslator exceptionTranslator) {

    SettableListenableFuture<T> settableFuture = new SettableListenableFuture<>();

    Futures.addCallback(guavaFuture, new FutureCallback<T>() {
        @Override/*from w  w  w  . j a v a2s .c o  m*/
        public void onSuccess(@Nullable T result) {
            settableFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof RuntimeException) {
                DataAccessException dataAccessException = exceptionTranslator
                        .translateExceptionIfPossible((RuntimeException) t);

                if (dataAccessException != null) {
                    settableFuture.setException(dataAccessException);
                    return;
                }
            }

            settableFuture.setException(t);
        }
    });

    return settableFuture;
}