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(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:org.multibit.network.MultiBitService.java

/**
 * Send bitcoins from the active wallet.
 *
 * @return The sent transaction (may be null if there were insufficient
 *         funds for send)//  ww  w . jav a 2s.c o  m
 * @throws KeyCrypterException
 * @throws IOException
 * @throws AddressFormatException
 */

public Transaction sendCoins(WalletData perWalletModelData, SendRequest sendRequest, CharSequence password)
        throws java.io.IOException, AddressFormatException, KeyCrypterException {

    // Ping the peers to check the uro network connection
    List<Peer> connectedPeers = peerGroup.getConnectedPeers();
    boolean atLeastOnePingWorked = false;
    if (connectedPeers != null) {
        for (Peer peer : connectedPeers) {

            log.debug("Ping: {}", peer.getAddress().toString());

            try {
                ListenableFuture<Long> result = peer.ping();
                result.get(4, TimeUnit.SECONDS);
                atLeastOnePingWorked = true;
                break;
            } catch (ProtocolException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (InterruptedException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (ExecutionException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (TimeoutException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            }
        }
    }

    if (!atLeastOnePingWorked) {
        throw new IllegalStateException("All peers failed ping test (check network)");
    }

    // Send the coins

    log.debug("MultiBitService#sendCoins - Just about to send coins");
    KeyParameter aesKey = null;
    if (perWalletModelData.getWallet().getEncryptionType() != EncryptionType.UNENCRYPTED) {
        aesKey = perWalletModelData.getWallet().getKeyCrypter().deriveKey(password);
    }
    sendRequest.aesKey = aesKey;
    sendRequest.fee = BigInteger.ZERO;
    sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

    sendRequest.tx.getConfidence().addEventListener(perWalletModelData.getWallet().getTxConfidenceListener());

    try {
        // The transaction is already added to the wallet (in SendBitcoinConfirmAction) so here we just need
        // to sign it, commit it and broadcast it.
        perWalletModelData.getWallet().sign(sendRequest);
        perWalletModelData.getWallet().commitTx(sendRequest.tx);

        // The tx has been committed to the pending pool by this point (via sendCoinsOffline -> commitTx), so it has
        // a txConfidenceListener registered. Once the tx is broadcast the peers will update the memory pool with the
        // count of seen peers, the memory pool will update the transaction confidence object, that will invoke the
        // txConfidenceListener which will in turn invoke the wallets event listener onTransactionConfidenceChanged
        // method.
        peerGroup.broadcastTransaction(sendRequest.tx);

        log.debug("Sending transaction '" + Utils.bytesToHexString(sendRequest.tx.bitcoinSerialize()) + "'");
    } catch (VerificationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Transaction sendTransaction = sendRequest.tx;

    log.debug("MultiBitService#sendCoins - Sent coins has completed");

    assert sendTransaction != null;
    // We should never try to send more coins than we have!
    // throw an exception if sendTransaction is null - no money.
    if (sendTransaction != null) {
        log.debug("MultiBitService#sendCoins - Sent coins. Transaction hash is {}",
                sendTransaction.getHashAsString() + ", identityHashcode = "
                        + System.identityHashCode(sendTransaction));

        if (sendTransaction.getConfidence() != null) {
            log.debug("Added bitcoinController " + System.identityHashCode(bitcoinController)
                    + " as listener to tx = " + sendTransaction.getHashAsString());
            sendTransaction.getConfidence().addEventListener(bitcoinController);
        } else {
            log.debug("Cannot add bitcoinController as listener to tx = " + sendTransaction.getHashAsString()
                    + " no transactionConfidence");
        }

        try {
            bitcoinController.getFileHandler().savePerWalletModelData(perWalletModelData, false);
        } catch (WalletSaveException wse) {
            log.error(wse.getClass().getCanonicalName() + " " + wse.getMessage());
            MessageManager.INSTANCE
                    .addMessage(new Message(wse.getClass().getCanonicalName() + " " + wse.getMessage()));
        } catch (WalletVersionException wse) {
            log.error(wse.getClass().getCanonicalName() + " " + wse.getMessage());
            MessageManager.INSTANCE
                    .addMessage(new Message(wse.getClass().getCanonicalName() + " " + wse.getMessage()));
        }

        try {
            // Notify other wallets of the send (it might be a send to or from them).
            List<WalletData> perWalletModelDataList = bitcoinController.getModel().getPerWalletModelDataList();

            if (perWalletModelDataList != null) {
                for (WalletData loopPerWalletModelData : perWalletModelDataList) {
                    if (!perWalletModelData.getWalletFilename()
                            .equals(loopPerWalletModelData.getWalletFilename())) {
                        Wallet loopWallet = loopPerWalletModelData.getWallet();
                        if (loopWallet.isPendingTransactionRelevant(sendTransaction)) {
                            // The loopPerWalletModelData is marked as dirty.
                            if (loopPerWalletModelData.getWalletInfo() != null) {
                                synchronized (loopPerWalletModelData.getWalletInfo()) {
                                    loopPerWalletModelData.setDirty(true);
                                }
                            } else {
                                loopPerWalletModelData.setDirty(true);
                            }
                            if (loopWallet.getTransaction(sendTransaction.getHash()) == null) {
                                log.debug("MultiBit adding a new pending transaction for the wallet '"
                                        + loopPerWalletModelData.getWalletDescription() + "'\n"
                                        + sendTransaction.toString());
                                loopWallet.receivePending(sendTransaction, null);
                            }
                        }
                    }
                }
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (VerificationException e) {
            e.printStackTrace();
        }
    }
    return sendTransaction;
}

From source file:org.wallet.network.WorldcoinWalletService.java

/**
 * Send worldcoins from the active wallet.
 *
 * @return The sent transaction (may be null if there were insufficient
 *         funds for send)//from w  ww.  j a  va2s .c o  m
 * @throws KeyCrypterException
 * @throws IOException
 * @throws AddressFormatException
 */

public Transaction sendCoins(WalletData perWalletModelData, SendRequest sendRequest, CharSequence password)
        throws java.io.IOException, AddressFormatException, KeyCrypterException {

    // Ping the peers to check the worldcoin network connection
    List<Peer> connectedPeers = peerGroup.getConnectedPeers();
    boolean atLeastOnePingWorked = false;
    if (connectedPeers != null) {
        for (Peer peer : connectedPeers) {

            log.debug("Ping: {}", peer.getAddress().toString());

            try {

                ListenableFuture<Long> result = peer.ping();
                result.get(4, TimeUnit.SECONDS);
                atLeastOnePingWorked = true;
                break;
            } catch (ProtocolException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (InterruptedException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (ExecutionException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            } catch (TimeoutException e) {
                log.warn("Peer '" + peer.getAddress().toString() + "' failed ping test. Message was "
                        + e.getMessage());
            }
        }
    }

    if (!atLeastOnePingWorked) {
        throw new IllegalStateException("All peers failed ping test (check network)");
    }

    // Send the coins

    log.debug("WorldcoinWalletService#sendCoins - Just about to send coins");
    KeyParameter aesKey = null;
    if (perWalletModelData.getWallet().getEncryptionType() != EncryptionType.UNENCRYPTED) {
        aesKey = perWalletModelData.getWallet().getKeyCrypter().deriveKey(password);
    }
    sendRequest.aesKey = aesKey;
    sendRequest.fee = BigInteger.ZERO;
    sendRequest.feePerKb = WorldcoinModel.SEND_FEE_PER_KB_DEFAULT;

    sendRequest.tx.getConfidence().addEventListener(perWalletModelData.getWallet().getTxConfidenceListener());

    try {
        // The transaction is already added to the wallet (in SendWorldcoinConfirmAction) so here we just need
        // to sign it, commit it and broadcast it.
        perWalletModelData.getWallet().sign(sendRequest);
        perWalletModelData.getWallet().commitTx(sendRequest.tx);

        // The tx has been committed to the pending pool by this point (via sendCoinsOffline -> commitTx), so it has
        // a txConfidenceListener registered. Once the tx is broadcast the peers will update the memory pool with the
        // count of seen peers, the memory pool will update the transaction confidence object, that will invoke the
        // txConfidenceListener which will in turn invoke the wallets event listener onTransactionConfidenceChanged
        // method.
        peerGroup.broadcastTransaction(sendRequest.tx);

        log.debug("Sending transaction '" + Utils.bytesToHexString(sendRequest.tx.worldcoinSerialize()) + "'");
    } catch (VerificationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Transaction sendTransaction = sendRequest.tx;

    log.debug("WorldcoinWalletService#sendCoins - Sent coins has completed");

    assert sendTransaction != null;
    // We should never try to send more coins than we have!
    // throw an exception if sendTransaction is null - no money.
    if (sendTransaction != null) {
        log.debug("WorldcoinWalletService#sendCoins - Sent coins. Transaction hash is {}",
                sendTransaction.getHashAsString() + ", identityHashcode = "
                        + System.identityHashCode(sendTransaction));

        if (sendTransaction.getConfidence() != null) {
            log.debug("Added worldcoinController " + System.identityHashCode(worldcoinController)
                    + " as listener to tx = " + sendTransaction.getHashAsString());
            sendTransaction.getConfidence().addEventListener(worldcoinController);
        } else {
            log.debug("Cannot add worldcoinController as listener to tx = " + sendTransaction.getHashAsString()
                    + " no transactionConfidence");
        }

        try {
            worldcoinController.getFileHandler().savePerWalletModelData(perWalletModelData, false);
        } catch (WalletSaveException wse) {
            log.error(wse.getClass().getCanonicalName() + " " + wse.getMessage());
            MessageManager.INSTANCE
                    .addMessage(new Message(wse.getClass().getCanonicalName() + " " + wse.getMessage()));
        } catch (WalletVersionException wse) {
            log.error(wse.getClass().getCanonicalName() + " " + wse.getMessage());
            MessageManager.INSTANCE
                    .addMessage(new Message(wse.getClass().getCanonicalName() + " " + wse.getMessage()));
        }

        try {
            // Notify other wallets of the send (it might be a send to or from them).
            List<WalletData> perWalletModelDataList = worldcoinController.getModel()
                    .getPerWalletModelDataList();

            if (perWalletModelDataList != null) {
                for (WalletData loopPerWalletModelData : perWalletModelDataList) {
                    if (!perWalletModelData.getWalletFilename()
                            .equals(loopPerWalletModelData.getWalletFilename())) {
                        com.google.worldcoin.core.Wallet loopWallet = loopPerWalletModelData.getWallet();
                        if (loopWallet.isPendingTransactionRelevant(sendTransaction)) {
                            // The loopPerWalletModelData is marked as dirty.
                            if (loopPerWalletModelData.getWalletInfo() != null) {
                                synchronized (loopPerWalletModelData.getWalletInfo()) {
                                    loopPerWalletModelData.setDirty(true);
                                }
                            } else {
                                loopPerWalletModelData.setDirty(true);
                            }
                            if (loopWallet.getTransaction(sendTransaction.getHash()) == null) {
                                log.debug("WorldcoinWallet adding a new pending transaction for the wallet '"
                                        + loopPerWalletModelData.getWalletDescription() + "'\n"
                                        + sendTransaction.toString());
                                loopWallet.receivePending(sendTransaction, null);
                            }
                        }
                    }
                }
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (VerificationException e) {
            e.printStackTrace();
        }
    }
    return sendTransaction;
}

From source file:bio.gcat.batch.Batch.java

public ListenableFuture<Result> execute(Collection<Tuple> tuples) {
    final Result result = new Result(tuples);
    Queue<Action> queue = new LinkedList<>(actions);
    if (queue.isEmpty())
        return new DefiniteListenableFuture<>(result);

    Action action;/*from  w  w w  .  jav  a2s  .c  o  m*/
    Future<Collection<Tuple>> future = new DefiniteFuture<>(tuples);
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    while ((action = queue.poll()) != null)
        future = service.submit(InjectionLogger.injectLogger(result, action.new Task(future)));

    final ListenableFuture<Collection<Tuple>> lastFuture = (ListenableFuture<Collection<Tuple>>) future;
    return new ListenableFuture<Result>() {
        @Override
        public boolean isDone() {
            return lastFuture.isDone();
        }

        @Override
        public boolean isCancelled() {
            return lastFuture.isCancelled();
        }

        @Override
        public Result get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            result.setTuples(lastFuture.get(timeout, unit));
            return result;
        }

        @Override
        public Result get() throws InterruptedException, ExecutionException {
            result.setTuples(lastFuture.get());
            return result;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return lastFuture.cancel(mayInterruptIfRunning);
        }

        @Override
        public void addListener(Runnable listener, Executor executor) {
            lastFuture.addListener(listener, executor);
        }
    };
}

From source file:com.vangav.backend.cassandra.Cassandra.java

/**
 * waitForFutures//from   w ww .  ja  v a 2 s.c om
 * used when multiple sync operations are being processed, they get processed
 *   asynchronously then blocks till results are returned as a more efficient
 *   way than blocking for each process to complete sequentially
 * @param listenableFutures
 * @return An array list with future results
 * @throws Exception
 */
private <T, P extends ListenableFuture<T>> ArrayList<T> waitForFutures(ArrayList<P> listenableFutures)
        throws Exception {

    ArgumentsInl.checkNotNull("Listenable futures", listenableFutures, ExceptionType.CODE_EXCEPTION);

    ArrayList<T> result = new ArrayList<T>();

    for (ListenableFuture<T> listenableFuture : listenableFutures) {

        for (int i = 0; i < this.queryRetries; i++) {

            try {

                if (healthCount.get() > kMinHealth) {

                    healthCount.decrementAndGet();
                }

                result.add((T) listenableFuture.get(kDefaultTimeout, kDefaultTimeunit));

                break;
            } catch (NoHostAvailableException nhae) {

                try {

                    if (reconnectFlag.get() == false) {

                        synchronized (mutex) {

                            if (healthCount.incrementAndGet() >= kHealthThreshold) {

                                this.reconnect();

                                healthCount.set(kMinHealth);
                            }
                        }
                    }
                } catch (Exception e) {

                    if (i == (this.queryRetries - 1)) {

                        throw e;
                    }
                }
            } catch (Exception e) {

                if (i == (this.queryRetries - 1)) {

                    throw e;
                }
            }
        }
    }

    return result;
}

From source file:org.apache.druid.query.groupby.epinephelinae.ConcurrentGrouper.java

private List<CloseableIterator<Entry<KeyType>>> parallelSortAndGetGroupersIterator() {
    // The number of groupers is same with the number of processing threads in the executor
    final ListenableFuture<List<CloseableIterator<Entry<KeyType>>>> future = Futures
            .allAsList(groupers.stream().map(grouper -> executor
                    .submit(new AbstractPrioritizedCallable<CloseableIterator<Entry<KeyType>>>(priority) {
                        @Override
                        public CloseableIterator<Entry<KeyType>> call() {
                            return grouper.iterator(true);
                        }/* w w  w  . j a  v a2s .  c  o m*/
                    })).collect(Collectors.toList()));

    try {
        final long timeout = queryTimeoutAt - System.currentTimeMillis();
        return hasQueryTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get();
    } catch (InterruptedException | TimeoutException e) {
        future.cancel(true);
        throw new QueryInterruptedException(e);
    } catch (CancellationException e) {
        throw new QueryInterruptedException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e.getCause());
    }
}

From source file:org.apache.druid.server.lookup.cache.LookupCoordinatorManager.java

@VisibleForTesting
void lookupManagementLoop() {
    // Sanity check for if we are shutting down
    if (Thread.currentThread().isInterrupted() || !lifecycleLock.awaitStarted(15, TimeUnit.SECONDS)) {
        LOG.info("Not updating lookups because process was interrupted or not finished starting yet.");
        return;//  w  w w . j  a v  a2 s  .c o  m
    }

    final Map<String, Map<String, LookupExtractorFactoryMapContainer>> allLookupTiers = lookupMapConfigRef
            .get();

    if (allLookupTiers == null) {
        LOG.info("Not updating lookups because no data exists");
        return;
    }

    LOG.debug("Starting lookup sync for on all nodes.");

    try {
        List<ListenableFuture<Map.Entry>> futures = new ArrayList<>();
        for (Map.Entry<String, Map<String, LookupExtractorFactoryMapContainer>> tierEntry : allLookupTiers
                .entrySet()) {

            LOG.debug("Starting lookup mgmt for tier [%s].", tierEntry.getKey());

            final Map<String, LookupExtractorFactoryMapContainer> tierLookups = tierEntry.getValue();
            for (final HostAndPortWithScheme node : lookupNodeDiscovery.getNodesInTier(tierEntry.getKey())) {

                LOG.debug("Starting lookup mgmt for tier [%s] and host [%s:%s:%s].", tierEntry.getKey(),
                        node.getScheme(), node.getHostText(), node.getPort());

                futures.add(executorService.submit(() -> {
                    try {
                        return new AbstractMap.SimpleImmutableEntry<>(node.getHostAndPort(),
                                doLookupManagementOnNode(node, tierLookups));
                    } catch (InterruptedException ex) {
                        LOG.warn(ex, "lookup management on node [%s:%s:%s] interrupted.", node.getScheme(),
                                node.getHostText(), node.getPort());
                        return null;
                    } catch (Exception ex) {
                        LOG.makeAlert(ex, "Failed to finish lookup management on node [%s:%s:%s]",
                                node.getScheme(), node.getHostText(), node.getPort()).emit();
                        return null;
                    }
                }));
            }
        }

        final ListenableFuture<List<Map.Entry>> allFuture = Futures.allAsList(futures);
        try {
            ImmutableMap.Builder<HostAndPort, LookupsState<LookupExtractorFactoryMapContainer>> stateBuilder = ImmutableMap
                    .builder();
            allFuture.get(lookupCoordinatorManagerConfig.getAllHostTimeout().getMillis(), TimeUnit.MILLISECONDS)
                    .stream().filter(Objects::nonNull).forEach(stateBuilder::put);
            knownOldState.set(stateBuilder.build());
        } catch (InterruptedException ex) {
            allFuture.cancel(true);
            Thread.currentThread().interrupt();
            throw ex;
        } catch (Exception ex) {
            allFuture.cancel(true);
            throw ex;
        }

    } catch (Exception ex) {
        LOG.makeAlert(ex, "Failed to finish lookup management loop.").emit();
    }

    LOG.debug("Finished lookup sync for on all nodes.");
}

From source file:org.apache.druid.query.metadata.SegmentMetadataQueryRunnerFactory.java

@Override
public QueryRunner<SegmentAnalysis> mergeRunners(ExecutorService exec,
        Iterable<QueryRunner<SegmentAnalysis>> queryRunners) {
    final ListeningExecutorService queryExecutor = MoreExecutors.listeningDecorator(exec);
    return new ConcatQueryRunner<SegmentAnalysis>(Sequences.map(Sequences.simple(queryRunners),
            new Function<QueryRunner<SegmentAnalysis>, QueryRunner<SegmentAnalysis>>() {
                @Override/*  w  w  w.j  ava 2 s .co  m*/
                public QueryRunner<SegmentAnalysis> apply(final QueryRunner<SegmentAnalysis> input) {
                    return new QueryRunner<SegmentAnalysis>() {
                        @Override
                        public Sequence<SegmentAnalysis> run(final QueryPlus<SegmentAnalysis> queryPlus,
                                final Map<String, Object> responseContext) {
                            final Query<SegmentAnalysis> query = queryPlus.getQuery();
                            final int priority = QueryContexts.getPriority(query);
                            final QueryPlus<SegmentAnalysis> threadSafeQueryPlus = queryPlus
                                    .withoutThreadUnsafeState();
                            final ListenableFuture<Sequence<SegmentAnalysis>> future = queryExecutor.submit(
                                    new AbstractPrioritizedCallable<Sequence<SegmentAnalysis>>(priority) {
                                        @Override
                                        public Sequence<SegmentAnalysis> call() {
                                            return Sequences.simple(
                                                    input.run(threadSafeQueryPlus, responseContext).toList());
                                        }
                                    });
                            try {
                                queryWatcher.registerQuery(query, future);
                                if (QueryContexts.hasTimeout(query)) {
                                    return future.get(QueryContexts.getTimeout(query), TimeUnit.MILLISECONDS);
                                } else {
                                    return future.get();
                                }
                            } catch (InterruptedException e) {
                                log.warn(e, "Query interrupted, cancelling pending results, query id [%s]",
                                        query.getId());
                                future.cancel(true);
                                throw new QueryInterruptedException(e);
                            } catch (CancellationException e) {
                                throw new QueryInterruptedException(e);
                            } catch (TimeoutException e) {
                                log.info("Query timeout, cancelling pending results for query id [%s]",
                                        query.getId());
                                future.cancel(true);
                                throw new QueryInterruptedException(e);
                            } catch (ExecutionException e) {
                                throw Throwables.propagate(e.getCause());
                            }
                        }
                    };
                }
            }));
}

From source file:com.vangav.backend.cassandra.Cassandra.java

/**
 * preparedStatement//w ww  . ja  va 2  s. c om
 * prepares param preparedStatement
 * @param query
 * @return if execType == ASYNC
 *           returns a Future Object that will be set to the
 *           PreparedStatement representation of param preparedStatement
 *         else if execType == SYNC
 *           waits till preparing param preparedStatement is complete
 *           then returns its PreparedStatement representation
 * @throws Exception
 */
private Object preparedStatement(String preparedStatement, ExecType execType) throws Exception {

    ArgumentsInl.checkNotNull("Prepared statement", preparedStatement, ExceptionType.CODE_EXCEPTION);
    ArgumentsInl.checkNotNull("Exec Type", execType, ExceptionType.CODE_EXCEPTION);

    while (reconnectFlag.get() == true) {

    }

    for (int i = 0; i < this.queryRetries; i++) {

        try {

            ListenableFuture<PreparedStatement> result = this.session.prepareAsync(preparedStatement);

            if (healthCount.get() > kMinHealth) {

                healthCount.decrementAndGet();
            }

            if (execType == ExecType.SYNC) {

                ThreadPool.i().<PreparedStatement>executeInCassandraPool(result);

                PreparedStatement preparedStatementResult = result.get(kDefaultTimeout, kDefaultTimeunit);

                this.preparedStatements.add(preparedStatement);

                return preparedStatementResult;
            } else if (execType == ExecType.ASYNC) {

                this.preparedStatements.add(preparedStatement);

                return result;
            }
        } catch (NoHostAvailableException nhae) {

            try {

                if (reconnectFlag.get() == false) {

                    synchronized (mutex) {

                        if (healthCount.incrementAndGet() >= kHealthThreshold) {

                            this.reconnect();

                            healthCount.set(kMinHealth);
                        }
                    }
                }
            } catch (Exception e) {

                if (i == (this.queryRetries - 1)) {

                    throw e;
                }
            }
        } catch (Exception e) {

            if (i == (this.queryRetries - 1)) {

                throw e;
            }
        }
    }

    throw new CodeException(21, 1, "Couldn't prepare prepared statement [" + preparedStatement + "]",
            ExceptionClass.CASSANDRA);
}

From source file:flipkart.lego.engine.Lego.java

private long waitUntilAvailableOrTimeout(Map<String, ListenableFuture> requiredFutureHashMap,
        Map<String, ListenableFuture> optionalFutureHashMap, Request request, long elementTimeout)
        throws TimeoutException {
    //requiredFuture is only realized if all the futures are realized
    List<ListenableFuture<Object>> requireFutureList = new ArrayList<>();
    for (Map.Entry<String, ListenableFuture> listenableFutureEntry : requiredFutureHashMap.entrySet()) {
        requireFutureList.add(listenableFutureEntry.getValue());
    }/*  w w  w.  j  ava  2 s. co m*/
    ListenableFuture<List<Object>> requiredFuture = Futures.allAsList(requireFutureList);

    //requiredFuture is only realized if all the futures are realized
    List<ListenableFuture<Object>> optionalFutureList = new ArrayList<>();
    for (Map.Entry<String, ListenableFuture> listenableFutureEntry : optionalFutureHashMap.entrySet()) {
        optionalFutureList.add(listenableFutureEntry.getValue());
    }
    ListenableFuture<List<Object>> optionalFuture = Futures.successfulAsList(optionalFutureList);

    //used to calculate remaining time for timeout
    Stopwatch requiredDSStopWatch = Stopwatch.createStarted();

    //Wait until timeout to see if required data is realized, if it times out throw internalErrorException
    try {
        requiredFuture.get(elementTimeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException timeoutException) {
        exceptionLogger.error("TimeOutException: required data sources timed out {}, Timeout:{}, Exception:{}",
                request, elementTimeout, timeoutException);
        requiredFuture.cancel(true);
        cancelFutures((Collection) requireFutureList);
        throw timeoutException;
    } catch (InterruptedException interruptedException) {
        exceptionLogger.error(
                "InterruptedException: required data sources were interrupted{}, Message:{}, Exception:{}",
                request, interruptedException.getMessage(), interruptedException);
        requiredFuture.cancel(true);
        cancelFutures((Collection) requireFutureList);
        throwTimeoutException(interruptedException);
    } catch (ExecutionException executionException) {
        exceptionLogger.error("ExcecutionException: {}", executionException);
        requiredFuture.cancel(true);
        cancelFutures((Collection) requireFutureList);
        throwTimeoutException(executionException);
    }

    //if time is still remaining before timeout wait until timeout for optional data to realize itself
    requiredDSStopWatch.stop();
    long remainingTimeForTimeout = elementTimeout - requiredDSStopWatch.elapsed(TimeUnit.MILLISECONDS); //calculates milliseconds remaining before elementTimeout
    Stopwatch optionalDsStopWatch = Stopwatch.createStarted();
    if (remainingTimeForTimeout > 0) {
        try {
            optionalFuture.get(1, TimeUnit.MILLISECONDS);
        } catch (Exception exception) {
            optionalFuture.cancel(true);
            cancelFutures((Collection) optionalFutureList);
            exceptionLogger.warn("Optional Data Sources Were Not Realized {}, Exception: {}", request,
                    exception);
        }
    }

    optionalDsStopWatch.stop();
    remainingTimeForTimeout = remainingTimeForTimeout - optionalDsStopWatch.elapsed(TimeUnit.MILLISECONDS); //calculate time remaining for execution of response filters
    return remainingTimeForTimeout > 0 ? remainingTimeForTimeout : 0;
}

From source file:com.google.caliper.runner.StreamService.java

@Override
protected void doStop() {
    if (openStreams.get() > 0) {
        // This means stop was called on us externally and we are still reading/writing, just log a
        // warning and do nothing
        logger.warning("Attempting to stop the stream service with streams still open");
    }/*from   ww w.  ja  va  2  s .c o m*/
    final ListenableFuture<Integer> processFuture = streamExecutor.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return process.waitFor();
        }
    });
    // Experimentally, even with well behaved processes there is some time between when all streams
    // are closed as part of process shutdown and when the process has exited. So to not fail 
    // flakily when shutting down normally we need to do a timed wait
    streamExecutor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            boolean threw = true;
            try {
                if (processFuture.get(SHUTDOWN_WAIT_MILLIS, TimeUnit.MILLISECONDS) == 0) {
                    notifyStopped();
                } else {
                    notifyFailed(
                            new Exception("Process failed to stop cleanly. Exit code: " + process.waitFor()));
                }
                threw = false;
            } finally {
                processFuture.cancel(true); // we don't need it anymore
                if (threw) {
                    process.destroy();
                    notifyFailed(
                            new Exception("Process failed to stop cleanly and was forcibly killed. Exit code: "
                                    + process.waitFor()));
                }
            }
            return null;
        }
    });
}