/** * Determines if the specified {@code data} is authorized for this service. If the result resolves * to {@code true}, the request is authorized, or {@code false} otherwise. If the future resolves * exceptionally, the request will not be authorized. */ static <T> CompletionStage<Boolean> authorize(Authorizer<T> authorizer, ServiceRequestContext ctx, T data) { try { final CompletionStage<Boolean> f = authorizer.authorize(ctx, data); if (f == null) { throw new NullPointerException("An " + Authorizer.class.getSimpleName() + " returned null: " + authorizer); } return f; } catch (Throwable cause) { return CompletableFutures.exceptionallyCompletedFuture(cause); } }
public CompletableFuture<List<Task>> describe() { return new PaginatedResponseIterator<>(ListTasksResponse::nextToken, this::list) .stream() .map(ListTasksResponse::taskArns) .filter(arns -> !arns.isEmpty()) .map(this::describeTasks) .collect(CompletableFutures.joinList()) .thenApply(this::extractTasksFromResponses); }
private CompletableFuture<Void> checkAndUpdateHealthyServers() { final List<ServerConnection> checkedServers = updateServerList(); final CompletableFuture<List<Boolean>> healthCheckResults = CompletableFutures.successfulAsList( checkedServers.stream() .map(connection -> connection.healthChecker.isHealthy(connection.endpoint())) .collect(toImmutableList()), t -> false); return healthCheckResults.handle((result, thrown) -> { final ImmutableList.Builder<Endpoint> newHealthyEndpoints = ImmutableList.builder(); for (int i = 0; i < result.size(); i++) { if (result.get(i)) { newHealthyEndpoints.add(checkedServers.get(i).endpoint()); } } setEndpoints(newHealthyEndpoints.build()); return null; }); }
/** * @param eventHandler the {@link EventHandler} for which the actions are to be executed * @param msg the {@link Message} that triggered the event * @return a {@link CompletableFuture} holding a list of {@link EventExecution}s for the {@link Action}s executed in the event handler */ private CompletableFuture<List<EventExecution>> executeActionsForEventHandler(EventHandler eventHandler, Message msg) { List<CompletableFuture<EventExecution>> futuresList = new ArrayList<>(); int i = 0; for (Action action : eventHandler.getActions()) { String id = msg.getId() + "_" + i++; EventExecution eventExecution = new EventExecution(id, msg.getId()); eventExecution.setCreated(System.currentTimeMillis()); eventExecution.setEvent(eventHandler.getEvent()); eventExecution.setName(eventHandler.getName()); eventExecution.setAction(action.getAction()); eventExecution.setStatus(Status.IN_PROGRESS); if (executionService.addEventExecution(eventExecution)) { futuresList.add(CompletableFuture.supplyAsync(() -> execute(eventExecution, action, getPayloadObject(msg.getPayload())), executorService)); } else { logger.warn("Duplicate delivery/execution of message: {}", msg.getId()); } } return CompletableFutures.allAsList(futuresList); }
@Override public void accept(V v, Throwable throwable) { if (throwable != null) { if (throwable instanceof CancellationException) { cancel(false); } else { setException(CompletableToListenableFutureWrapper.unwrapThrowable(throwable)); } } else { set(v); } } }
/** * Wrap a {@link CompletionStage} in a {@link ApiFuture}. The returned future will * complete with the same result or failure as the original future. * * @param future The {@link CompletionStage} to wrap in a {@link ApiFuture}. * @return A {@link ApiFuture} that completes when the original future completes. */ public static <V> ApiFuture<V> toApiFuture(CompletionStage<V> future) { if (future instanceof ApiFutureToCompletableFutureWrapper) { return ((ApiFutureToCompletableFutureWrapper<V>) future).unwrap(); } return new CompletableToApiFutureWrapper<>(future); }
/** * @param maxConcurrency maximum number of futures in progress, * @param maxQueueSize maximum number of jobs in queue. This is a soft bound and may be * temporarily exceeded if add() is called concurrently. * @return a new concurrency limiter */ public static <T> ConcurrencyReducer<T> create(int maxConcurrency, int maxQueueSize) { return new ConcurrencyReducer<>(maxConcurrency, maxQueueSize); }
@Override public void onFailure(final Throwable t) { completeExceptionally(t); } }
/** * A lambda-friendly way to attach a callback to a {@link ListenableFuture}. The callback will * only be run if the future fails. * @param future a ListenableFuture to attach the callback to. * @param consumer a consumer, to be called with the result of the failed future. */ public static <T> void addFailureCallback( final ListenableFuture<T> future, final Consumer<Throwable> consumer, final Executor executor) { addCallback(future, null, consumer, executor); }
@Override public CompletableFuture<AggregatedHttpFile> aggregateWithPooledObjects(Executor fileReadExecutor, ByteBufAllocator alloc) { try { final HttpFile file = getFile(); return file != null ? file.aggregateWithPooledObjects(fileReadExecutor, alloc) : CompletableFuture.completedFuture(HttpFile.nonExistent()); } catch (Exception e) { return CompletableFutures.exceptionallyCompletedFuture(e); } }
public CompletableFuture<List<ContainerInstance>> describe() { return new PaginatedResponseIterator<>(ListContainerInstancesResponse::nextToken, this::list) .stream() .map(ListContainerInstancesResponse::containerInstanceArns) .filter(arns -> !arns.isEmpty()) .map(this::describeContainerInstances) .collect(CompletableFutures.joinList()) .thenApply(this::extractContainerInstancesFromResponses); }
@Override public CompletableFuture<AggregatedHttpFile> aggregate(Executor fileReadExecutor) { try { final HttpFile file = getFile(); return file != null ? file.aggregate(fileReadExecutor) : CompletableFuture.completedFuture(HttpFile.nonExistent()); } catch (Exception e) { return CompletableFutures.exceptionallyCompletedFuture(e); } }
@Override @SneakyThrows // TODO add checked exception handling public Void handleRequest(CloudWatchEvent<Map> input, Context context) { log.debug("Reconciler request: {}", input); ListClustersResponse r = dataService.listClusters(ListClustersRequest.builder().build()); List<Cluster> clusters = r.getClusters(); clusters .stream() .map(c -> stateFunction.triggerAsync(new ManagerInput(c))) .collect(CompletableFutures.joinList()) .join(); return null; } }
submitted = true; } catch (Exception e) { return exceptionallyCompletedFuture(e); } finally { if (!submitted) {
@Override @SneakyThrows // TODO add checked exception handling public ManagerOutput handleRequest(ManagerInput input, Context context) { log.debug("Manager request: {}", input); ListEnvironmentsResponse r = data.listEnvironments( ListEnvironmentsRequest.builder().cluster(input.getCluster()).build()); List<EnvironmentId> environments = r.getEnvironmentIds(); ClusterSnapshot state = ecs.snapshotState(input.getCluster().getClusterName()); Stream<CompletableFuture<SchedulerOutput>> pendingRequests = environments .stream() .map(environmentId -> scheduler.callAsync(new SchedulerInput(state, environmentId))); List<SchedulerOutput> outputs = pendingRequests.collect(CompletableFutures.joinList()).join(); return new ManagerOutput(input.getCluster(), outputs); } }
case STARTED: if (failIfStarted) { return exceptionallyCompletedFuture( new IllegalStateException("must be stopped to start; currently " + state)); } else { submitted = true; } catch (Exception e) { return exceptionallyCompletedFuture(e); } finally { if (!submitted) { }); return rollbackFuture.<V>thenCompose(unused -> exceptionallyCompletedFuture(cause)); } else { enter(State.STARTED, result);
actions.stream().map(a -> a.execute(ecs)).collect(CompletableFutures.joinList()).join();
@Test public void transferFailure_Throwable() { @SuppressWarnings("unchecked") final AsyncMethodCallback<String> callback = mock(AsyncMethodCallback.class); AsyncMethodCallbacks.transfer(exceptionallyCompletedFuture(new Throwable("foo")), callback); verify(callback, only()).onError(argThat(argument -> { return argument instanceof CompletionException && "foo".equals(argument.getCause().getMessage()); })); }
@Test public void transferFailure_Exception() { @SuppressWarnings("unchecked") final AsyncMethodCallback<String> callback = mock(AsyncMethodCallback.class); AsyncMethodCallbacks.transfer(exceptionallyCompletedFuture(new AnticipatedException()), callback); verify(callback, only()).onError(isA(AnticipatedException.class)); }
attrs = readAttributes(); } catch (IOException e) { return CompletableFutures.exceptionallyCompletedFuture(e); return CompletableFutures.exceptionallyCompletedFuture( new IOException("too large to aggregate: " + attrs.length() + " bytes")); in = newStream(); } catch (IOException e) { return CompletableFutures.exceptionallyCompletedFuture(e);