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.placeoffer.tasks.BroadcastCreateOfferFeeTx.java

@Override
protected void run() {
    try {//from  w  w w  .  ja v a  2 s.  co  m
        runInterceptHook();
        model.tradeWalletService.broadcastTx(model.getTransaction(), new FutureCallback<Transaction>() {
            @Override
            public void onSuccess(Transaction transaction) {
                log.debug("Broadcast of offer fee payment succeeded: transaction = " + transaction.toString());

                if (model.getTransaction().getHashAsString().equals(transaction.getHashAsString())) {
                    model.offer.setState(Offer.State.OFFER_FEE_PAID);
                    // No tx malleability happened after broadcast (still not in blockchain)
                    complete();
                } else {
                    log.warn(
                            "Tx malleability happened after broadcast. We publish the changed offer to the P2P network again.");
                    // Tx malleability happened after broadcast. We first remove the malleable offer.
                    // Then we publish the changed offer to the P2P network again after setting the new TxId.
                    // Normally we use a delay for broadcasting to the peers, but at shut down we want to get it fast out
                    model.offerBookService.removeOffer(model.offer, () -> {
                        log.debug("We store now the changed txID to the offer and add that again.");
                        // We store now the changed txID to the offer and add that again.
                        model.offer.setOfferFeePaymentTxID(transaction.getHashAsString());
                        model.setTransaction(transaction);
                        model.offerBookService.addOffer(model.offer, () -> complete(), errorMessage -> {
                            log.error("addOffer failed");
                            addOfferFailed = true;
                            updateStateOnFault();
                            model.offer.setErrorMessage(
                                    "An error occurred when adding the offer to the P2P network.\n"
                                            + "Error message:\n" + errorMessage);
                            failed(errorMessage);
                        });
                    }, errorMessage -> {
                        log.error("removeOffer failed");
                        removeOfferFailed = true;
                        updateStateOnFault();
                        model.offer.setErrorMessage(
                                "An error occurred when removing the offer from the P2P network.\n"
                                        + "Error message:\n" + errorMessage);
                        failed(errorMessage);
                    });
                }
            }

            @Override
            public void onFailure(@NotNull Throwable t) {
                updateStateOnFault();
                model.offer.setErrorMessage("An error occurred.\n" + "Error message:\n" + t.getMessage());
                failed(t);
            }
        });
    } catch (Throwable t) {
        model.offer.setErrorMessage("An error occurred.\n" + "Error message:\n" + t.getMessage());
        failed(t);
    }
}

From source file:org.opendaylight.controller.cluster.datastore.ChainedCommitCohort.java

@Override
public void commit(final FutureCallback<UnsignedLong> callback) {
    delegate.commit(new FutureCallback<UnsignedLong>() {
        @Override//from  w  ww.ja  va  2 s.c  o m
        public void onSuccess(final UnsignedLong result) {
            chain.clearTransaction(transaction);
            LOG.debug("Committed transaction {}", transaction);
            callback.onSuccess(result);
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error("Transaction {} commit failed, cannot recover", transaction, t);
            callback.onFailure(t);
        }
    });
}

From source file:ratpack.session.store.internal.RedisSessionStore.java

@Override
public Operation store(AsciiString sessionId, ByteBuf sessionData) {
    return Promise.<Boolean>of(
            d -> Futures.addCallback(connection.set(sessionId, sessionData), new FutureCallback<String>() {
                @Override//from w w  w .jav  a  2 s . c o m
                public void onSuccess(String result) {
                    if (result != null && result.equalsIgnoreCase("OK")) {
                        d.success(true);
                    } else {
                        d.error(new RuntimeException("Failed to set session data"));
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    d.error(new RuntimeException("Failed to set session data.", t));
                }
            }, Execution.current().getEventLoop())).operation();
}

From source file:com.skcraft.launcher.update.UpdateManager.java

public void checkForUpdate() {
    ListenableFuture<URL> future = launcher.getExecutor().submit(new UpdateChecker(launcher));

    Futures.addCallback(future, new FutureCallback<URL>() {
        @Override// www  . j  av a  2  s.c  o m
        public void onSuccess(URL result) {
            if (result != null) {
                requestUpdate(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {

        }
    }, SwingExecutor.INSTANCE);
}

From source file:com.vmware.photon.controller.common.zookeeper.ServiceNodeUtils.java

private static void handleLeaseExpiration(ServiceNode.Lease lease, final ServiceNode serviceNode,
        final long retryIntervalMsec, final ServiceNodeEventHandler serviceNodeEventHandler) {
    Futures.addCallback(lease.getExpirationFuture(), new FutureCallback<Void>() {
        @Override// www  .  jav a  2s. co  m
        public void onSuccess(Void result) {
            rejoin();
        }

        @Override
        public void onFailure(Throwable t) {
            // Could happen if the expiration future gets cancelled: in that case
            // we can't reliably detect when we need to expire the connection anymore,
            // so it probably makes sense to leave and attempt to re-join immediately.
            logger.error("The expiration future has failed", t);
            rejoin();
        }

        public void rejoin() {
            if (serviceNodeEventHandler != null) {
                serviceNodeEventHandler.onLeave();
            }
            joinService(serviceNode, retryIntervalMsec, serviceNodeEventHandler);
        }
    });
}

From source file:crud.http.ListenerInvokingAnswer.java

@Override
public Future<ClientResponse> answer(final InvocationOnMock invocation) {
    @SuppressWarnings("unchecked")
    final ITypeListener<ClientResponse> listener = (ITypeListener<ClientResponse>) invocation.getArguments()[0];

    Futures.addCallback(this.mockFuture, new FutureCallback<ClientResponse>() {
        @Override/*from   w  w  w . ja  va2 s .  c om*/
        public void onSuccess(final ClientResponse result) {
            try {
                listener.onComplete(ListenerInvokingAnswer.this.mockFuture);
            } catch (final InterruptedException ex) {
                Throwables.propagate(ex);
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            try {
                listener.onComplete(ListenerInvokingAnswer.this.mockFuture);
            } catch (final InterruptedException ex) {
                Throwables.propagate(ex);
            }
        }
    });
    return this.mockFuture;
}

From source file:io.v.v23.syncbase.Batch.java

@CheckReturnValue
private static ListenableFuture<Boolean> tryBatch(final VContext ctx, final Database db,
        final BatchOptions opts, final BatchOperation op) {
    final SettableFuture<Boolean> ret = SettableFuture.create();
    Futures.addCallback(db.beginBatch(ctx, opts), new FutureCallback<BatchDatabase>() {
        @Override// w w w  .j ava 2s  .  c om
        public void onFailure(Throwable t) {
            ret.setException(t);
        }

        @Override
        public void onSuccess(final BatchDatabase batch) {
            Futures.addCallback(op.run(batch), new FutureCallback<Void>() {
                @Override
                public void onFailure(final Throwable t) {
                    Futures.addCallback(batch.abort(ctx), new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(Void result) {
                            ret.setException(t);
                        }

                        @Override
                        public void onFailure(Throwable newT) {
                            ret.setException(t);
                        }
                    });
                }

                @Override
                public void onSuccess(Void result) {
                    Futures.addCallback(opts.getReadOnly() ? batch.abort(ctx) : batch.commit(ctx),
                            new FutureCallback<Void>() {
                                @Override
                                public void onSuccess(Void result) {
                                    ret.set(true); // success
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    if (t instanceof ConcurrentBatchException) {
                                        // retry
                                        ret.set(false);
                                    } else {
                                        ret.setException(t);
                                    }
                                }
                            });
                }
            });
        }
    });
    return ret;
}

From source file:org.opendaylight.controller.cluster.datastore.DebugThreePhaseCommitCohort.java

private <V> ListenableFuture<V> addFutureCallback(ListenableFuture<V> future) {
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override//w  w w  .  j  av  a 2s .com
        public void onSuccess(V result) {
            // no-op
        }

        @Override
        public void onFailure(Throwable t) {
            log.warn("Transaction {} failed with error \"{}\" - was allocated in the following context",
                    transactionId, t, debugContext);
        }
    });

    return future;
}

From source file:com.continuuity.weave.internal.zookeeper.RewatchOnExpireZKClient.java

@Override
public OperationFuture<Stat> exists(String path, Watcher watcher) {
    final RewatchOnExpireWatcher wrappedWatcher = new RewatchOnExpireWatcher(this, ActionType.EXISTS, path,
            watcher);/*from w  w w .j ava2  s .c  om*/
    OperationFuture<Stat> result = super.exists(path, wrappedWatcher);
    Futures.addCallback(result, new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            wrappedWatcher.setLastResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op
        }
    });
    return result;
}

From source file:net.javacrumbs.futureconverter.common.test.guava.GuavaConvertedFutureTestHelper.java

@Override
public void waitForCalculationToFinish(
        com.google.common.util.concurrent.ListenableFuture<String> convertedFuture)
        throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    Futures.addCallback(convertedFuture, new FutureCallback<String>() {
        @Override/*from   ww w  . ja  v  a 2  s.  c  o  m*/
        public void onSuccess(String result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    }, MoreExecutors.directExecutor());

    latch.await(1, TimeUnit.SECONDS);
}