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:com.bluecollarcoder.api.rest.MotionComponent.java
@POST @Consumes(MediaType.APPLICATION_JSON)//w ww. j a v a2s . c om @Produces(MediaType.TEXT_PLAIN) public void recordMotion(@Suspended final AsyncResponse resp) { FutureCallback<UserRecordResult> callback = new FutureCallback<UserRecordResult>() { @Override public void onSuccess(UserRecordResult v) { resp.resume("Successfully submitted motion record " + completed.incrementAndGet()); } @Override public void onFailure(Throwable thrwbl) { resp.resume(thrwbl); } }; ListenableFuture<UserRecordResult> future = producer.addUserRecord(STREAM, PARTITION, ByteBuffer.allocate(Long.SIZE).putLong(submitted.get())); Futures.addCallback(future, callback); }
From source file:de.cuseb.bilderbuch.images.ImageSearchService.java
public ImageResponse searchImages(final String query) { final ImageResponse response = new ImageResponse(); final ListeningExecutorService executor = MoreExecutors .listeningDecorator(Executors.newFixedThreadPool(searches.size())); for (final ImageSearch search : searches.values()) { if (!search.isEnabled()) { continue; }/*from w w w . ja v a2 s . co m*/ ListenableFuture<List<Image>> searchResult = executor.submit(new Callable<List<Image>>() { @Override public List<Image> call() throws Exception { log.debug("starting enabled search " + search.getClass().getSimpleName()); return search.searchImages(query); } }); Futures.addCallback(searchResult, new FutureCallback<List<Image>>() { @Override public void onSuccess(List<Image> result) { log.debug(search.getClass().getSimpleName() + " result size: " + result.size()); response.addImages(result); } @Override public void onFailure(Throwable t) { log.error(search.getClass().getSimpleName(), t); } }); } try { executor.shutdown(); executor.awaitTermination(timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("awaitTermination interrupted", e); } if (shuffle) { log.debug("shuffling result"); response.shuffle(); } return response; }
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; }// w w w. ja v a 2 s .co 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:com.google.cloud.pubsub.PollingSubscriberConnection.java
@Override void initialize() { ListenableFuture<Subscription> subscriptionInfo = stub .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS) .getSubscription(GetSubscriptionRequest.newBuilder().setSubscription(subscription).build()); Futures.addCallback(subscriptionInfo, new FutureCallback<Subscription>() { @Override/*from w w w . jav a 2s. co m*/ public void onSuccess(Subscription result) { setMessageDeadlineSeconds(result.getAckDeadlineSeconds()); pullMessages(INITIAL_BACKOFF); } @Override public void onFailure(Throwable cause) { notifyFailed(cause); } }); }
From source file:com.spotify.futures.AsyncRetrier.java
private <T> void startRetry(final SettableFuture<T> future, final Supplier<ListenableFuture<T>> code, final int retries, final long delay, final TimeUnit timeUnit, final Predicate<T> retryCondition) { ListenableFuture<T> codeFuture; try {/*from w w w.j a v a2 s. c om*/ codeFuture = code.get(); } catch (Exception e) { handleFailure(future, code, retries, delay, timeUnit, retryCondition, e); return; } Futures.addCallback(codeFuture, new FutureCallback<T>() { @Override public void onSuccess(T result) { if (retryCondition.apply(result)) { future.set(result); } else { RuntimeException exception = new RuntimeException("Failed retry condition"); handleFailure(future, code, retries, delay, timeUnit, retryCondition, exception); } } @Override public void onFailure(Throwable t) { handleFailure(future, code, retries, delay, timeUnit, retryCondition, t); } }); }
From source file:com.abiquo.bond.api.EventDispatcher.java
/** * Submits a Future to the ExecutorService that will execute the plugin's processEvent method * for the event. Also creates a callback that will be executed when all the plugins have * completed processing the event. The callback method updates the lastEventTimestamp variable. * //from ww w .j a v a 2 s.c o m * @param event the event to be processed by each plugin */ void dispatchEvent(final APIEvent event) { List<ListenableFuture<APIEventResult>> futures = new ArrayList<>(); for (final PluginInterface plugin : plugins) { if (plugin.handlesEventType(event.getClass())) { ListenableFuture<APIEventResult> task = eventDispatcher.submit(() -> plugin.processEvent(event)); futures.add(task); } } if (!futures.isEmpty()) { Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<APIEventResult>>() { @Override public void onSuccess(final List<APIEventResult> results) { for (APIEventResult result : results) { LocalDateTime eventTs = result.getEvent().getTimestamp(); if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventTs)) { lastEventTimestamp = eventTs; logger.info("Last event timestamp updated to {}", lastEventTimestamp); } } } @Override public void onFailure(final Throwable t) { if (t instanceof PluginEventException) { PluginEventException pee = (PluginEventException) t; Optional<APIEvent> optEvent = pee.getAPIEvent(); if (optEvent.isPresent()) { LocalDateTime eventts = optEvent.get().getTimestamp(); if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventts)) { lastEventTimestamp = eventts; } } } else { // There's nothing we can do if any other exception type is thrown as we // won't know which event was being processed. Simply log a message. // Hopefully one of the other plugins will process the event // successfully and that will update the timestamp. If not then the // event will be resubmitted for processing by all plugins if no later // events are successfully processed. logger.error("Processing of event failed", t); } } }); } }
From source file:zipkin.storage.cassandra.DeduplicatingExecutor.java
/** * @param session which conditionally executes bound statements * @param ttl how long the results of statements are remembered, in milliseconds. *///from ww w .j a v a 2 s. c o m DeduplicatingExecutor(Session session, long ttl) { this.session = session; this.cache = CacheBuilder.newBuilder().expireAfterWrite(ttl, TimeUnit.MILLISECONDS).ticker(new Ticker() { @Override public long read() { return nanoTime(); } }) // TODO: maximum size or weight .build(new CacheLoader<BoundStatementKey, ListenableFuture<Void>>() { @Override public ListenableFuture<Void> load(final BoundStatementKey key) { ListenableFuture<?> cassandraFuture = executeAsync(key.statement); // Drop the cassandra future so that we don't hold references to cassandra state for // long periods of time. final SettableFuture<Void> disconnectedFuture = SettableFuture.create(); Futures.addCallback(cassandraFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { disconnectedFuture.set(null); } @Override public void onFailure(Throwable t) { cache.invalidate(key); disconnectedFuture.setException(t); } }); return disconnectedFuture; } }); }
From source file:com.b2international.snowowl.core.events.util.Promise.java
/** * Define what to do when the promise becomes rejected. * //from w w w .j av a 2 s .c o m * @param then * @return */ public final Promise<T> fail(final Function<Throwable, T> fail) { final Promise<T> promise = new Promise<>(); Futures.addCallback(this, new FutureCallback<T>() { @Override public void onSuccess(T result) { promise.resolve(result); } @Override public void onFailure(Throwable t) { try { promise.resolve(fail.apply(t)); } catch (Throwable e) { promise.reject(e); } } }); return promise; }
From source file:$.AddBridgeOnHiveMQStart.java
/** * This method is called from HiveMQ, and the custom behaviour has to be implemented in here. * If some preconditions are not met to successfully operate, a {@link com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException} * should be thrown.// www .j av a 2s . c o m * * @throws com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException If the exception is thrown, HiveMQ will be stopped. */ @Override public void onBrokerStart() throws BrokerUnableToStartException { log.info("Adding Bridge to MQTT Dashboard"); final Bridge bridge = createBridge(); // Start bridge with Bridge Manager Service dynamically final ListenableFuture<Void> future = bridgeManagerService.startBridge(bridge); Futures.addCallback(future, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { log.info("Bridge started successfully"); } @Override public void onFailure(Throwable t) { log.info("Bridge failed to start"); } }); }
From source file:com.facebook.presto.util.AsyncSemaphore.java
private void runNext() { final QueuedTask<T> queuedTask = queuedTasks.poll(); ListenableFuture<?> future = submitTask(queuedTask.getTask()); Futures.addCallback(future, new FutureCallback<Object>() { @Override// ww w .j ava 2s. c o m public void onSuccess(Object result) { queuedTask.markCompleted(); releasePermit(); } @Override public void onFailure(Throwable t) { queuedTask.markFailure(t); releasePermit(); } }); }