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:com.vmware.photon.controller.clustermanager.statuschecks.KubernetesStatusChecker.java

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

    try {/*  w  w  w . ja va2  s .c  o m*/
        String connectionString = createConnectionString(masterAddress);
        kubernetesClient.getNodeAddressesAsync(connectionString, new FutureCallback<Set<String>>() {
            @Override
            public void onSuccess(@Nullable Set<String> nodes) {
                if (!nodes.contains(masterAddress)) {
                    logger.info("Node not registered with Kubernetes: {}", masterAddress);
                    callback.onSuccess(false);
                    return;
                }

                try {
                    if (slaveAddresses == null || slaveAddresses.size() == 0) {
                        // we are only checking the current master
                        callback.onSuccess(true);
                    } else {
                        for (String slaveAddress : slaveAddresses) {
                            if (!nodes.contains(slaveAddress)) {
                                logger.info("Slave not registered with Kubernetes: {}", slaveAddress);
                                callback.onSuccess(false);
                                return;
                            }
                        }
                        callback.onSuccess(true);
                    }
                } catch (Exception e) {
                    logger.warn("Failed to process Kubernetes nodes: ", e);
                    callback.onFailure(e);
                }
            }

            @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.proofpoint.concurrent.AsyncSemaphore.java

private void runNext() {
    final QueuedTask<T> queuedTask = queuedTasks.poll();
    ListenableFuture<?> future = submitTask(queuedTask.getTask());
    FutureCallback<Object> callback = new FutureCallback<Object>() {
        @Override//from  w  w  w  . java2  s  .c o m
        public void onSuccess(Object result) {
            queuedTask.markCompleted();
            releasePermit();
        }

        @Override
        public void onFailure(Throwable t) {
            queuedTask.markFailure(t);
            releasePermit();
        }
    };
    Futures.addCallback(future, callback, directExecutor());
}

From source file:com.google.cloud.pubsub.PollingSubscriberConnection.java

@Override
void initialize() {
    ListenableFuture<Subscription> subscriptionInfo = stub
            .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)
            .getSubscription(GetSubscriptionRequest.newBuilder().setSubscription(subscription).build());

    Futures.addCallback(subscriptionInfo, new FutureCallback<Subscription>() {
        @Override/*  w w  w .ja v a2 s.  c  o  m*/
        public void onSuccess(Subscription result) {
            setMessageDeadlineSeconds(result.getAckDeadlineSeconds());
            pullMessages(INITIAL_BACKOFF);
        }

        @Override
        public void onFailure(Throwable cause) {
            notifyFailed(cause);
        }
    });
}

From source file:com.spotify.futures.AsyncRetrier.java

private <T> void startRetry(final SettableFuture<T> future, final Supplier<ListenableFuture<T>> code,
        final int retries, final long delay, final TimeUnit timeUnit, final Predicate<T> retryCondition) {

    ListenableFuture<T> codeFuture;
    try {/*from   w  w w .j  a va  2s.c om*/
        codeFuture = code.get();
    } catch (Exception e) {
        handleFailure(future, code, retries, delay, timeUnit, retryCondition, e);
        return;
    }

    Futures.addCallback(codeFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            if (retryCondition.apply(result)) {
                future.set(result);
            } else {
                RuntimeException exception = new RuntimeException("Failed retry condition");
                handleFailure(future, code, retries, delay, timeUnit, retryCondition, exception);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            handleFailure(future, code, retries, delay, timeUnit, retryCondition, t);
        }
    });
}

From source file:com.b2international.snowowl.core.events.util.Promise.java

/**
 * Define what to do when the promise becomes rejected.
 * //from ww w. j a v a 2s  .c  o  m
 * @param then
 * @return
 */
public final Promise<T> fail(final Function<Throwable, T> fail) {
    final Promise<T> promise = new Promise<>();
    Futures.addCallback(this, new FutureCallback<T>() {

        @Override
        public void onSuccess(T result) {
            promise.resolve(result);
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                promise.resolve(fail.apply(t));
            } catch (Throwable e) {
                promise.reject(e);
            }
        }

    });
    return promise;
}

From source file:$.AddBridgeOnHiveMQStart.java

/**
     * This method is called from HiveMQ, and the custom behaviour has to be implemented in here.
     * If some preconditions are not met to successfully operate, a {@link com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException}
     * should be thrown.//from  www  .  ja  va2 s .c om
     *
     * @throws com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException If the exception is thrown, HiveMQ will be stopped.
     */
    @Override
    public void onBrokerStart() throws BrokerUnableToStartException {
        log.info("Adding Bridge to MQTT Dashboard");
        final Bridge bridge = createBridge();

        // Start bridge with Bridge Manager Service dynamically
        final ListenableFuture<Void> future = bridgeManagerService.startBridge(bridge);

        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                log.info("Bridge started successfully");
            }

            @Override
            public void onFailure(Throwable t) {
                log.info("Bridge failed to start");
            }
        });

    }

From source file:zipkin.storage.cassandra.DeduplicatingExecutor.java

/**
 * @param session which conditionally executes bound statements
 * @param ttl how long the results of statements are remembered, in milliseconds.
 *///from w  w w. j av  a2  s  .  c o m
DeduplicatingExecutor(Session session, long ttl) {
    this.session = session;
    this.cache = CacheBuilder.newBuilder().expireAfterWrite(ttl, TimeUnit.MILLISECONDS).ticker(new Ticker() {
        @Override
        public long read() {
            return nanoTime();
        }
    })
            // TODO: maximum size or weight
            .build(new CacheLoader<BoundStatementKey, ListenableFuture<Void>>() {
                @Override
                public ListenableFuture<Void> load(final BoundStatementKey key) {
                    ListenableFuture<?> cassandraFuture = executeAsync(key.statement);

                    // Drop the cassandra future so that we don't hold references to cassandra state for
                    // long periods of time.
                    final SettableFuture<Void> disconnectedFuture = SettableFuture.create();
                    Futures.addCallback(cassandraFuture, new FutureCallback<Object>() {

                        @Override
                        public void onSuccess(Object result) {
                            disconnectedFuture.set(null);
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            cache.invalidate(key);
                            disconnectedFuture.setException(t);
                        }
                    });
                    return disconnectedFuture;
                }
            });
}

From source file:com.facebook.presto.util.AsyncSemaphore.java

private void runNext() {
    final QueuedTask<T> queuedTask = queuedTasks.poll();
    ListenableFuture<?> future = submitTask(queuedTask.getTask());
    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override/*from  w w w. j  a  va2 s. co  m*/
        public void onSuccess(Object result) {
            queuedTask.markCompleted();
            releasePermit();
        }

        @Override
        public void onFailure(Throwable t) {
            queuedTask.markFailure(t);
            releasePermit();
        }
    });
}

From source file:org.opendaylight.mdsal.binding.dom.adapter.BindingDOMTransactionChainAdapter.java

private CheckedFuture<Void, TransactionCommitFailedException> listenForFailure(final WriteTransaction tx,
        final CheckedFuture<Void, TransactionCommitFailedException> future) {
    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override/* ww w  . j  a  v  a 2 s  .  c  om*/
        public void onFailure(final Throwable t) {
            failTransactionChain(tx, t);
        }

        @Override
        public void onSuccess(final Void result) {
            // Intentionally NOOP
        }
    });

    return future;
}

From source file:com.abiquo.bond.api.EventDispatcher.java

/**
 * Submits a Future to the ExecutorService that will execute the plugin's processEvent method
 * for the event. Also creates a callback that will be executed when all the plugins have
 * completed processing the event. The callback method updates the lastEventTimestamp variable.
 * // ww w.  j  ava  2s .  c  o m
 * @param event the event to be processed by each plugin
 */
void dispatchEvent(final APIEvent event) {
    List<ListenableFuture<APIEventResult>> futures = new ArrayList<>();
    for (final PluginInterface plugin : plugins) {
        if (plugin.handlesEventType(event.getClass())) {
            ListenableFuture<APIEventResult> task = eventDispatcher.submit(() -> plugin.processEvent(event));
            futures.add(task);
        }
    }

    if (!futures.isEmpty()) {
        Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<APIEventResult>>() {

            @Override
            public void onSuccess(final List<APIEventResult> results) {
                for (APIEventResult result : results) {
                    LocalDateTime eventTs = result.getEvent().getTimestamp();
                    if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventTs)) {
                        lastEventTimestamp = eventTs;
                        logger.info("Last event timestamp updated to {}", lastEventTimestamp);
                    }
                }

            }

            @Override
            public void onFailure(final Throwable t) {
                if (t instanceof PluginEventException) {
                    PluginEventException pee = (PluginEventException) t;
                    Optional<APIEvent> optEvent = pee.getAPIEvent();
                    if (optEvent.isPresent()) {
                        LocalDateTime eventts = optEvent.get().getTimestamp();
                        if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventts)) {
                            lastEventTimestamp = eventts;
                        }
                    }
                } else {
                    // There's nothing we can do if any other exception type is thrown as we
                    // won't know which event was being processed. Simply log a message.
                    // Hopefully one of the other plugins will process the event
                    // successfully and that will update the timestamp. If not then the
                    // event will be resubmitted for processing by all plugins if no later
                    // events are successfully processed.
                    logger.error("Processing of event failed", t);
                }
            }
        });
    }
}