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.opendaylight.nemo.user.vnspacemanager.structurestyle.deleteintent.DeleteFlow.java

private void DeleteFlowInstance(UserId userId, FlowId flowId) {
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    UserKey userKey = new UserKey(userId);
    FlowKey flowKey = new FlowKey(flowId);

    InstanceIdentifier<Flow> flowid = InstanceIdentifier.builder(Users.class).child(User.class, userKey)
            .child(Objects.class).child(Flow.class, flowKey).build();
    t.delete(LogicalDatastoreType.CONFIGURATION, flowid);
    CheckedFuture<Void, TransactionCommitFailedException> f = t.submit();
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override/*from   w  w w  . j a  va 2  s  .c  o  m*/
        public void onFailure(Throwable t) {
            LOG.error("Could not write endpoint base container", t);
        }

        @Override
        public void onSuccess(Void result) {
        }
    });
}

From source file:co.cask.cdap.common.service.RetryOnStartFailureService.java

@Override
protected void doStop() {
    startupThread.interrupt();/* w ww  .  ja v a  2 s  .co m*/
    Uninterruptibles.joinUninterruptibly(startupThread);

    Service service = currentDelegate;
    if (service != null) {
        Futures.addCallback(service.stop(), new FutureCallback<State>() {
            @Override
            public void onSuccess(State result) {
                notifyStopped();
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, Threads.SAME_THREAD_EXECUTOR);
    } else {
        notifyStopped();
    }
}

From source file:org.opendaylight.mdsal.mount.cache.impl.tx.CachedDOMWriteTransaction.java

private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
        final DOMStoreWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {

    // Not using Futures.allAsList here to avoid its internal overhead.
    FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
        @Override//from   w w w .  ja  v  a2  s. c o  m
        public void onSuccess(Boolean result) {
            if (result == null || !result) {
                handleException(clientSubmitFuture, transaction, cohort, CAN_COMMIT,
                        TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER,
                        new TransactionCommitFailedException(
                                "%s: Can Commit failed, no detailed cause available." + nodeId));
            } else {
                // All cohorts completed successfully - we can move on to the preCommit phase
                doPreCommit(clientSubmitFuture, transaction, cohort);
            }
        }

        @Override
        public void onFailure(Throwable failure) {
            handleException(clientSubmitFuture, transaction, cohort, CAN_COMMIT,
                    TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, failure);
        }
    };

    ListenableFuture<Boolean> canCommitFuture = cohort.canCommit();
    Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
}

From source file:org.opendaylight.nemo.user.vnspacemanager.structurestyle.deleteintent.DeleteNode.java

private void DeleteNodeInstance(UserId userId, NodeId nodeId) {
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    UserKey userKey = new UserKey(userId);
    NodeKey nodeKey = new NodeKey(nodeId);

    InstanceIdentifier<Node> nodeid = InstanceIdentifier.builder(Users.class).child(User.class, userKey)
            .child(Objects.class).child(Node.class, nodeKey).build();
    t.delete(LogicalDatastoreType.CONFIGURATION, nodeid);
    CheckedFuture<Void, TransactionCommitFailedException> f = t.submit();
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override/* w  ww.j a va2s .  c o m*/
        public void onFailure(Throwable t) {
            LOG.error("Could not write endpoint base container", t);
        }

        @Override
        public void onSuccess(Void result) {
        }
    });
}

From source file:org.apache.solr.handler.component.aggregates.Aggregate.java

private AggregationResult sum(String fieldName) throws IOException {
    int page = 0;
    int size = this.req.getParams().getInt(GroupByComponent.Params.SIZE, 4096);
    int mincount = Math.max(this.req.getParams().getInt(GroupByComponent.Params.MINCOUNT, 1), 1);
    Double sum = 0D;//from  w  w  w . j  a va2s .  c o m
    Double itemValue = 0D;
    Long count = 0L;
    final AggregationResult result = new AggregationResult(fieldName);

    boolean done = false;
    while (!done) {
        ModifiableSolrParams p = new ModifiableSolrParams(this.req.getParams());
        p.set("facet.mincount", mincount);
        p.set("facet.limit", size);
        p.set("facet.offset", page * size);
        SimpleFacets facets = new SimpleFacets(this.req, base, p);

        // TODO - offset pagination support at different levels
        // for example page through sub-children as they can be rather large
        // but we could be on second page of facets for parent....
        // groupby.[noun:shopper].offset=10
        // groupby.[noun:xact/product_city_name].offset=10
        // groupby.[noun:xact/product_city_name].limit=10
        // groupby.[noun:xact/product_city_name].mincount=10
        // etc...

        NamedList<Integer> terms = facets.getTermCounts(fieldName);

        if (terms == null || terms.size() <= 0) {
            done = true;
            break;
        }

        FutureCallback<Double> cb = null;
        if (doPercentiles) {
            result.setQdigest(new QDigest(this.compression));
            result.setPercentiles(this.requestedPercentiles);
            cb = new FutureCallback<Double>() {
                public void onSuccess(Double value) {
                    result.getQdigest().offer(value.longValue());
                }

                public void onFailure(Throwable arg0) {
                }
            };
        }

        for (Map.Entry<String, Integer> parent : terms) {
            // System.out.println("\t Facet " + fieldName + ":" + parent.getKey() + " (" + parent.getValue() + ")");
            itemValue = Double.parseDouble(parent.getKey());
            Double total = itemValue * parent.getValue();
            sum += total;
            count += parent.getValue();
            if (cb != null) {
                cb.onSuccess(total);
            }
        }

        page = page + 1;
    }

    result.setSum(sum);
    result.setCount(count);
    return result;
}

From source file:org.retrostore.android.RetrostoreActivity.java

private void refreshApps() {
    setRefreshingStatus(true);/*  ww  w.j  a v  a 2 s  .  c  o m*/
    // FIXME: I don't see variable names for the API.
    Futures.addCallback(mFetcher.getAppsAsync(), new FutureCallback<List<App>>() {
        @Override
        public void onSuccess(List<App> result) {
            onAppsReceived(result);
            setRefreshingStatus(false);
        }

        @Override
        public void onFailure(Throwable t) {
            showToast("Something went wrong during the request: " + t.getMessage());
            setRefreshingStatus(false);
        }
    });
}

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

private void pullMessages(final Duration backoff) {
    ListenableFuture<PullResponse> pullResult = stub
            .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)
            .pull(PullRequest.newBuilder().setSubscription(subscription).setMaxMessages(DEFAULT_MAX_MESSAGES)
                    .setReturnImmediately(true).build());

    Futures.addCallback(pullResult, new FutureCallback<PullResponse>() {
        @Override/*from w w w  . j  ava2  s  . c  o  m*/
        public void onSuccess(PullResponse pullResponse) {
            processReceivedMessages(pullResponse.getReceivedMessagesList());
            if (pullResponse.getReceivedMessagesCount() == 0) {
                // No messages in response, possibly caught up in backlog, we backoff to avoid 
                // slamming the server.
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            pullMessages(INITIAL_BACKOFF);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (!(cause instanceof StatusRuntimeException)
                    || isRetryable(((StatusRuntimeException) cause).getStatus())) {
                logger.error("Failed to pull messages (recoverable): " + cause.getMessage(), cause);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            notifyFailed(cause);
        }
    });
}

From source file:org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl.java

@Override
public void run() {
    while (true) {
        forgetSuccessfulTransactions();/*from   w  w  w.j ava  2 s. c  o m*/

        List<TransactionCommand> commands = null;
        try {
            commands = extractCommands();
        } catch (InterruptedException e) {
            LOG.warn("Extracting commands was interrupted.", e);
            continue;
        }

        ReadWriteTransaction transactionInFlight = null;
        try {
            for (TransactionCommand command : commands) {
                final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
                transactionInFlight = transaction;
                recordPendingTransaction(command, transaction);
                command.execute(transaction);
                Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
                    @Override
                    public void onSuccess(final Void result) {
                        successfulTransactionQueue.offer(transaction);
                    }

                    @Override
                    public void onFailure(final Throwable throwable) {
                        // NOOP - handled by failure of transaction chain
                    }
                });
            }
        } catch (IllegalStateException e) {
            if (transactionInFlight != null) {
                // TODO: This method should distinguish exceptions on which the command should be
                // retried from exceptions on which the command should NOT be retried.
                // Then it should retry only the commands which should be retried, otherwise
                // this method will retry commands which will never be successful forever.
                failedTransactionQueue.offer(transactionInFlight);
            }
            LOG.warn("Failed to process an update notification from OVS.", e);
        }
    }
}

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   www  .  ja  v  a 2 s .  c o  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// w w  w.  j ava  2 s.  c  om
            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()));
            }
        });
    }
}