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:com.b2international.snowowl.core.events.util.Promise.java

/**
 * Define what to do when the promise becomes rejected. The given {@link Function} should return another {@link Promise} which will be used to evaluate this {@link Promise}.
 * @param fail/*from w  ww .  j a va2 s. co  m*/
 * @return
 */
public final Promise<T> failWith(final Function<Throwable, Promise<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.resolveWith(fail.apply(t));
            } catch (Throwable e) {
                promise.reject(e);
            }
        }

    });
    return promise;
}

From source file:org.apache.gobblin.compliance.restore.ComplianceRestoreJob.java

public void run() throws IOException {
    Preconditions.checkNotNull(this.finder, "Dataset finder class is not set");
    List<Dataset> datasets = this.finder.findDatasets();
    this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size()));
    for (final Dataset dataset : datasets) {
        ListenableFuture<Void> future = this.service.submit(new Callable<Void>() {
            @Override/*from   www .j a va 2  s  .c o m*/
            public Void call() throws Exception {
                if (dataset instanceof RestorableDataset) {
                    log.info("Trying to restore");
                    ((RestorableDataset) dataset).restore();
                } else {
                    log.warn("Not an instance of " + RestorableDataset.class + " Dataset won't be restored "
                            + dataset.datasetURN());
                }
                return null;
            }
        });
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void result) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.info("Successfully restored: " + dataset.datasetURN());
            }

            @Override
            public void onFailure(Throwable t) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.warn("Exception caught when restoring " + dataset.datasetURN() + ".", t);
                ComplianceRestoreJob.this.throwables.add(t);
                ComplianceRestoreJob.this.eventSubmitter.submit(ComplianceEvents.Restore.FAILED_EVENT_NAME,
                        ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY,
                                ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY,
                                dataset.datasetURN()));
            }
        });
    }
}

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

private 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/*from   w  ww  . ja va 2  s  .  c o  m*/
        public void onSuccess(Subscription result) {
            messageDispatcher.setMessageDeadlineSeconds(result.getAckDeadlineSeconds());
            pullMessages(INITIAL_BACKOFF);
        }

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

From source file:org.opendaylight.netvirt.elan.l2gw.jobs.DeleteL2GwDeviceMacsFromElanJob.java

@Override
public List<ListenableFuture<Void>> call() {
    LOG.debug("Deleting l2gw device [{}] macs from other l2gw devices for elan [{}]",
            this.l2GwDevice.getHwvtepNodeId(), this.elanName);
    final String logicalSwitchName = ElanL2GatewayUtils.getLogicalSwitchFromElan(this.elanName);

    ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils
            .getInvolvedL2GwDevices(this.elanName);
    List<ListenableFuture<Void>> futures = new ArrayList<>();
    for (L2GatewayDevice otherDevice : elanL2GwDevices.values()) {
        if (!otherDevice.getHwvtepNodeId().equals(this.l2GwDevice.getHwvtepNodeId())
                && !ElanL2GatewayUtils.areMLAGDevices(this.l2GwDevice, otherDevice)) {
            final String hwvtepId = otherDevice.getHwvtepNodeId();
            // never batch deletes
            ListenableFuture<Void> uninstallFuture = HwvtepUtils.deleteRemoteUcastMacs(this.broker,
                    new NodeId(hwvtepId), logicalSwitchName, this.macAddresses);
            Futures.addCallback(uninstallFuture, new FutureCallback<Void>() {
                @Override/*from   w  w w.j  a  v  a 2  s .com*/
                public void onSuccess(Void noarg) {
                    LOG.trace("Successful in initiating ucast_remote_macs deletion related to {} in {}",
                            logicalSwitchName, hwvtepId);
                }

                @Override
                public void onFailure(Throwable error) {
                    LOG.error(String.format("Failed removing ucast_remote_macs related to %s in %s",
                            logicalSwitchName, hwvtepId), error);
                }
            });
            futures.add(uninstallFuture);
        }
    }
    return futures;
}

From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java

@GET
@ManagedAsync//from   w w w . jav  a  2  s. com
public void observable(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final AgentResponse response = new AgentResponse();

    // Fallback.
    Futures.addCallback(Futures.successfulAsList(Arrays.asList(visited(response), recommended(response))),
            new FutureCallback<List<AgentResponse>>() {
                @Override
                public void onSuccess(final List<AgentResponse> result) {
                    response.setProcessingTime((System.nanoTime() - time) / 1000000);
                    async.resume(response);
                }

                @Override
                public void onFailure(final Throwable t) {
                    async.resume(t);
                }
            });
}

From source file:org.hawkular.metrics.api.jaxrs.handler.CounterHandler.java

@POST
@Path("/{group}/{counter}/{value}")
@ApiOperation(value = "Update value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
        @PathParam("counter") String counter, @PathParam("value") Long value) {
    ListenableFuture<Void> future = metricsService
            .updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter, value));
    Futures.addCallback(future, new NoDataCallback<>(asyncResponse));
}

From source file:org.opendaylight.router.UserDataHandler.java

public void deleteDataFromOprDataStore(InstanceIdentifier<?> iid) {
    WriteTransaction wtx = dataBroker.newWriteOnlyTransaction();
    wtx.delete(LogicalDatastoreType.OPERATIONAL, iid);
    CheckedFuture<Void, TransactionCommitFailedException> future = wtx.submit();

    Futures.addCallback(future, new FutureCallback<Void>() {

        @Override//from  ww  w.j a v a  2s  .c  o m
        public void onSuccess(Void result) {
            LOG.info("deleted the subinterface");
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.info("failed to delete the subinterface");
        }
    });
}