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.sha1coin.tools.WalletTool.java

private static void sendPaymentRequest(String location, boolean verifyPki) {
    if (location.startsWith("http") || location.startsWith("bitcoin")) {
        try {//from   w ww .  j  a  v a  2  s  . co  m
            ListenableFuture<PaymentSession> future;
            if (location.startsWith("http")) {
                future = PaymentSession.createFromUrl(location, verifyPki);
            } else {
                BitcoinURI paymentRequestURI = new BitcoinURI(location);
                future = PaymentSession.createFromBitcoinUri(paymentRequestURI, verifyPki);
            }
            PaymentSession session = future.get();
            if (session != null) {
                send(session);
            } else {
                System.err.println("Server returned null session");
                System.exit(1);
            }
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        } catch (BitcoinURIParseException e) {
            System.err.println("Invalid bitcoin uri: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            // Ignore.
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        // Try to open the payment request as a file.
        FileInputStream stream = null;
        try {
            File paymentRequestFile = new File(location);
            stream = new FileInputStream(paymentRequestFile);
        } catch (Exception e) {
            System.err.println("Failed to open file: " + e.getMessage());
            System.exit(1);
        }
        try {
            paymentRequest = org.bitcoin.protocols.payments.Protos.PaymentRequest.newBuilder().mergeFrom(stream)
                    .build();
        } catch (IOException e) {
            System.err.println("Failed to parse payment request from file " + e.getMessage());
            System.exit(1);
        }
        PaymentSession session = null;
        try {
            session = new PaymentSession(paymentRequest, verifyPki);
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        }
        send(session);
    }
}

From source file:io.airlift.drift.client.DriftInvocationHandler.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getDeclaringClass() == Object.class) {
        switch (method.getName()) {
        case "toString":
            return serviceName;
        case "equals":
            return Proxy.isProxyClass(args[0].getClass()) && (Proxy.getInvocationHandler(args[0]) == this);
        case "hashCode":
            return System.identityHashCode(this);
        }/*  ww w. jav a  2  s . c o  m*/
        throw new UnsupportedOperationException(method.getName());
    }

    if (args == null) {
        args = NO_ARGS;
    }

    if ((args.length == 0) && "close".equals(method.getName())) {
        return null;
    }

    DriftMethodHandler methodHandler = methods.get(method);

    try {
        if (methodHandler == null) {
            throw new TApplicationException(UNKNOWN_METHOD, "Unknown method: " + method);
        }

        ListenableFuture<Object> future = methodHandler.invoke(addressSelectionContext, headers, asList(args));

        if (methodHandler.isAsync()) {
            return unwrapUserException(future);
        }

        try {
            return future.get();
        } catch (ExecutionException e) {
            throw unwrapUserException(e.getCause());
        }
    } catch (Exception e) {
        // rethrow any exceptions declared to be thrown by the method
        boolean canThrowTException = false;
        for (Class<?> exceptionType : method.getExceptionTypes()) {
            if (exceptionType.isAssignableFrom(e.getClass())) {
                throw e;
            }
            canThrowTException = canThrowTException || exceptionType == TException.class;
        }

        if (e instanceof TApplicationException) {
            throw new UncheckedTApplicationException((TApplicationException) e);
        }

        if (e instanceof TProtocolException) {
            throw new UncheckedTProtocolException((TProtocolException) e);
        }

        if (e instanceof TTransportException) {
            throw new UncheckedTTransportException((TTransportException) e);
        }

        if (e instanceof TException) {
            throw new UncheckedTException((TException) e);
        }

        TException wrappedException;
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
            wrappedException = new TException("Thread interrupted", e);
        } else {
            wrappedException = new TException(e.getMessage(), e);
        }

        if (canThrowTException) {
            throw wrappedException;
        }
        throw new UncheckedTException(wrappedException);
    }
}

From source file:io.druid.query.GroupByMergedQueryRunner.java

private void waitForFutureCompletion(GroupByQuery query, ListenableFuture<?> future,
        IncrementalIndex<?> closeOnFailure) {
    try {//w  w  w  . j  a v  a2s.  c o m
        queryWatcher.registerQuery(query, future);
        final Number timeout = query.getContextValue(QueryContextKeys.TIMEOUT, (Number) null);
        if (timeout == null) {
            future.get();
        } else {
            future.get(timeout.longValue(), TimeUnit.MILLISECONDS);
        }
    } catch (InterruptedException e) {
        log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId());
        future.cancel(true);
        closeOnFailure.close();
        throw new QueryInterruptedException(e);
    } catch (CancellationException e) {
        closeOnFailure.close();
        throw new QueryInterruptedException(e);
    } catch (TimeoutException e) {
        closeOnFailure.close();
        log.info("Query timeout, cancelling pending results for query id [%s]", query.getId());
        future.cancel(true);
        throw new QueryInterruptedException(e);
    } catch (ExecutionException e) {
        closeOnFailure.close();
        throw Throwables.propagate(e.getCause());
    }
}

From source file:com.dtolabs.rundeck.core.rules.WorkflowEngineOperationsProcessor.java

private void awaitFutures() {
    if (!inProcess.isEmpty()) {
        for (ListenableFuture<RES> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException | CancellationException ignored) {

            }/*from  www  . ja  va 2s  .co  m*/
        }
    }
}

From source file:zipkin.storage.cassandra.DeduplicatingExecutor.java

/**
 * Upon success, the statement's result will be remembered and returned for all subsequent
 * executions with the same key, subject to a local TTL.
 *
 * <p>The results of failed statements are forgotten based on the supplied key.
 *
 * @param statement what to conditionally execute
 * @param key determines equivalence of the bound statement
 * @return future of work initiated by this or a previous request
 *//*w w w. j  a  v a2  s.  com*/
ListenableFuture<Void> maybeExecuteAsync(BoundStatement statement, Object key) {
    BoundStatementKey cacheKey = new BoundStatementKey(statement, key);
    try {
        ListenableFuture<Void> result = cache.get(new BoundStatementKey(statement, key));
        // A future could be constructed directly (i.e. immediate future), get the value to
        // see if it was exceptional. If so, the catch block will invalidate that key.
        if (result.isDone())
            result.get();
        return result;
    } catch (UncheckedExecutionException | ExecutionException e) {
        cache.invalidate(cacheKey);
        return Futures.immediateFailedFuture(e.getCause());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new AssertionError();
    }
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleTransaction.java

@Override
public CompositeNode readOperationalData(final YangInstanceIdentifier legacyPath) {
    YangInstanceIdentifier normalizedPath = normalizer.toNormalized(legacyPath);

    ListenableFuture<Optional<NormalizedNode<?, ?>>> normalizedData = asyncTx
            .read(LogicalDatastoreType.OPERATIONAL, normalizedPath);

    try {/*from w  w w.j a  v  a2s. c o m*/
        return normalizer.toLegacy(normalizedPath, normalizedData.get().orNull());
    } catch (InterruptedException | ExecutionException e) {
        return null;
    }
}

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

@Override
public void readBlob(final String blobName, final ReadBlobListener listener) {
    final ListenableFuture<? extends Blob> future = cloudBlobStore.async().getBlob(cloudBlobStore.container(),
            buildBlobPath(blobName));/* w w  w .j ava 2  s .c o  m*/
    future.addListener(new Runnable() {
        @Override
        public void run() {
            Blob blob;
            try {
                blob = future.get();
                if (blob == null) {
                    listener.onFailure(
                            new BlobStoreException("No blob found for [" + buildBlobPath(blobName) + "]"));
                    return;
                }
            } catch (InterruptedException e) {
                listener.onFailure(e);
                return;
            } catch (ExecutionException e) {
                listener.onFailure(e.getCause());
                return;
            }
            byte[] buffer = new byte[cloudBlobStore.bufferSizeInBytes()];
            InputStream is = blob.getPayload().getInput();
            try {
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    listener.onPartial(buffer, 0, bytesRead);
                }
                listener.onCompleted();
            } catch (Exception e) {
                try {
                    is.close();
                } catch (IOException e1) {
                    // ignore
                }
                listener.onFailure(e);
            }
        }
    }, cloudBlobStore.executor());
}

From source file:com.dogecoin.dogecoinj.tools.WalletTool.java

private static void send(PaymentSession session) {
    try {//  w w  w. j ava  2 s .  c  o m
        System.out.println("Payment Request");
        System.out.println("Coin: " + session.getValue().toFriendlyString());
        System.out.println("Date: " + session.getDate());
        System.out.println("Memo: " + session.getMemo());
        if (session.pkiVerificationData != null) {
            System.out.println("Pki-Verified Name: " + session.pkiVerificationData.displayName);
            System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
        }
        final Wallet.SendRequest req = session.getSendRequest();
        if (password != null) {
            req.aesKey = passwordToKey(true);
            if (req.aesKey == null)
                return; // Error message already printed.
        }
        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<PaymentProtocol.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null,
                null);
        if (future == null) {
            // No payment_url for submission so, broadcast and wait.
            peers.start();
            peers.broadcastTransaction(req.tx).get();
        } else {
            PaymentProtocol.Ack ack = future.get();
            wallet.commitTx(req.tx);
            System.out.println("Memo from server: " + ack.getMemo());
        }
    } catch (PaymentProtocolException 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 " + wallet.getBalance().toFriendlyString());
    } catch (BlockStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleTransaction.java

@Override
public CompositeNode readConfigurationData(final YangInstanceIdentifier legacyPath) {

    YangInstanceIdentifier normalizedPath = normalizer.toNormalized(legacyPath);

    ListenableFuture<Optional<NormalizedNode<?, ?>>> normalizedData = asyncTx
            .read(LogicalDatastoreType.CONFIGURATION, normalizedPath);

    try {//w  ww  .j av  a2  s.com
        return normalizer.toLegacy(normalizedPath, normalizedData.get().orNull());
    } catch (InterruptedException | ExecutionException e) {
        return null;
    }
}

From source file:com.jivesoftware.os.tasmo.lib.process.traversal.InitiateTraversal.java

private void commitChanges(WrittenEventContext writtenEventContext, TenantIdAndCentricId tenantIdAndCentricId,
        List<ListenableFuture<List<ViewFieldChange>>> futures)
        throws InterruptedException, ExecutionException, CommitChangeException {
    ListenableFuture<List<List<ViewFieldChange>>> allAsList = Futures.allAsList(futures);
    List<ViewFieldChange> writeableChanges = new ArrayList<>();
    for (List<ViewFieldChange> changes : allAsList.get()) {
        writeableChanges.addAll(changes);
    }/*ww w  .  j a v  a  2s. c o m*/
    writtenEventContext.getCommitChange().commitChange(writtenEventContext, tenantIdAndCentricId,
            writeableChanges);
}