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.microsoft.office.integration.test.MessagesAsyncTestCase.java

public void testRead() {
    // create message first
    prepareMessage();/*  w  w  w . j a v  a 2s . com*/
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                try {
                    readAndCheck();
                } finally {
                    // clean-up
                    removeMessage();
                }
            } catch (Exception e) {
                reportError(e);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testRead() timed out");
        }
    } catch (InterruptedException e) {
        fail("testRead() has been interrupted");
    }
}

From source file:org.opendaylight.openflowplugin.applications.frsync.impl.SyncReactorGuardDecorator.java

public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
        final SyncupEntry syncupEntry) throws InterruptedException {
    final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);
    LOG.trace("syncup guard decorator: {}", nodeId.getValue());

    final long stampBeforeGuard = System.nanoTime();
    final Semaphore guard = summonGuardAndAcquire(flowcapableNodePath);
    if (guard == null) {
        return Futures.immediateFuture(false);
    }/*from w ww  . j av  a2s  .  c  o  m*/
    final long stampAfterGuard = System.nanoTime();

    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("syncup start {} waiting:{} guard:{} thread:{}", nodeId.getValue(),
                    formatNanos(stampAfterGuard - stampBeforeGuard), guard, threadName());
        }

        final ListenableFuture<Boolean> endResult = delegate.syncup(flowcapableNodePath, syncupEntry);

        Futures.addCallback(endResult, createSyncupCallback(guard, stampBeforeGuard, stampAfterGuard, nodeId));
        return endResult;
    } catch (InterruptedException e) {
        releaseGuardForNodeId(guard);
        throw e;
    }
}

From source file:com.example.suharshs.vango.RunKeyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_run_key);

    Intent intent = getIntent();//  ww w .  jav  a  2s.c  om
    final String key = intent.getStringExtra(MainActivity.EXTRA_KEY);

    TextView textView = (TextView) findViewById(R.id.text_run_key_status);
    textView.setText(String.format("Running go function keyed by '%s'", key));

    mOutput = (TextView) findViewById(R.id.text_run_key_output);

    if (savedInstanceState != null) {
        mLines = (String[]) savedInstanceState.getCharSequenceArray(OUTPUT_DATA);
        mNextLine = savedInstanceState.getInt(OUTPUT_NEXT);
        write(null); // force a redraw of the output TextView.
        if (savedInstanceState.getBoolean(STARTED)) {
            return;
        }
    }

    final VContext ctx = V.init(this,
            new Options().set(OptionDefs.LOG_VLEVEL, 0).set(OptionDefs.LOG_VMODULE, "*=0"));
    try {
        mRemoteInspectors = new RemoteInspectors(ctx);
    } catch (VException e) {
        Log.e(TAG, "Failed to enable remote inspection: " + e.toString());
    }
    synchronized (this) {
        mLines = new String[10];
        mNextLine = 0;
    }
    Futures.addCallback(BlessingsManager.getBlessings(ctx, this, BLESSINGS_KEY, true),
            new FutureCallback<Blessings>() {
                @Override
                public void onSuccess(Blessings b) {
                    Log.v(TAG, "Received blessings " + b.toString());
                    AsyncTask.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                (new Vango()).run(ctx, key, RunKeyActivity.this);
                            } catch (Exception e) {
                                write(e.toString());
                            }
                        }
                    });
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.d(TAG, "Failed to get blessings", t);
                }
            });
}

From source file:com.microsoft.artcurator.net.MessagesLoader.java

/**
 * Requests Attachment information about a given Message
 *
 * @param client   the client to make the request
 * @param msgId    the Message for which Attachment data should be loaded
 * @param callback callback to notify on success/failure
 *//*w w w  .  j av a2  s.  c  o  m*/
public static void getAttachmentContentTypeAsync(OutlookClient client, String msgId,
        FutureCallback<List<Attachment>> callback) {
    ListenableFuture<List<Attachment>> future = client.getMe().getMessage(msgId).getAttachments()
            .select("ContentType").read();
    Futures.addCallback(future, callback);
}

From source file:GRSX.SendMoneyController.java

public void send(ActionEvent event) {
    Coin amount = Coin.parseCoin(amountEdit.getText());

    if (amount.getValue() > 0.0 && Integer.parseInt(feeEdit.getText()) >= 10) {
        try {//from   w ww .ja  va 2s  .  com
            Address destination = Address.fromBase58(Main.params, address.getText());
            SendRequest req = null;

            if (amount.equals(Main.groestlcoin.wallet().getBalance())) {
                req = SendRequest.emptyWallet(destination);
            } else {
                req = SendRequest.to(destination, amount);
            }

            req.ensureMinRequiredFee = false;
            //converting because the UI uses sats/byte, so we need to convert that to fee per kb here
            req.feePerKb = Coin.valueOf(Long.parseLong(feeEdit.getText()) * 1000L);
            sendResult = Main.groestlcoin.wallet().sendCoins(Main.groestlcoin.peerGroup(), req);
            Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
                @Override
                public void onSuccess(Transaction result) {
                    checkGuiThread();
                    overlayUI.done();
                }

                @Override
                public void onFailure(Throwable t) {
                    // We died trying to empty the wallet.
                    crashAlert(t);
                }
            });
            sendResult.tx.getConfidence().addEventListener((tx, reason) -> {
            });
            sendBtn.setDisable(true);
            address.setDisable(true);
            ((HBox) amountEdit.getParent()).getChildren().remove(amountEdit);
            ((HBox) btcLabel.getParent()).getChildren().remove(btcLabel);
        } catch (InsufficientMoneyException e) {
            informationalAlert("Vortex Notification", "You do not have enough GRS for this transaction.");
            overlayUI.done();
        }
    }
}

From source file:io.crate.operation.join.CollectingPageableTaskIterable.java

@Override
public ListenableFuture<Void> fetchPage(PageInfo pageInfo) throws NoSuchElementException {
    this.pageInfo(pageInfo);

    final SettableFuture<Void> future = SettableFuture.create();
    Futures.addCallback(currentTaskResult.fetch(pageInfo), new FutureCallback<PageableTaskResult>() {
        @Override// www .  j  a  v  a 2s.  co  m
        public void onSuccess(@Nullable PageableTaskResult result) {
            if (result == null) {
                future.setException(new IllegalArgumentException("PageableTaskResult is null"));
            } else {
                pages.add(result.page());
                future.set(null);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}

From source file:org.apache.tez.dag.app.TezTestServiceCommunicator.java

public void runContainer(RunContainerRequestProto request, String host, int port,
        final ExecuteRequestCallback<RunContainerResponseProto> callback) {
    ListenableFuture<RunContainerResponseProto> future = executor
            .submit(new RunContainerCallable(request, host, port));
    Futures.addCallback(future, new FutureCallback<RunContainerResponseProto>() {
        @Override/*from w  w  w  . j a  v a  2 s.c om*/
        public void onSuccess(RunContainerResponseProto result) {
            callback.setResponse(result);
        }

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

}

From source file:org.opendaylight.vtn.manager.internal.flow.reader.FlowCountFuture.java

/**
 * Construct a new instance./*from  w  ww . j a  va 2 s  .c o  m*/
 *
 * @param ctx    A {@link TxContext} instance.
 * @param input  Input of the RPC call.
 * @throws RpcException  An error occurred.
 */
private FlowCountFuture(TxContext ctx, GetDataFlowCountInput input) throws RpcException {
    super(ctx, input.getTenantName());

    // Read the VTN flow table.
    LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL;
    InstanceIdentifier<VtnFlowTable> path = FlowUtils.getIdentifier(input.getTenantName());
    Futures.addCallback(ctx.getTransaction().read(oper, path), this);
}

From source file:io.baku.examples.distro.DistroActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FlutterMain.ensureInitializationComplete(getApplicationContext(), null);
    setContentView(R.layout.flutter_layout);

    flutterView = (FlutterView) findViewById(R.id.flutter_view);
    File appBundle = new File(PathUtils.getDataDirectory(this), FlutterMain.APP_BUNDLE);
    flutterView.runFromBundle(appBundle.getPath(), null);

    poller = new ScheduledThreadPoolExecutor(1);

    context = VAndroidContexts.withDefaults(this, savedInstanceState);

    Futures.addCallback(BlessingsManager.getBlessings(context.getVContext(), this, "blessings", true),
            new FutureCallback<Blessings>() {
                @Override//from   w  w w . j  ava2 s.com
                public void onSuccess(final Blessings blessings) {
                    onBlessingsAvailable(blessings);
                }

                @Override
                public void onFailure(final Throwable t) {
                    Log.e(TAG, "Unable to attain blessings", t);
                }
            });
}

From source file:org.opendaylight.bier.driver.common.util.DataWriter.java

public static <T extends DataObject> CheckedFuture<Void, TransactionCommitFailedException> operate(
        OperateType type, DataBroker dataBroker, final int tries, InstanceIdentifier<T> path, T data) {

    final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
    switch (type) {
    case CREATE:/*from  w w w  .  jav a  2s  . co m*/
    case REPLACE:
        writeTransaction.put(LogicalDatastoreType.CONFIGURATION, path, data, true);
        break;
    case MERGE:
        writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, path, data, true);
        break;
    case DELETE:
        writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, path);
        break;
    default:
        break;

    }

    final CheckedFuture<Void, TransactionCommitFailedException> submitResult = writeTransaction.submit();
    Futures.addCallback(submitResult, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
        }

        @Override
        public void onFailure(final Throwable throwable) {
            operateFail(throwable, type, dataBroker, path, data, tries);
        }
    });

    return submitResult;

}