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:com.google.monacoin.tools.WalletTool.java

private static void send(PaymentSession session) {
    try {/*  w  w w .j  a va 2 s  .co  m*/
        System.out.println("Payment Request");
        System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mMONA");
        System.out.println("Date: " + session.getDate());
        System.out.println("Memo: " + session.getMemo());
        if (session.pkiVerificationData != null) {
            System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name);
            if (session.pkiVerificationData.orgName != null)
                System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName);
            System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
        }
        final Wallet.SendRequest req = session.getSendRequest();
        if (password != null) {
            if (!wallet.checkPassword(password)) {
                System.err.println("Password is incorrect.");
                return;
            }
            req.aesKey = wallet.getKeyCrypter().deriveKey(password);
        }
        wallet.completeTx(req); // may throw InsufficientMoneyException.
        if (options.has("offline")) {
            wallet.commitTx(req.tx);
            return;
        }
        setup();
        // No refund address specified, no user-specified memo field.
        ListenableFuture<PaymentSession.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null, null);
        if (future == null) {
            // No payment_url for submission so, broadcast and wait.
            peers.startAndWait();
            peers.broadcastTransaction(req.tx).get();
        } else {
            PaymentSession.Ack ack = future.get();
            wallet.commitTx(req.tx);
            System.out.println("Memo from server: " + ack.getMemo());
        }
    } catch (PaymentRequestException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (VerificationException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (ExecutionException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Invalid payment " + e.getMessage());
        System.exit(1);
    } catch (InterruptedException e1) {
        // Ignore.
    } catch (InsufficientMoneyException e) {
        System.err
                .println("Insufficient funds: have " + Utils.bitcoinValueToFriendlyString(wallet.getBalance()));
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.defcoin.tools.WalletTool.java

private static void send(PaymentSession session) {
    try {// w ww  .  j  av a  2s.co  m
        System.out.println("Payment Request");
        System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mDOGE");
        System.out.println("Date: " + session.getDate());
        System.out.println("Memo: " + session.getMemo());
        if (session.pkiVerificationData != null) {
            System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name);
            if (session.pkiVerificationData.orgName != null)
                System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName);
            System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
        }
        final Wallet.SendRequest req = session.getSendRequest();
        if (password != null) {
            if (!wallet.checkPassword(password)) {
                System.err.println("Password is incorrect.");
                return;
            }
            req.aesKey = wallet.getKeyCrypter().deriveKey(password);
        }
        wallet.completeTx(req); // may throw InsufficientMoneyException.
        if (options.has("offline")) {
            wallet.commitTx(req.tx);
            return;
        }
        setup();
        // No refund address specified, no user-specified memo field.
        ListenableFuture<PaymentSession.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null, null);
        if (future == null) {
            // No payment_url for submission so, broadcast and wait.
            peers.startAndWait();
            peers.broadcastTransaction(req.tx).get();
        } else {
            PaymentSession.Ack ack = future.get();
            wallet.commitTx(req.tx);
            System.out.println("Memo from server: " + ack.getMemo());
        }
    } catch (PaymentRequestException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (VerificationException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (ExecutionException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Invalid payment " + e.getMessage());
        System.exit(1);
    } catch (InterruptedException e1) {
        // Ignore.
    } catch (InsufficientMoneyException e) {
        System.err
                .println("Insufficient funds: have " + Utils.bitcoinValueToFriendlyString(wallet.getBalance()));
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bushstar.kobocoinj.tools.WalletTool.java

private static void send(PaymentSession session) {
    try {/*from   w  w w. j a v  a2  s  . c o  m*/
        System.out.println("Payment Request");
        System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mBTC");
        System.out.println("Date: " + session.getDate());
        System.out.println("Memo: " + session.getMemo());
        if (session.pkiVerificationData != null) {
            System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name);
            if (session.pkiVerificationData.orgName != null)
                System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName);
            System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
        }
        final Wallet.SendRequest req = session.getSendRequest();
        if (password != null) {
            if (!wallet.checkPassword(password)) {
                System.err.println("Password is incorrect.");
                return;
            }
            req.aesKey = wallet.getKeyCrypter().deriveKey(password);
        }
        wallet.completeTx(req); // may throw InsufficientMoneyException.
        if (options.has("offline")) {
            wallet.commitTx(req.tx);
            return;
        }
        setup();
        // No refund address specified, no user-specified memo field.
        ListenableFuture<PaymentSession.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null, null);
        if (future == null) {
            // No payment_url for submission so, broadcast and wait.
            peers.startAndWait();
            peers.broadcastTransaction(req.tx).get();
        } else {
            PaymentSession.Ack ack = future.get();
            wallet.commitTx(req.tx);
            System.out.println("Memo from server: " + ack.getMemo());
        }
    } catch (PaymentRequestException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (VerificationException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (ExecutionException e) {
        System.err.println("Failed to send payment " + e.getMessage());
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Invalid payment " + e.getMessage());
        System.exit(1);
    } catch (InterruptedException e1) {
        // Ignore.
    } catch (InsufficientMoneyException e) {
        System.err.println(
                "Insufficient funds: have " + Utils.kobocoinValueToFriendlyString(wallet.getBalance()));
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.flipkart.hydra.task.entities.WrapperCallable.java

protected Object getResponsesForMap() throws Exception {
    Map iterable = (Map) loopVar;

    Map<Object, ListenableFuture<Object>> futureMap = new HashMap<>();
    for (Object i : iterable.keySet()) {
        ListenableFuture<Object> future = getFuture(i, iterable.get(i));
        futureMap.put(i, future);//  w ww .j a v a2  s .com
    }

    ListenableFuture<List<Object>> compositeFuture = Futures.allAsList(futureMap.values());
    compositeFuture.get();

    Map<Object, Object> responsesMap = new HashMap<>();
    for (Object i : iterable.keySet()) {
        responsesMap.put(i, futureMap.get(i).get());
    }

    return responsesMap;
}

From source file:com.flipkart.hydra.task.entities.WrapperCallable.java

protected Object getResponsesForList() throws Exception {
    List list = (List) loopVar;

    Map<Integer, ListenableFuture<Object>> futureMap = new HashMap<>();
    for (int i = 0; i < list.size(); i++) {
        ListenableFuture<Object> future = getFuture(i, list.get(i));
        futureMap.put(i, future);//from  w w w.ja  va 2  s. c o  m
    }

    ListenableFuture<List<Object>> compositeFuture = Futures.allAsList(futureMap.values());
    compositeFuture.get();

    List<Object> responsesList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        responsesList.add(futureMap.get(i));
    }

    return responsesList;
}

From source file:com.flipkart.hydra.task.entities.WrapperCallable.java

protected Object getResponsesForArray() throws Exception {
    Object[] arr = (Object[]) loopVar;

    Map<Integer, ListenableFuture<Object>> futureMap = new HashMap<>();
    for (int i = 0; i < arr.length; i++) {
        ListenableFuture<Object> future = getFuture(i, arr[i]);
        futureMap.put(i, future);// w  w  w.  ja va 2  s  .  co m
    }

    ListenableFuture<List<Object>> compositeFuture = Futures.allAsList(futureMap.values());
    compositeFuture.get();

    Object[] responsesArray = new Object[arr.length];
    for (int i = 0; i < arr.length; i++) {
        responsesArray[i] = futureMap.get(i);
    }

    return responsesArray;
}

From source file:co.cask.cdap.internal.app.runtime.batch.distributed.DistributedMapReduceTaskContextProvider.java

@Override
protected void startUp() throws Exception {
    super.startUp();
    try {//from  w  w  w.java 2 s  . c  om
        List<ListenableFuture<State>> startFutures = Services
                .chainStart(zkClientService, kafkaClientService, metricsCollectionService).get();
        // All services should be started
        for (ListenableFuture<State> future : startFutures) {
            Preconditions.checkState(future.get() == State.RUNNING,
                    "Failed to start services: zkClient %s, kafkaClient %s, metricsCollection %s",
                    zkClientService.state(), kafkaClientService.state(), metricsCollectionService.state());
        }
        logAppenderInitializer.initialize();
    } catch (Exception e) {
        // Try our best to stop services. Chain stop guarantees it will stop everything, even some of them failed.
        try {
            shutDown();
        } catch (Exception stopEx) {
            e.addSuppressed(stopEx);
        }
        throw e;
    }
}

From source file:utils.teamcity.wallt.controller.api.ApiMonitoringService.java

private Runnable checkQueuedBuildStatus() {
    return () -> {
        if (!isActive())
            return;

        try {/*  w  w w .  j a va2  s.c om*/
            final Instant before = Instant.now();
            ListenableFuture<Void> future = _apiController.requestQueuedBuilds();
            future.get();
            LOGGER.info("Checking queued builds: done in {} s",
                    Duration.between(before, Instant.now()).getSeconds());
        } catch (InterruptedException | ExecutionException ignored) {
        }
    };
}

From source file:org.trinity.shell.api.widget.BaseShellWidget.java

@Override
public DisplaySurface getDisplaySurfaceImpl() {
    final ListenableFuture<DisplaySurface> dsFuture = this.painter.getDislaySurface();

    DisplaySurface ds = null;//from  w  ww  . j  a  v  a2s. c o m
    try {
        ds = dsFuture.get();
    } catch (final InterruptedException e) {
        LOG.error("Interrupted while waiting for display surface from painter.", e);
    } catch (final ExecutionException e) {
        LOG.error("Error while waiting for display surface from painter.", e);
    }
    return ds;
}

From source file:org.apache.usergrid.management.export.S3ExportImpl.java

@Override
public void copyToS3(File ephemeral, final Map<String, Object> exportInfo, String filename) {

    fn = filename;//from  w  ww .j av a 2s  .  co  m

    Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);
    /*won't need any of the properties as I have the export info*/
    Map<String, Object> properties = (Map<String, Object>) exportInfo.get("properties");

    Map<String, Object> storage_info = (Map<String, Object>) properties.get("storage_info");

    String bucketName = (String) storage_info.get("bucket_location");
    String accessId = (String) storage_info.get("s3_access_id");
    String secretKey = (String) storage_info.get("s3_key");

    Properties overrides = new Properties();
    overrides.setProperty("s3" + ".identity", accessId);
    overrides.setProperty("s3" + ".credential", secretKey);

    final Iterable<? extends Module> MODULES = ImmutableSet.of(new JavaUrlHttpCommandExecutorServiceModule(),
            new Log4JLoggingModule(), new NettyPayloadModule());

    BlobStoreContext context = ContextBuilder.newBuilder("s3").credentials(accessId, secretKey).modules(MODULES)
            .overrides(overrides).buildView(BlobStoreContext.class);

    // Create Container (the bucket in s3)
    try {
        AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync
        // BlobStore (returns false if it already exists)
        ListenableFuture<Boolean> container = blobStore.createContainerInLocation(null, bucketName);
        if (container.get()) {
            logger.info("Created bucket " + bucketName);
        }
    } catch (Exception ex) {
        logger.error("Could not start binary service: {}", ex.getMessage());
        return;
    }

    try {
        AsyncBlobStore blobStore = context.getAsyncBlobStore();
        BlobBuilder blobBuilder = blobStore.blobBuilder(fn).payload(ephemeral).calculateMD5()
                .contentType("application/json");

        Blob blob = blobBuilder.build();

        ListenableFuture<String> futureETag = blobStore.putBlob(bucketName, blob,
                PutOptions.Builder.multipart());

        logger.info("Uploaded file etag=" + futureETag.get());
    } catch (Exception e) {
        logger.error("Error uploading to blob store", e);
    }
}