Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListenableFuture get.

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:org.elasticsearch.cloud.blobstore.CloudImmutableBlobContainer.java

@Override
public void writeBlob(String blobName, InputStream is, long sizeInBytes, final WriterListener listener) {
    BlobBuilder blob = cloudBlobStore.async().blobBuilder(buildBlobPath(blobName)).payload(is)
            .contentLength(sizeInBytes);
    final ListenableFuture<String> future = cloudBlobStore.async().putBlob(cloudBlobStore.container(),
            blob.build());/*from   ww w .ja  v a2  s.c  o  m*/
    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                future.get();
                listener.onCompleted();
            } catch (InterruptedException e) {
                listener.onFailure(e);
            } catch (ExecutionException e) {
                listener.onFailure(e.getCause());
            } catch (Throwable t) {
                listener.onFailure(t);
            }
        }
    }, cloudBlobStore.executor());
}

From source file:com.rbmhtechnology.example.japi.querydb.Writer.java

private <T> CompletableFuture<T> toCompletableFuture(final ListenableFuture<T> listenableFuture,
        final Executor executor) {
    final CompletableFuture<T> ft = new CompletableFuture<>();
    listenableFuture.addListener(() -> {
        try {/*from w ww  .  ja v  a  2  s.com*/
            ft.complete(listenableFuture.get());
        } catch (Throwable e) {
            ft.completeExceptionally(e);
        }
    }, executor);

    return ft;
}

From source file:io.bitsafe.examplewallet.bitcoin.BitcoinJInterface.java

/** Create, sign, commit and broadcast a transaction which spends to
 * multiple recipients.//  w  ww  . j  a v  a2s . c  o  m
 * @param recipients Who to send to
 * @param allowUnconfirmedSpend Whether to allow spending unconfirmed outputs
 * @param signer External transaction signer (can be null)
 * @throws AddressFormatException 
 * @throws InsufficientMoneyException 
 * @throws InterruptedException 
 * @throws ExecutionException 
 */
public void sendMulti(SendRecipient[] recipients, boolean allowUnconfirmedSpend, TransactionSigner signer)
        throws AddressFormatException, InsufficientMoneyException, InterruptedException, ExecutionException {
    // Create empty send request.
    Transaction tx = new Transaction(params);
    Wallet.SendRequest req = Wallet.SendRequest.forTx(tx);
    // Populate output list with recipients.
    Address addr;
    for (SendRecipient recipient : recipients) {
        addr = new Address(params, recipient.getAddress());
        tx.addOutput(recipient.getAmount(), addr);
    }
    // Always generate a new change address.
    req.changeAddress = addressGenerator.generateNewKey().toAddress(params);
    // Complete transaction by adding inputs, a change output and fees.
    CoinSelector oldSelector = vWallet.getCoinSelector();
    if (allowUnconfirmedSpend) {
        vWallet.allowSpendingUnconfirmedTransactions();
    }
    vWallet.completeTx(req);
    boolean discardTransaction = false;
    if (signer != null) {
        discardTransaction = !signer.signTransaction(req.tx, vWallet);
    }

    if (!discardTransaction) {
        vWallet.commitTx(req.tx);
        vWallet.setCoinSelector(oldSelector);
        // Broadcast the transaction.
        ListenableFuture<Transaction> future = vPeerGroup.broadcastTransaction(req.tx);
        future.get();
    }
}

From source file:org.opendaylight.controller.frm.reconil.FlowNodeReconcilListener.java

private Optional<FlowCapableNode> readFlowCapableNode(final InstanceIdentifier<FlowCapableNode> flowNodeIdent) {
    ReadOnlyTransaction readTrans = this.provider.getDataService().newReadOnlyTransaction();
    try {/*from  ww w.  j a v a 2s.com*/
        ListenableFuture<Optional<FlowCapableNode>> confFlowNode = readTrans
                .read(LogicalDatastoreType.CONFIGURATION, flowNodeIdent);
        if (confFlowNode.get().isPresent()) {
            return Optional.<FlowCapableNode>of(confFlowNode.get().get());
        } else {
            return Optional.absent();
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Unexpected exception by reading flow ".concat(flowNodeIdent.toString()), e);
        return Optional.absent();
    } finally {
        readTrans.close();
    }
}

From source file:com.github.trask.sandbox.executors.RetryingCommandWrapper.java

public void run() {
    if (startTimeMillis == 0) {
        // mark the start time of the first attempt
        startTimeMillis = System.currentTimeMillis();
    }//  w ww  .  j  a va  2  s  . c o m
    try {
        final ListenableFuture<E> future = command.execute();
        future.addListener(new Runnable() {
            public void run() {
                try {
                    E result = future.get();
                    handleResult(result);
                } catch (InterruptedException e) {
                    // we've been interrupted, presumably for a good reason (e.g. shutdown)
                    // so we terminate this command
                } catch (ExecutionException e) {
                    handleAsyncException(e.getCause());
                }
            }
        }, executorService);
    } catch (FailButResetBackoffException e) {
        resetBackoffAndReExecuteImmediately();
    } catch (FailAndBackoffException e) {
        rescheduleWithBackoff();
    } catch (AbortException e) {
        // do nothing and allow thread to terminate
    }
}

From source file:org.opendaylight.topomanager.impl.BierTopologyAdapter.java

public Topology getInitTopology(DataBroker dataBroker, String topologyId) {
    BierTopologyProcess<Topology> processor = new BierTopologyProcess<Topology>(dataBroker,
            BierTopologyProcess.FLAG_READ, (new TopologyBuilder()).build());

    final InstanceIdentifier<Topology> path = InstanceIdentifier.create(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(new TopologyId(topologyId)));
    if (!isTopologyExist(dataBroker, path)) {
        return null;
    }/*from w ww.  j  a  v  a  2  s. co m*/

    processor.enqueueOperation(new BierTopologyOperation() {
        @Override
        public void writeOperation(ReadWriteTransaction transaction) {
            // Auto-generated method stub
        }

        @SuppressWarnings("unchecked")
        @Override
        public ListenableFuture<Optional<Topology>> readOperation(ReadWriteTransaction transaction) {

            ListenableFuture<Optional<Topology>> listenableFuture = transaction
                    .read(LogicalDatastoreType.OPERATIONAL, path);

            return listenableFuture;
        }
    });

    Future<ListenableFuture<Topology>> future = executor.submit(processor);

    try {
        ListenableFuture<Topology> result = future.get();
        Topology topology = result.get();
        if (null == topology || null == topology.getTopologyId()) {
            LOG.error("Get topology is faild!");
            return null;
        }
        return topology;
    } catch (InterruptedException e) {
        LOG.error("Get topology is Interrupted by", e);
    } catch (ExecutionException e) {
        LOG.error("Get topology is faild cause by", e);
    }
    LOG.error("Get topology is faild!");
    return null;
}

From source file:com.linecorp.platform.channel.sample.BusinessConnect.java

public void sendTextMessage(List<String> toUsers, String message, ApiHttpClient apiHttpClient) {
    OutgoingMessage outgoingMessage = new OutgoingMessage();
    outgoingMessage.setTo(toUsers);//from  ww w . j ava2  s.  com
    outgoingMessage.setToChannel(Constants.ToChannel.MESSAGE);
    outgoingMessage.setEventType(Constants.EventType.OUTGOING_MESSAGE);
    MessageContent messageContent = new MessageContent();
    messageContent.setContentType(Constants.ContentType.TEXT);
    messageContent.setToType(Constants.ToType.USER);
    messageContent.setText(message);
    outgoingMessage.setContent(messageContent);

    ListenableFuture<ApiResponse> apiListenableFuture = apiHttpClient.sendMessage(API_URL_EVENTS,
            outgoingMessage);
    if (apiListenableFuture != null) {
        try {
            ApiResponse apiResponse = apiListenableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.beam.runners.core.construction.ArtifactServiceStager.java

private void stageManifest(ListenableFuture<StagingResult> stagingFuture) throws InterruptedException {
    try {//from  ww w  . j  a v a 2  s  .c om
        StagingResult stagingResult = stagingFuture.get();
        if (stagingResult.isSuccess()) {
            Manifest manifest = Manifest.newBuilder().addAllArtifact(stagingResult.getMetadata()).build();
            blockingStub.commitManifest(CommitManifestRequest.newBuilder().setManifest(manifest).build());
        } else {
            RuntimeException failure = new RuntimeException(String.format("Failed to stage %s files: %s",
                    stagingResult.getFailures().size(), stagingResult.getFailures().keySet()));
            for (Throwable t : stagingResult.getFailures().values()) {
                failure.addSuppressed(t);
            }
            throw failure;
        }
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.examples.rackspace.cloudfiles.UploadDirectoryToCDN.java

/**
 * Upload the files in parallel./*from  ww w  .ja  v a  2  s  .  c o  m*/
 */
private void uploadFiles(String container, List<BlobDetail> blobDetails)
        throws InterruptedException, ExecutionException {
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(newFixedThreadPool(THREADS));
    List<ListenableFuture<BlobDetail>> blobUploaderFutures = Lists.newArrayList();
    BlobUploaderCallback blobUploaderCallback = new BlobUploaderCallback();

    try {

        for (BlobDetail blobDetail : blobDetails) {
            BlobUploader blobUploader = new BlobUploader(container, blobDetail);
            ListenableFuture<BlobDetail> blobDetailFuture = executor.submit(blobUploader);
            blobUploaderFutures.add(blobDetailFuture);

            Futures.addCallback(blobDetailFuture, blobUploaderCallback);
        }

        ListenableFuture<List<BlobDetail>> future = Futures.successfulAsList(blobUploaderFutures);
        List<BlobDetail> uploadedBlobDetails = future.get(); // begin the upload

        System.out.format("%n");

        for (int i = 0; i < uploadedBlobDetails.size(); i++) {
            if (uploadedBlobDetails.get(i) != null) {
                BlobDetail blobDetail = uploadedBlobDetails.get(i);
                System.out.format("  %s (eTag: %s)%n", blobDetail.getRemoteBlobName(), blobDetail.getETag());
            } else {
                System.out.format(" %s (ERROR)%n", blobDetails.get(i).getLocalFile().getAbsolutePath());
            }
        }
    } finally {
        executor.shutdown();
    }
}

From source file:org.flinkspector.core.runtime.Runner.java

/**
 * Starts the test execution.//from   w  ww . j  a  va2 s. co  m
 * Collects the results from sockets after
 * the cluster has terminated.
 *
 * @throws Throwable any Exception that has occurred
 *                   during validation the test.
 */
public void executeTest() throws Throwable {
    stopTimer.schedule(stopExecution, timeout);
    try {
        executeEnvironment();
    } catch (IllegalStateException | JobExecutionException e) {
        //cluster has been shutdown forcefully, most likely by at timeout.
        if (!stopped.get()) {
            stopped.set(true);
            subscribers.close();
        }
    }

    //====================
    // collect failures
    //====================
    for (ListenableFuture future : listenerFutures) {
        try {
            future.get();
        } catch (ExecutionException e) {
            //check if it is a FlinkTestFailedException
            if (e.getCause() instanceof FlinkTestFailedException) {
                //unwrap exception
                throw e.getCause().getCause();
            }
            if (!stopped.get()) {
                throw e.getCause();
            }
        }
    }
    Thread.sleep(50);
    if (!stopped.get()) {
        subscribers.close();
    }
    stopTimer.cancel();
    stopTimer.purge();
}