List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback
FutureCallback
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. */// w ww.j ava 2 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:org.javabits.yar.guice.AbstractExecutionStrategy.java
public void execute(final List<Callable<Void>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException { for (int i = 0; i < tasks.size(); i++) { final int taskNumber = i; Callable<Void> task = tasks.get(i); final ListenableFuture<Void> future = executorService().submit(task); pendingTasks.put(future, task);/*from w ww . j a va2 s .c o m*/ future.addListener(new Runnable() { @Override public void run() { pendingTasks.remove(future); } }, executorService()); addCallback(future, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { LOG.log(Level.FINE, String.format("Listener task succeeded : %s", tasks.get(taskNumber))); } @Override public void onFailure(Throwable t) { LOG.log(Level.SEVERE, String.format("Listener task failed: %s", tasks.get(taskNumber)), t); } }); } }
From source file:com.vmware.photon.controller.clustermanager.rolloutplans.BasicNodeRollout.java
private void provisionNodes(final Service service, final NodeRolloutInput input, final FutureCallback<NodeRolloutResult> responseFutureCallback) { final Queue<Throwable> exceptions = new ConcurrentLinkedQueue<>(); final Queue<String> nodeAddresses = new ConcurrentLinkedQueue<>(); final AtomicInteger latch = new AtomicInteger(input.nodeCount); for (int i = 0; i < input.nodeCount; i++) { FutureCallback<VmProvisionTaskService.State> callback = new FutureCallback<VmProvisionTaskService.State>() { @Override//from www. j av a2 s . c o m public void onSuccess(@Nullable VmProvisionTaskService.State result) { switch (result.taskState.stage) { case FINISHED: nodeAddresses.add(result.vmIpAddress); break; case CANCELLED: exceptions.add(new IllegalStateException( String.format("VmProvisionTaskService was canceled. %s", result.documentSelfLink))); break; case FAILED: exceptions.add(new IllegalStateException( String.format("VmProvisionTaskService failed with error %s. %s", result.taskState.failure.message, result.documentSelfLink))); break; } if (0 == latch.decrementAndGet()) { if (0 == exceptions.size()) { waitForNodes(service, input, new ArrayList<>(nodeAddresses), responseFutureCallback); } else { responseFutureCallback.onFailure(ExceptionUtils.createMultiException(exceptions)); } } } @Override public void onFailure(Throwable t) { exceptions.add(t); if (0 == latch.decrementAndGet()) { responseFutureCallback.onFailure(ExceptionUtils.createMultiException(exceptions)); } } }; NodeTemplate template = NodeTemplateFactory.createInstance(input.nodeType); String scriptDirectory = HostUtils.getScriptsDirectory(service); Map<String, String> nodeProperties = new HashMap<>(input.nodeProperties); nodeProperties.put(NodeTemplateUtils.NODE_INDEX_PROPERTY, Integer.toString(i)); nodeProperties.put(NodeTemplateUtils.HOST_ID_PROPERTY, UUID.randomUUID().toString()); VmProvisionTaskService.State startState = new VmProvisionTaskService.State(); startState.diskFlavorName = input.diskFlavorName; startState.imageId = input.imageId; startState.projectId = input.projectId; startState.vmFlavorName = input.vmFlavorName; startState.vmNetworkId = input.vmNetworkId; startState.vmTags = ClusterUtil.createClusterTags(input.clusterId, input.nodeType); startState.vmName = template.getVmName(nodeProperties); startState.userData = template.createUserDataTemplate(scriptDirectory, nodeProperties); startState.metaData = template.createMetaDataTemplate(scriptDirectory, nodeProperties); TaskUtils.startTaskAsync(service, VmProvisionTaskFactoryService.SELF_LINK, startState, (state) -> TaskUtils.finalTaskStages.contains(state.taskState.stage), VmProvisionTaskService.State.class, ClusterManagerConstants.DEFAULT_TASK_POLL_DELAY, callback); } }
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 www .j ava2s . c om * * @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:xyz.cloudbans.bukkit.command.UnbanCommand.java
@Override public boolean onCommand(final CommandSender sender, Command command, String label, final String[] args) { // unban <player> <reason> if (!sender.hasPermission("cloudbans.ban.unban")) { sender.sendMessage(ChatColor.RED + "You don't have enough permissions for that."); return true; }//from ww w. j a v a2 s . c o m if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Your missing arguments for this command."); return false; } if (sender instanceof BlockCommandSender) { sender.sendMessage(ChatColor.RED + "For security reasons this command can only executed by a player or the console!"); return true; } Future<BanResponse> future = client.getActiveBan(config.getServerUuid(), args[0]); Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future, executor), new FutureCallback<BanResponse>() { @Override public void onSuccess(BanResponse result) { BanRequestBuilder builder = new BanRequestBuilder(); builder.setId(result.getBan().getId()); if (args.length > 2) { String[] reason = Arrays.copyOfRange(args, 2, args.length); String unbanReason = Joiner.on(" ").join(reason); builder.setDescription(result.getBan().getDescription() + " Unban: " + unbanReason); } builder.setEnabled(false); BanRequest request = builder.build(); Future<BanResponse> unbanResponseFuture = client.updateBan(request); Futures.addCallback(JdkFutureAdapters.listenInPoolThread(unbanResponseFuture, executor), new FutureCallback<BanResponse>() { @Override public void onSuccess(BanResponse result) { switch (result.getBan().getDelayState()) { case EXECUTED: sender.sendMessage(ChatColor.GREEN + "Unban executed"); break; case QUEUED: sender.sendMessage(ChatColor.GREEN + "Unban will be executed soon."); break; } } @Override public void onFailure(Throwable t) { sender.sendMessage(ChatColor.RED + "Unban was not executed successfully."); LOGGER.log(Level.SEVERE, "An error occurred while executing unban request.", t); } }); } @Override public void onFailure(Throwable t) { } }); return true; }
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 w w .j a v a 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: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//from w w w . j a va 2 s . c o 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:io.crate.executor.transport.task.UpsertTask.java
@Override public void start() { if (subTasks.size() == 0) { ((SettableFuture) resultList.get(0)).set(RowCountResult.EMPTY_RESULT); return;//from w w w. j a va2 s . co 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.whispersystems.textsecuregcm.push.APNSender.java
public ListenableFuture<ApnResult> sendMessage(final ApnMessage message) throws TransientPushFailureException { String topic = bundleId;/*from ww w . java 2 s . c o m*/ if (message.isVoip()) { topic = topic + ".voip"; } ListenableFuture<ApnResult> future = apnsClient.send(message.getApnId(), topic, message.getMessage(), new Date(message.getExpirationTime())); Futures.addCallback(future, new FutureCallback<ApnResult>() { @Override public void onSuccess(@Nullable ApnResult result) { if (result == null) { logger.warn("*** RECEIVED NULL APN RESULT ***"); } else if (result.getStatus() == ApnResult.Status.NO_SUCH_USER) { handleUnregisteredUser(message.getApnId(), message.getNumber(), message.getDeviceId()); } else if (result.getStatus() == ApnResult.Status.GENERIC_FAILURE) { logger.warn("*** Got APN generic failure: " + result.getReason() + ", " + message.getNumber()); } } @Override public void onFailure(@Nullable Throwable t) { logger.warn("Got fatal APNS exception", t); } }, executor); return future; }
From source file:org.opencms.ui.components.extensions.CmsWindowExtension.java
/** * Tries to open a new browser window.<p> * * If openning the window fails, the given callback is called.<p> * * @param location the URL to open in the new window * @param target the target window name//from www . java 2s. c o m * * @param onFailure the callback to call if opening the window fails */ public void open(String location, String target, final Runnable onFailure) { String id = RandomStringUtils.randomAlphanumeric(16); m_callbackMap.put(id, new FutureCallback<Boolean>() { public void onFailure(Throwable t) { // } public void onSuccess(Boolean result) { if (!result.booleanValue()) { onFailure.run(); } } }); getRpcProxy(I_CmsWindowClientRpc.class).open(location, target, id); }