/** * 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); } }
/** * @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); }
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); }
@Override public <T> CompletionStage<T> send(final Request<T> request) { final CompletionStage<T> future = delegate.send(request); return CompletableFutures.exceptionallyCompose( future, e -> { e = unwrap(e); if (e instanceof MemcacheClosedException && delegate.isConnected()) { return delegate.send(request); } else { return CompletableFutures.exceptionallyCompletedFuture(e); } }); }
range = normalizeNow(from, to).toAscending(); } catch (Exception e) { return CompletableFutures.exceptionallyCompletedFuture(e); CompletableFutures.combine(fromEntryFuture, toEntryFuture, (fromEntry, toEntry) -> { @SuppressWarnings("unchecked") final Query<Object> castQuery = (Query<Object>) query;
/** * Gets the value of a completed stage. * * @param stage a completed {@link CompletionStage} * @param <T> the type of the value that the stage completes into * @return the value of the stage if it has one * @throws IllegalStateException if the stage is not completed * @since 0.1.0 */ public static <T> T getCompleted(CompletionStage<T> stage) { CompletableFuture<T> future = stage.toCompletableFuture(); checkCompleted(future); return future.join(); }
/** * Gets the value of a completed stage. * * @param stage a completed {@link CompletionStage} * @param <T> the type of the value that the stage completes into * @return the value of the stage if it has one * @throws IllegalStateException if the stage is not completed * @since 0.1.0 */ public static <T> T getCompleted(CompletionStage<T> stage) { CompletableFuture<T> future = stage.toCompletableFuture(); checkCompleted(future); return future.join(); }
@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); } }
private <T> CompletionStage<MemcacheStatus> sendToAll(final Request<T> request) { List<CompletionStage<MemcacheStatus>> futures = clients .stream() .map(client -> (CompletionStage<MemcacheStatus>) client.send(request)) .collect(Collectors.toList()); return CompletableFutures.allAsList(futures) .thenApply( ts -> ts.stream() .filter(status -> status != MemcacheStatus.OK) .findFirst() .orElse(MemcacheStatus.OK)); }
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 public void listRepositories(String projectName, AsyncMethodCallback resultHandler) { handle(allAsList(projectManager.get(projectName).repos().list().entrySet().stream() .map(e -> convert(e.getKey(), e.getValue())) .collect(toList())), resultHandler); }
@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; } }
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);
private CompletionStage<Response<ByteString>> haltActiveBackfillInstances(Backfill backfill, Client client) { return CompletableFutures.allAsList( retrieveBackfillStatuses(backfill).stream() .filter(BackfillResource::isActiveState) .map(RunStateData::workflowInstance) .map(workflowInstance -> haltActiveBackfillInstance(workflowInstance, client)) .collect(toList())) .handle((result, throwable) -> { if (throwable != null || result.contains(Boolean.FALSE)) { return Response.forStatus( Status.INTERNAL_SERVER_ERROR .withReasonPhrase( "some active instances cannot be halted, however no new ones will be triggered")); } else { return Response.ok(); } }); }
@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); } }
submitted = true; } catch (Exception e) { return exceptionallyCompletedFuture(e); } finally { if (!submitted) {
private CompletionStage<List<GetResult<V>>> multiget(List<byte[]> keys, int ttl) { final int size = keys.size(); if (size == 0) { return CompletableFuture.completedFuture(Collections.<GetResult<V>>emptyList()); } final List<List<byte[]>> keyPartition = Lists.partition(keys, MemcacheEncoder.MAX_MULTIGET_SIZE); final List<CompletionStage<List<GetResult<byte[]>>>> futureList = new ArrayList<>(keyPartition.size()); for (final List<byte[]> part : keyPartition) { MultigetRequest request = MultigetRequest.create(part, ttl); futureList.add(rawMemcacheClient.send(request)); } final CompletionStage<List<GetResult<byte[]>>> future = CompletableFutures.allAsList(futureList).thenApply(Utils.flatten()); metrics.measureMultigetFuture(future); return transformerUtil.decodeList(future); }
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()); })); }