Example usage for com.google.common.util.concurrent FutureCallback FutureCallback

List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback

Introduction

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

Prototype

FutureCallback

Source Link

Usage

From source file:org.apache.storm.cassandra.executor.AsyncExecutor.java

/**
 * Asynchronously executes all statements associated to the specified input.
 * The input will be passed to handler#onSuccess once all queries succeed or to handler#onFailure if any one of them fails.
 *//*from  w  ww.  j  av  a  2 s  . c o m*/
public List<SettableFuture<T>> execAsync(List<Statement> statements, final T input) {

    List<SettableFuture<T>> settableFutures = new ArrayList<>(statements.size());

    for (Statement s : statements)
        settableFutures.add(execAsync(s, input, AsyncResultHandler.NO_OP_HANDLER));

    ListenableFuture<List<T>> allAsList = Futures.allAsList(settableFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<T>>() {
        @Override
        public void onSuccess(List<T> inputs) {
            handler.success(input);
        }

        @Override
        public void onFailure(Throwable t) {
            handler.failure(t, input);
        }
    }, executorService);
    return settableFutures;
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.PCEPStatefulPeerProposal.java

void setPeerProposal(final NodeId nodeId, final TlvsBuilder openTlvsBuilder) {
    if (isSynOptimizationEnabled(openTlvsBuilder)) {
        final ListenableFuture<Optional<LspDbVersion>> future = this.dataBroker.newReadOnlyTransaction().read(
                LogicalDatastoreType.OPERATIONAL,
                this.topologyId.child(Node.class, new NodeKey(nodeId)).augmentation(Node1.class)
                        .child(PathComputationClient.class).augmentation(PathComputationClient1.class)
                        .child(LspDbVersion.class));
        Futures.addCallback(future, new FutureCallback<Optional<LspDbVersion>>() {
            @Override/*w  ww  .ja  v  a 2 s  .  c  o  m*/
            public void onSuccess(final Optional<LspDbVersion> result) {
                if (result.isPresent()) {
                    openTlvsBuilder.addAugmentation(Tlvs3.class,
                            new Tlvs3Builder().setLspDbVersion(result.get()).build());
                }
            }

            @Override
            public void onFailure(final Throwable t) {
                LOG.warn("Failed to read toplogy {}.",
                        InstanceIdentifier.keyOf(PCEPStatefulPeerProposal.this.topologyId), t);
            }
        });
    }
}

From source file:io.crate.operation.collect.JobCollectContext.java

public JobCollectContext(final CollectPhase collectPhase, MapSideDataCollectOperation collectOperation,
        String localNodeId, RamAccountingContext queryPhaseRamAccountingContext, final RowReceiver rowReceiver,
        SharedShardContexts sharedShardContexts) {
    super(collectPhase.phaseId(), LOGGER);
    this.collectPhase = collectPhase;
    this.collectOperation = collectOperation;
    this.queryPhaseRamAccountingContext = queryPhaseRamAccountingContext;
    this.sharedShardContexts = sharedShardContexts;

    listenableRowReceiver = RowReceivers.listenableRowReceiver(rowReceiver);
    Futures.addCallback(listenableRowReceiver.finishFuture(), new FutureCallback<Void>() {
        @Override/*w w  w  .  j av  a2  s.  c o  m*/
        public void onSuccess(@Nullable Void result) {
            close();
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            closeDueToFailure(t);
        }
    });
    this.rowReceiver = listenableRowReceiver;
    this.threadPoolName = threadPoolName(collectPhase, localNodeId);
}

From source file:org.opendaylight.dsbenchmark.txchain.TxchainDomDelete.java

@Override
public void executeList() {
    int txSubmitted = 0;
    int writeCnt = 0;

    org.opendaylight.yangtools.yang.common.QName OL_ID = QName.create(OuterList.QNAME, "id");
    DOMTransactionChain chain = domDataBroker.createTransactionChain(this);
    DOMDataWriteTransaction tx = chain.newWriteOnlyTransaction();

    YangInstanceIdentifier pid = YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME)
            .build();/*from   ww w . j av a 2  s.c  o m*/
    for (int l = 0; l < outerListElem; l++) {
        YangInstanceIdentifier yid = pid.node(new NodeIdentifierWithPredicates(OuterList.QNAME, OL_ID, l));
        tx.delete(LogicalDatastoreType.CONFIGURATION, yid);

        writeCnt++;

        if (writeCnt == writesPerTx) {
            txSubmitted++;
            Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
                @Override
                public void onSuccess(final Void result) {
                    txOk++;
                }

                @Override
                public void onFailure(final Throwable t) {
                    LOG.error("Transaction failed, {}", t);
                    txError++;
                }
            });
            tx = chain.newWriteOnlyTransaction();
            writeCnt = 0;
        }
    }

    // *** Clean up and close the transaction chain ***
    // Submit the outstanding transaction even if it's empty and wait for it to finish
    // We need to empty the transaction chain before closing it
    try {
        txSubmitted++;
        tx.submit().checkedGet();
        txOk++;
    } catch (TransactionCommitFailedException e) {
        LOG.error("Transaction failed", e);
        txError++;
    }
    try {
        chain.close();
    } catch (IllegalStateException e) {
        LOG.error("Transaction close failed,", e);
    }
    LOG.info("Transactions: submitted {}, completed {}", txSubmitted, (txOk + txError));
}

From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfMasterDOMTransaction.java

@Override
public Future<Optional<NormalizedNodeMessage>> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    LOG.trace("{}: Read[{}] {} via NETCONF: {}", id, readTx.getIdentifier(), store, path);

    final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = readTx.read(store,
            path);//from  w  w w  . ja v  a 2  s. c  o m

    final DefaultPromise<Optional<NormalizedNodeMessage>> promise = new DefaultPromise<>();
    Futures.addCallback(readFuture, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
            if (!result.isPresent()) {
                promise.success(Optional.absent());
            } else {
                promise.success(Optional.of(new NormalizedNodeMessage(path, result.get())));
            }
        }

        @Override
        public void onFailure(@Nonnull final Throwable throwable) {
            promise.failure(throwable);
        }
    });
    return promise.future();
}

From source file:com.facebook.swift.perf.loadgenerator.AsyncClientWorker.java

@Override
public void run() {
    try {/*w w w  . java 2  s .  co m*/
        ListenableFuture<LoadTest> clientFuture;

        clientFuture = clientManager.createClient(connector, LoadTest.class,
                new Duration(config.connectTimeoutMilliseconds, TimeUnit.SECONDS),
                new Duration(config.sendTimeoutMilliseconds, TimeUnit.MILLISECONDS),
                new Duration(config.receiveTimeoutMilliseconds, TimeUnit.MILLISECONDS), "AsyncClientWorker",
                null);

        Futures.addCallback(clientFuture, new FutureCallback<LoadTest>() {
            @Override
            public void onSuccess(LoadTest result) {
                logger.info("Worker connected");

                client = result;
                channel = clientManager.getNiftyChannel(client);

                // Thrift clients are not thread-safe, and for maximum efficiency, new requests are made
                // on the channel thread, as the pipeline starts to clear out. So we either need to
                // synchronize on "sendRequest" or make the initial calls to fill the pipeline on the
                // channel thread as well.
                channel.executeInIoThread(new Runnable() {
                    @Override
                    public void run() {
                        fillRequestPipeline(client);
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                onConnectFailed(t);
            }
        });
    } catch (Throwable t) {
        onConnectFailed(t);
    }
}

From source file:org.apache.bookkeeper.client.DefaultSpeculativeRequestExecutionPolicy.java

private ScheduledFuture<?> scheduleSpeculativeRead(final ScheduledExecutorService scheduler,
        final SpeculativeRequestExecutor requestExecutor, final int speculativeRequestTimeout) {
    try {//from  w  w w.  ja  v  a2s.c  om
        return scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                ListenableFuture<Boolean> issueNextRequest = requestExecutor.issueSpeculativeRequest();
                Futures.addCallback(issueNextRequest, new FutureCallback<Boolean>() {
                    // we want this handler to run immediately after we push the big red button!
                    public void onSuccess(Boolean issueNextRequest) {
                        if (issueNextRequest) {
                            scheduleSpeculativeRead(scheduler, requestExecutor,
                                    Math.min(maxSpeculativeRequestTimeout,
                                            Math.round((float) speculativeRequestTimeout * backoffMultiplier)));
                        } else {
                            if (LOG.isTraceEnabled()) {
                                LOG.trace(
                                        "Stopped issuing speculative requests for {}, "
                                                + "speculativeReadTimeout = {}",
                                        requestExecutor, speculativeRequestTimeout);
                            }
                        }
                    }

                    public void onFailure(Throwable thrown) {
                        LOG.warn("Failed to issue speculative request for {}, speculativeReadTimeout = {} : ",
                                requestExecutor, speculativeRequestTimeout, thrown);
                    }
                });
            }
        }, speculativeRequestTimeout, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException re) {
        if (!scheduler.isShutdown()) {
            LOG.warn("Failed to schedule speculative request for {}, speculativeReadTimeout = {} : ",
                    requestExecutor, speculativeRequestTimeout, re);
        }
    }
    return null;
}

From source file:io.bitsquare.p2p.tomp2p.TomP2PNode.java

public Observable<BootstrappedPeerBuilder.State> bootstrap(KeyPair keyPair) {
    bootstrappedPeerBuilder.setKeyPair(keyPair);

    bootstrappedPeerBuilder.getState().addListener((ov, oldValue, newValue) -> {
        log.debug("BootstrapState changed " + newValue);
        bootstrapStateSubject.onNext(newValue);
    });//from ww w .  j a v  a  2  s  .  c o m

    SettableFuture<PeerDHT> bootstrapFuture = bootstrappedPeerBuilder.start();
    Futures.addCallback(bootstrapFuture, new FutureCallback<PeerDHT>() {
        @Override
        public void onSuccess(@Nullable PeerDHT peerDHT) {
            if (peerDHT != null) {
                TomP2PNode.this.peerDHT = peerDHT;

                BaseP2PService.getUserThread()
                        .execute(() -> numPeers.set(peerDHT.peerBean().peerMap().all().size()));
                log.debug("Number of peers = " + peerDHT.peerBean().peerMap().all().size());

                peerDHT.peerBean().peerMap().addPeerMapChangeListener(new PeerMapChangeListener() {
                    @Override
                    public void peerInserted(PeerAddress peerAddress, boolean b) {
                        BaseP2PService.getUserThread()
                                .execute(() -> numPeers.set(peerDHT.peerBean().peerMap().all().size()));
                        log.debug("peerInserted " + peerAddress);
                        log.debug("Number of peers = " + peerDHT.peerBean().peerMap().all().size());
                    }

                    @Override
                    public void peerRemoved(PeerAddress peerAddress, PeerStatistic peerStatistic) {
                        BaseP2PService.getUserThread()
                                .execute(() -> numPeers.set(peerDHT.peerBean().peerMap().all().size()));
                        log.debug("peerRemoved " + peerAddress);
                        log.debug("Number of peers = " + peerDHT.peerBean().peerMap().all().size());
                    }

                    @Override
                    public void peerUpdated(PeerAddress peerAddress, PeerStatistic peerStatistic) {
                        BaseP2PService.getUserThread()
                                .execute(() -> numPeers.set(peerDHT.peerBean().peerMap().all().size()));
                        // log.debug("peerUpdated " + peerAddress);
                        // log.debug("Number of peers = " + peerDHT.peerBean().peerMap().all().size());
                    }
                });
                /*   peerDHT.peerBean().addPeerStatusListener(new PeerStatusListener() {
                @Override
                public boolean peerFailed(PeerAddress peerAddress, PeerException e) {
                    return false;
                }
                        
                @Override
                public boolean peerFound(PeerAddress peerAddress, PeerAddress peerAddress1, PeerConnection peerConnection, RTT rtt) {
                    BaseP2PService.getUserThread().execute(() -> numPeers.set(peerDHT.peerBean().peerMap().size()));
                    return false;
                }
                   });*/

                resultHandlers.stream().forEach(ResultHandler::handleResult);
                bootstrapStateSubject.onCompleted();
            } else {
                log.error("Error at bootstrap: peerDHT = null");
                bootstrapStateSubject.onError(new BitsquareException("Error at bootstrap: peerDHT = null"));
            }
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("Exception at bootstrap " + t.getMessage());
            bootstrapStateSubject.onError(t);
        }
    });

    return bootstrapStateSubject.asObservable();
}

From source file:com.spotify.heroic.cache.memcached.MemcachedCacheModule.java

@Provides
@CacheScope/*from  w  w w.j a  v a2s .  c  om*/
public Managed<MemcacheClient<byte[]>> memcacheClient(final AsyncFramework async) {
    return async.managed(new ManagedSetup<MemcacheClient<byte[]>>() {
        @Override
        public AsyncFuture<MemcacheClient<byte[]>> construct() throws Exception {
            final List<HostAndPort> addresses = new ArrayList<>();

            for (final String address : MemcachedCacheModule.this.addresses) {
                addresses.add(HostAndPort.fromString(address));
            }

            final BinaryMemcacheClient<byte[]> client = MemcacheClientBuilder.newByteArrayClient()
                    .withAddresses(addresses).connectBinary();

            final ResolvableFuture<MemcacheClient<byte[]>> future = async.future();

            Futures.addCallback(ConnectFuture.connectFuture(client), new FutureCallback<Void>() {
                @Override
                public void onSuccess(@Nullable final Void result) {
                    future.resolve(client);
                }

                @Override
                public void onFailure(final Throwable cause) {
                    future.fail(cause);
                }
            });

            return future;
        }

        @Override
        public AsyncFuture<Void> destruct(final MemcacheClient<byte[]> value) throws Exception {
            return async.call(() -> {
                value.shutdown();
                return null;
            });
        }
    });
}

From source file:com.google.gerrit.server.index.change.ReindexAfterRefUpdate.java

@Override
public void onGitReferenceUpdated(final Event event) {
    if (!enabled || event.getRefName().startsWith(RefNames.REFS_CHANGES)
            || event.getRefName().startsWith(RefNames.REFS_DRAFT_COMMENTS)
            || event.getRefName().startsWith(RefNames.REFS_USERS)) {
        return;//w ww.ja v a 2s . com
    }
    Futures.addCallback(executor.submit(new GetChanges(event)), new FutureCallback<List<Change>>() {
        @Override
        public void onSuccess(List<Change> changes) {
            for (Change c : changes) {
                // Don't retry indefinitely; if this fails changes may be stale.
                @SuppressWarnings("unused")
                Future<?> possiblyIgnoredError = executor.submit(new Index(event, c.getId()));
            }
        }

        @Override
        public void onFailure(Throwable ignored) {
            // Logged by {@link GetChanges#call()}.
        }
    }, directExecutor());
}