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.opendaylight.mdsal.binding.dom.adapter.BindingDOMTransactionChainAdapter.java
private CheckedFuture<Void, TransactionCommitFailedException> listenForFailure(final WriteTransaction tx, final CheckedFuture<Void, TransactionCommitFailedException> future) { Futures.addCallback(future, new FutureCallback<Void>() { @Override/*from w w w . j a v a 2s .c o m*/ public void onFailure(final Throwable t) { failTransactionChain(tx, t); } @Override public void onSuccess(final Void result) { // Intentionally NOOP } }); return future; }
From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.java
/** * Performs a query against the remote table and stores results. * * @param query an optional query to filter results * @param queryKey key to identify the query * @return A ListenableFuture that is done when results have been pulled. *//*from ww w .j ava2 s.c o m*/ public ListenableFuture<Void> pull(Query query, String queryId) { ListenableFuture<Void> pull = this.mInternalTable.pull(query, queryId); final SettableFuture<Void> result = SettableFuture.create(); Futures.addCallback(pull, new FutureCallback<Void>() { @Override public void onFailure(Throwable throwable) { result.setException(throwable); } @Override public void onSuccess(Void value) { result.set(value); } }); return result; }
From source file:co.cask.cdap.internal.app.deploy.SandboxConfigurator.java
/** * Runs the <code>Application.configure()</code> in a sandbox JVM * with high level of security.//from w ww. jav a 2 s . c o m * * @return An instance of {@link ListenableFuture} */ @Override public ListenableFuture<ConfigResponse> config() { final SettableFuture<ConfigResponse> result = SettableFuture.create(); final File outputFile; try { outputFile = File.createTempFile(PREFIX, EXT); // Run the command in seperate JVM. process = Runtime.getRuntime().exec(getCommand(outputFile)); // Add future to handle the case when the future is cancelled. // OnSuccess, we don't do anything other than cleaning the output. // onFailure, we make sure that process is destroyed. Futures.addCallback(result, new FutureCallback<ConfigResponse>() { private void deleteOutput() { if (outputFile.exists()) { outputFile.delete(); } } @Override public void onSuccess(final ConfigResponse result) { // Delete the output file on delete. deleteOutput(); } @Override public void onFailure(final Throwable t) { // In case the future was cancelled, we have to // destroy the process. if (result.isCancelled()) { process.destroy(); } deleteOutput(); } }); } catch (Exception e) { // Returns a {@code ListenableFuture} which has an exception set immediately // upon construction. return Futures.immediateFailedFuture(e); } // Start a thread that waits for command execution to complete or till it's cancelled. new Thread() { @Override public void run() { try { // Wait for process to exit and extract the return. If cancelled the process will // be shutdown. process.waitFor(); int exit = process.exitValue(); if (exit == 0) { result.set( new DefaultConfigResponse(0, Files.newReaderSupplier(outputFile, Charsets.UTF_8))); } else { result.set(new DefaultConfigResponse(exit, null)); } } catch (Exception e) { result.setException(e); } } }.start(); return result; }
From source file:sharding.simple.shardtests.ShardTestCallable.java
@Override public Void call() throws Exception { int testDataIdx = 0; int writeCnt = 0; DOMDataTreeCursorAwareTransaction tx = sd.getProducer().createTransaction(false); DOMDataTreeWriteCursor cursor = tx.createCursor(sd.getDOMDataTreeIdentifier()); cursor.enter(new NodeIdentifier(InnerList.QNAME)); for (int i = 0; i < numItems; i++) { NodeIdentifierWithPredicates nodeId = new NodeIdentifierWithPredicates(InnerList.QNAME, DomListBuilder.IL_NAME, (long) i); MapEntryNode element;// w ww. j ava 2 s . c om if (testData != null) { element = testData.get(testDataIdx++); } else { element = AbstractShardTest.createListEntry(nodeId, shardNum, i); } writeCnt++; cursor.write(nodeId, element); if (writeCnt == opsPerTx) { // We have reached the limit of writes-per-transaction. // Submit the current outstanding transaction and create // a new one in its place. txSubmitted++; cursor.close(); Futures.addCallback(tx.submit(), new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { txOk++; } @Override public void onFailure(final Throwable t1) { LOG.error("Transaction failed, shard {}, exception {}", shardNum, t1); txError++; } }); writeCnt = 0; tx = sd.getProducer().createTransaction(false); cursor = tx.createCursor(sd.getDOMDataTreeIdentifier()); cursor.enter(new NodeIdentifier(InnerList.QNAME)); } } // Submit the last outstanding transaction even if it's empty and wait // for it to complete. This will flush all outstanding transactions to // the data store. Note that all tx submits except for the last one are // asynchronous. txSubmitted++; cursor.close(); try { tx.submit().checkedGet(); txOk++; } catch (TransactionCommitFailedException e) { LOG.error("Last transaction submit failed, shard {}, exception {}", shardNum, e); txError++; } return null; }
From source file:io.crate.executor.transport.task.UpsertTask.java
@Override public void start() { if (subTasks.size() == 0) { ((SettableFuture) resultList.get(0)).set(RowCountResult.EMPTY_RESULT); return;// w w w . j a va2 s . c o m } else if (forwardResultsFromSubTask) { // result list is bind to sub task results, no further action/listener required transportExecutor.execute(subTasks); } else { final SettableFuture<TaskResult> result = (SettableFuture) resultList.get(0); final List<ListenableFuture<TaskResult>> subTasksResult = transportExecutor.execute(subTasks); Futures.addCallback(Futures.allAsList(subTasksResult), new FutureCallback<List<TaskResult>>() { @Override public void onSuccess(@Nullable List<TaskResult> results) { if (results == null) { result.setException(new NullPointerException()); return; } assert results.size() == 1 : "Last sub-task is expected to have 1 result only"; result.set(new RowCountResult( ((Number) results.get(0).rows().iterator().next().get(0)).longValue())); } @Override public void onFailure(@Nonnull Throwable t) { if (t == null) { t = new NullPointerException(); } result.setException(t); } }); } }
From source file:org.opendaylight.netconf.topology.impl.OnlySuccessStateAggregator.java
@Override public ListenableFuture<Void> combineDeleteAttempts(List<ListenableFuture<Void>> stateFutures) { final SettableFuture<Void> future = SettableFuture.create(); final ListenableFuture<List<Void>> allAsList = Futures.allAsList(stateFutures); Futures.addCallback(allAsList, new FutureCallback<List<Void>>() { @Override// w w w. j a v a2s . co m public void onSuccess(List<Void> result) { future.set(null); } @Override public void onFailure(Throwable t) { LOG.error("One of the combined delete attempts failed {}", t); future.setException(t); } }); return future; }
From source file:demos.AsynchronousRead.java
@Override public void run() { try {/*from w w w . j a v a 2s . c om*/ logger.info("Preparing to read data points"); Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect("demo"); PreparedStatement query = session.prepare( "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?"); DateTime end = DateTime.now(); DateTime start = end.minusYears(1); final CountDownLatch latch = new CountDownLatch(NUM_METRICS); final Set<DataPoint> dataPoints = new ConcurrentSkipListSet<>( comparing(DataPoint::getTimestamp).thenComparing(DataPoint::getValue)); Stopwatch stopwatch = new Stopwatch().start(); for (int i = 0; i < NUM_METRICS; ++i) { ResultSetFuture queryFuture = session .executeAsync(query.bind("metric-" + i, start.toDate(), end.toDate())); ListenableFuture<List<DataPoint>> dataFuture = Futures.transform(queryFuture, (ResultSet resultSet) -> StreamSupport.stream(resultSet.spliterator(), false) .map(row -> new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2))) .collect(toList())); Futures.addCallback(dataFuture, new FutureCallback<List<DataPoint>>() { @Override public void onSuccess(List<DataPoint> results) { dataPoints.addAll(results); latch.countDown(); } @Override public void onFailure(Throwable t) { logger.warn("There was an error reading data", t); latch.countDown(); } }); } latch.await(); stopwatch.stop(); logger.info("Retrieved {} data points in {} ms", dataPoints.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { logger.info("There was an interrupt while waiting for inserts to complete"); } }
From source file:com.microsoft.sharepointservices.DocLibClient.java
/** * Gets children folder with a given path * //from w ww . jav a 2s . c om * @param path * @return OfficeFuture<FileSystemItem> */ public ListenableFuture<List<FileSystemItem>> getFileSystemItems(String path, String library) { final SettableFuture<List<FileSystemItem>> result = SettableFuture.create(); String getPath; if (library == null) { if (path == null || path.length() == 0) { getPath = getSiteUrl() + "_api/Files"; } else { getPath = getSiteUrl() + String.format("_api/Files('%s')/children", urlEncode(path)); } } else { if (path == null || path.length() == 0) { getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library)); } else { getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files('%s')/children", urlEncode(library), urlEncode(path)); } } ListenableFuture<JSONObject> request = executeRequestJson(getPath, "GET"); Futures.addCallback(request, new FutureCallback<JSONObject>() { @Override public void onFailure(Throwable t) { result.setException(t); } @Override public void onSuccess(JSONObject json) { List<FileSystemItem> item; try { item = FileSystemItem.listFrom(json); result.set(item); } catch (Throwable e) { result.setException(e); } } }); return result; }
From source file:demos.BatchInsert.java
public void run() { try {//from w w w. j a v a2s . co m logger.info("Preparing to insert metric data points"); Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect("demo"); PreparedStatement insert = session .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)"); Random random = new Random(); DateTime time = DateTime.now().minusYears(1); final CountDownLatch latch = new CountDownLatch(NUM_INSERTS / BATCH_SIZE); FutureCallback<ResultSet> callback = new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { latch.countDown(); } @Override public void onFailure(Throwable t) { logger.warn("There was an error inserting data", t); latch.countDown(); } }; Stopwatch stopwatch = new Stopwatch().start(); BatchStatement batch = new BatchStatement(); for (int i = 0; i < NUM_INSERTS; ++i) { String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS); double value = random.nextDouble(); batch.add(insert.bind(metricId, time.toDate(), value)); time = time.plusSeconds(10); if (batch.size() == BATCH_SIZE) { ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, callback); batch = new BatchStatement(); } } latch.await(); stopwatch.stop(); logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS, stopwatch.elapsed(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { logger.info("There was an interrupt while waiting for inserts to complete"); } }
From source file:org.springframework.integration.samples.helloworld.HelloService.java
public void doGuavaDownloadWithChainedThreads(final URL url) throws IOException { ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); List<ListenableFuture<String>> calls = new ArrayList<ListenableFuture<String>>(); while (calls.size() < 5) { com.google.common.util.concurrent.ListenableFuture<String> call = service .submit(new Callable<String>() { @Override/* ww w . j a v a 2 s . c om*/ public String call() throws Exception { try (InputStream input = url.openStream()) { return IOUtils.toString(input, StandardCharsets.UTF_8); } } }); calls.add(call); } ListenableFuture<List<String>> goodCalls = Futures.successfulAsList(calls); Futures.addCallback(goodCalls, new FutureCallback<List<String>>() { @Override public void onSuccess(List<String> strings) { System.out.print("Successful call"); } @Override public void onFailure(Throwable throwable) { System.err.println("Problems"); } }); }