List of usage examples for com.google.common.util.concurrent Futures addCallback
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)
From source file:org.apache.flink.batch.connectors.cassandra.CassandraOutputFormatBase.java
@Override public void writeRecord(OUT record) throws IOException { if (exception != null) { throw new IOException("write record failed", exception); }//from ww w . java2 s . co m Object[] fields = extractFields(record); ResultSetFuture result = session.executeAsync(prepared.bind(fields)); Futures.addCallback(result, callback); }
From source file:com.spotify.heroic.cache.memcached.MemcachedCacheModule.java
@Provides @CacheScope//from w w w .j a v a 2s . co m 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: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/*from ww w. jav 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: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();// ww w . ja va 2s. c om 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 ww w. j a 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 {//from w w w . j a va2 s . c o 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 . j a va 2s. c o m*/ 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); });/* ww w . ja v a2 s.c om*/ 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.microsoft.office.integration.test.EventsAsyncTestCase.java
public void testUpdate() { prepareEvent();//from ww w .ja v a 2 s. c om counter = new CountDownLatch(1); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); counter.countDown(); } public void onSuccess(Void result) { try { updateAndCheck(); removeEvent(); } catch (Throwable t) { reportError(t); } counter.countDown(); } }); try { if (!counter.await(60000, TimeUnit.MILLISECONDS)) { fail("testUpdate() timed out"); } } catch (InterruptedException e) { fail("testUpdate() has been interrupted"); } }
From source file:org.bitcoinj_extra.net.NioClient.java
/** * <p>Creates a new client to the given server address using the given {@link StreamConnection} to decode the data. * The given connection <b>MUST</b> be unique to this object. This does not block while waiting for the connection to * open, but will call either the {@link StreamConnection#connectionOpened()} or * {@link StreamConnection#connectionClosed()} callback on the created network event processing thread.</p> * * @param connectTimeoutMillis The connect timeout set on the connection (in milliseconds). 0 is interpreted as no * timeout.//from ww w . j ava 2 s. c o m */ public NioClient(final SocketAddress serverAddress, final StreamConnection parser, final int connectTimeoutMillis) throws IOException { manager.startAsync(); manager.awaitRunning(); handler = new Handler(parser, connectTimeoutMillis); Futures.addCallback(manager.openConnection(serverAddress, handler), new FutureCallback<SocketAddress>() { @Override public void onSuccess(SocketAddress result) { } @Override public void onFailure(Throwable t) { log.error("Connect to {} failed: {}", serverAddress, Throwables.getRootCause(t)); } }); }