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:io.bitsquare.trade.protocol.trade.tasks.shared.BroadcastAfterLockTime.java

private void broadcastTx() {
    Log.traceCall();/*from  ww  w.j a v  a  2s. c  o m*/
    Transaction payoutTx = trade.getPayoutTx();
    checkNotNull(payoutTx, "payoutTx must not be null at BroadcastAfterLockTime.broadcastTx");

    Transaction payoutTxFromWallet = processModel.getWalletService().getWallet()
            .getTransaction(payoutTx.getHash());
    log.debug("payoutTxFromWallet:" + payoutTxFromWallet);
    if (payoutTxFromWallet != null)
        payoutTx = payoutTxFromWallet;

    TransactionConfidence.ConfidenceType confidenceType = payoutTx.getConfidence().getConfidenceType();
    log.debug("payoutTx confidenceType:" + confidenceType);
    if (confidenceType.equals(TransactionConfidence.ConfidenceType.BUILDING)
            || confidenceType.equals(TransactionConfidence.ConfidenceType.PENDING)) {
        log.debug("payoutTx already building:" + payoutTx);
        trade.setState(Trade.State.PAYOUT_BROAD_CASTED);
        complete();
    } else {
        log.debug("do broadcast tx " + payoutTx);
        processModel.getTradeWalletService().broadcastTx(payoutTx, new FutureCallback<Transaction>() {
            @Override
            public void onSuccess(Transaction transaction) {
                log.debug("BroadcastTx succeeded. Transaction:" + transaction);
                trade.setState(Trade.State.PAYOUT_BROAD_CASTED);
                complete();
            }

            @Override
            public void onFailure(@NotNull Throwable t) {
                log.error("BroadcastTx failed. Error:" + t.getMessage());
                failed(t);
            }
        });
    }
}

From source file:io.crate.operation.merge.IteratorPageDownstream.java

@Override
public void nextPage(BucketPage page, final PageConsumeListener listener) {
    FutureCallback<List<Bucket>> finalCallback = new FutureCallback<List<Bucket>>() {
        @Override//from  ww w  .j av a2 s  .co m
        public void onSuccess(List<Bucket> buckets) {
            pagingIterator.merge(numberedBuckets(buckets));
            lastIterator = pagingIterator;
            lastListener = listener;
            try {
                processBuckets(pagingIterator, listener);
            } catch (Throwable t) {
                fail(t);
                listener.finish();
            }
        }

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

    /**
     * Wait for all buckets to arrive before doing any work to make sure that the job context is present on all nodes
     * Otherwise there could be race condition.
     * E.g. if a FetchProjector finishes early with data from one node and wants to close the remaining contexts it
     * could be that one node doesn't even have a context to close yet and that context would remain open.
     *
     * NOTE: this doesn't use Futures.allAsList because in the case of failures it should still wait for the other
     * upstreams before taking any action
     */
    Executor executor = RejectionAwareExecutor.wrapExecutor(this.executor, finalCallback);
    MultiFutureCallback<Bucket> multiFutureCallback = new MultiFutureCallback<>(page.buckets().size(),
            finalCallback);
    for (ListenableFuture<Bucket> bucketFuture : page.buckets()) {
        Futures.addCallback(bucketFuture, multiFutureCallback, executor);
    }
}

From source file:com.infinities.skyport.quartz.QuartzServiceImpl.java

private <T> FutureCallback<T> rescheduledCallback(final K k, final QuartzConfiguration<T> configuration,
        final boolean periodic, final ListeningExecutorService worker) {
    return new FutureCallback<T>() {

        @Override//ww w  .j a va  2  s .c o m
        public void onSuccess(T result) {
            reschedule(k, configuration, periodic, worker);
        }

        @Override
        public void onFailure(Throwable t) {
            reschedule(k, configuration, periodic, worker);
        }
    };
}

From source file:org.opendaylight.netconf.sal.connect.netconf.sal.tx.WriteCandidateTx.java

private void lock() {
    final FutureCallback<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
        @Override//  ww w.  jav  a  2  s  .co m
        public void onSuccess(DOMRpcResult result) {
            if (isSuccess(result)) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Lock candidate succesfull");
                }
            } else {
                LOG.warn("{}: lock candidate invoked unsuccessfully: {}", id, result.getErrors());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.warn("Lock candidate operation failed. {}", t);
            NetconfDocumentedException e = new NetconfDocumentedException(
                    id + ": Lock candidate operation failed.", NetconfDocumentedException.ErrorType.application,
                    NetconfDocumentedException.ErrorTag.operation_failed,
                    NetconfDocumentedException.ErrorSeverity.warning);
            discardChanges();
            throw new RuntimeException(e);
        }
    };
    netOps.lockCandidate(lockCandidateCallback);
}

From source file:io.bitsquare.gui.main.account.content.registration.RegistrationModel.java

void payFee() {
    FutureCallback<Transaction> callback = new FutureCallback<Transaction>() {
        @Override// w ww . j  ava  2s .c o m
        public void onSuccess(@Nullable Transaction transaction) {
            log.debug("payRegistrationFee onSuccess");
            if (transaction != null) {
                transactionId = transaction.getHashAsString();
                log.info("payRegistrationFee onSuccess tx id:" + transaction.getHashAsString());

                if (getAddressEntry() != null)
                    user.setAccountID(getAddressEntry().toString());

                persistence.write(user.getClass().getName(), user);
                payFeeSuccess.set(true);
            }
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.debug("payRegistrationFee onFailure");
            payFeeErrorMessage.set("Fee payment failed with error: " + t.getMessage());
        }
    };
    try {
        walletService.payRegistrationFee(user.getStringifiedBankAccounts(), callback);
    } catch (InsufficientMoneyException e) {
        payFeeErrorMessage.set("Fee payment failed with error: " + e.getMessage());
    }
}

From source file:io.v.v23.InputChannels.java

private static <T> FutureCallback<T> newCallbackForDone(final InputChannel<T> channel,
        final SettableFuture<Void> future, final Executor executor) {
    return new FutureCallback<T>() {
        @Override/*www  .ja  va2 s  .com*/
        public void onSuccess(T result) {
            Futures.addCallback(channel.recv(), newCallbackForDone(channel, future, executor), executor);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof EndOfFileException) {
                future.set(null);
            } else {
                future.setException(t);
            }
        }
    };
}

From source file:com.vmware.photon.controller.client.resource.FlavorApi.java

/**
 * Lists all flavors./*ww w .j  a  va 2  s. c  o  m*/
 *
 * @param responseCallback
 * @throws IOException
 */
public void listAllAsync(final FutureCallback<ResourceList<Flavor>> responseCallback) throws IOException {
    ResourceList<Flavor> flavorResourceList = new ResourceList<>();
    FutureCallback<ResourceList<Flavor>> callback = new FutureCallback<ResourceList<Flavor>>() {
        @Override
        public void onSuccess(@Nullable ResourceList<Flavor> result) {
            if (flavorResourceList.getItems() == null) {
                flavorResourceList.setItems(result.getItems());
            } else {
                flavorResourceList.getItems().addAll(result.getItems());
            }
            if (result.getNextPageLink() != null && !result.getNextPageLink().isEmpty()) {
                try {
                    getObjectByPathAsync(result.getNextPageLink(), this,
                            new TypeReference<ResourceList<Flavor>>() {
                            });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                responseCallback.onSuccess(flavorResourceList);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            responseCallback.onFailure(t);
        }
    };

    getObjectByPathAsync(getBasePath(), callback, new TypeReference<ResourceList<Flavor>>() {
    });
}

From source file:org.apache.twill.internal.zookeeper.LeaderElection.java

@Override
protected void doStop() {
    final SettableFuture<String> completion = SettableFuture.create();
    Futures.addCallback(completion, new FutureCallback<String>() {
        @Override//  w  ww .  j a v  a2 s . co m
        public void onSuccess(String result) {
            try {
                notifyStopped();
            } finally {
                executor.shutdown();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                notifyFailed(t);
            } finally {
                executor.shutdown();
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    executor.execute(new Runnable() {
        @Override
        public void run() {
            if (watcherCancellable != null) {
                watcherCancellable.cancel();
            }
            if (state != State.CANCELLED) {
                // becomeFollower has to be called before deleting node to make sure no two active leader.
                if (state == State.LEADER) {
                    becomeFollower();
                }
                state = State.CANCELLED;
                doDeleteNode(completion);
            }
        }
    });
}

From source file:io.crate.action.sql.TransportSQLBulkAction.java

@Override
void executePlan(Executor executor, Analysis analysis, Plan plan,
        final ActionListener<SQLBulkResponse> listener, final SQLBulkRequest request, final long startTime) {
    if (!analysis.expectsAffectedRows()) {
        listener.onFailure(new UnsupportedOperationException(
                "Bulk operations for statements that return result sets is not supported"));
        return;/* www .j a  va  2s  . c  o m*/
    }

    ListenableFuture<List<TaskResult>> future = Futures.allAsList(executor.executeBulk(plan));
    Futures.addCallback(future, new FutureCallback<List<TaskResult>>() {
        @Override
        public void onSuccess(@Nullable List<TaskResult> result) {
            listener.onResponse(createResponse(result, startTime));
        }

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

From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();//w  ww . j a  v  a  2s . c om
    LOG.debug("{}: Invoking read at {}:{}", txIdentifier, store, path);
    final ListenerRegistration<DOMDataTreeListener> reg;
    final SettableFuture<Optional<NormalizedNode<?, ?>>> initialDataTreeChangeFuture = SettableFuture.create();
    try {
        reg = service.registerListener(new ReadShardedListener(initialDataTreeChangeFuture),
                Collections.singleton(new DOMDataTreeIdentifier(store, path)), false, Collections.emptyList());
        registrations.add(reg);
    } catch (final DOMDataTreeLoopException e) {
        // This should not happen, we are not specifying any
        // producers when registering listener
        throw new IllegalStateException("Loop in listener and producers detected", e);
    }

    // After data tree change future is finished, we can close the listener registration
    Futures.addCallback(initialDataTreeChangeFuture, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            reg.close();
        }

        @Override
        public void onFailure(final Throwable throwable) {
            reg.close();
        }
    });

    return Futures.makeChecked(initialDataTreeChangeFuture, ReadFailedException.MAPPER);
}