@Nonnull private CompletionStage<Optional<String>> cacheAndFetch(@Nonnull final String key) { final Consumer<List<TaxCategory>> taxCategoryPageConsumer = taxCategoryPage -> taxCategoryPage.forEach(taxCategory -> { final String fetchedTaxCategoryKey = taxCategory.getKey(); final String id = taxCategory.getId(); if (StringUtils.isNotBlank(fetchedTaxCategoryKey)) { keyToIdCache.put(fetchedTaxCategoryKey, id); } else { syncOptions.applyWarningCallback(format("TaxCategory with id: '%s' has no key set. Keys are" + " required for taxCategory matching.", id)); } }); return CtpQueryUtils.queryAll(syncOptions.getCtpClient(), TaxCategoryQuery.of(), taxCategoryPageConsumer) .thenApply(result -> Optional.ofNullable(keyToIdCache.get(key))); }
/** * Given an {@link InventoryEntryDraftBuilder} and a {@code channelKey} this method fetches the actual id of the * channel corresponding to this key, ideally from a cache. Then it sets this id on the supply channel reference * id of the inventory entry draft builder. If the id is not found in cache nor the CTP project * and {@code ensureChannel} option is set to true, a new channel will be created with this key * and the role {@code "InventorySupply"}. * However, if the {@code ensureChannel} is set to false, the future is completed exceptionally with a * {@link ReferenceResolutionException}. * * @param draftBuilder the inventory draft builder to read it's values (key, sku, channel) * and then to write resolved references. * @param channelKey the key of the channel to resolve it's actual id on the draft. * @return a {@link CompletionStage} that contains as a result the same {@code draftBuilder} inventory draft builder * instance with resolved supply channel reference or an exception. */ @Nonnull private CompletionStage<InventoryEntryDraftBuilder> fetchOrCreateAndResolveReference( @Nonnull final InventoryEntryDraftBuilder draftBuilder, @Nonnull final String channelKey) { final CompletionStage<InventoryEntryDraftBuilder> inventoryEntryDraftCompletionStage = channelService .fetchCachedChannelId(channelKey) .thenCompose(resolvedChannelIdOptional -> resolvedChannelIdOptional .map(resolvedChannelId -> setChannelReference(resolvedChannelId, draftBuilder)) .orElseGet(() -> createChannelAndSetReference(channelKey, draftBuilder))); final CompletableFuture<InventoryEntryDraftBuilder> result = new CompletableFuture<>(); inventoryEntryDraftCompletionStage .whenComplete((resolvedDraftBuilder, exception) -> { if (exception != null) { result.completeExceptionally( new ReferenceResolutionException(format(FAILED_TO_RESOLVE_SUPPLY_CHANNEL, draftBuilder.getSku(), exception.getCause().getMessage()), exception)); } else { result.complete(resolvedDraftBuilder); } }); return result; }
@Override public CompletionStage<Void> close() { // first despawn on the local node distributedShardedDOMDataTree.despawnShardFrontend(prefix); // update the config so the remote nodes are updated final Future<Object> ask = Patterns.ask(shardedDataTreeActor, new PrefixShardRemovalLookup(prefix), SHARD_FUTURE_TIMEOUT); final Future<Void> closeFuture = ask.transform( new Mapper<Object, Void>() { @Override public Void apply(final Object parameter) { return null; } }, new Mapper<Throwable, Throwable>() { @Override public Throwable apply(final Throwable throwable) { return throwable; } }, actorSystem.dispatcher()); return FutureConverters.toJava(closeFuture); }
@Test public void returnValueAndExceptionRetriedButStillReturnBad() throws Exception { Delay<Throwable> exceptionDelay = spy(ofSeconds(1)); Delay<String> returnValueDelay = spy(ofSeconds(1)); Retryer.ForReturnValue<String> forReturnValue = retryer .upon(IOException.class, asList(exceptionDelay)) .uponReturn("bad", asList(returnValueDelay, returnValueDelay)); IOException exception = new IOException(); when(action.run()) .thenReturn("bad").thenThrow(exception).thenReturn("bad").thenReturn("bad") .thenReturn("fixed"); CompletionStage<String> stage = forReturnValue.retry(action::run, executor); assertPending(stage); elapse(4, Duration.ofSeconds(1)); assertCompleted(stage).isEqualTo("bad"); verify(action, times(4)).run(); verify(returnValueDelay, times(2)).beforeDelay("bad"); verify(returnValueDelay, times(2)).afterDelay("bad"); verify(exceptionDelay).beforeDelay(exception); verify(exceptionDelay).afterDelay(exception); }
public CompletionStage<Result> call(final Http.Context ctx) { String username = ctx.session().get("username"); Long postId = Long.parseLong(ctx.request().getQueryString("id")); Optional<PostDTO> optionalPost = postService.getPost(postId); if (!optionalPost.isPresent()) { // Post doesn't exists, return notFound return CompletableFuture.completedFuture(notFound()); } else if (!optionalPost.get().username.equals(username)) { // User is not the owner of Post, show him Login form Result login = unauthorized(views.html.login.render( loginDTOForm.withGlobalError("Please login with proper credentials to modify this post"))); return CompletableFuture.completedFuture(login); } else { // Post exists and User is the owner of Post, call delegate return delegate.call(ctx); } }
/** * Given an {@link PriceDraftBuilder} and a {@code channelKey} this method fetches the actual id of the * channel corresponding to this key, ideally from a cache. Then it sets this id on the supply channel reference * id of the inventory entry draft. If the id is not found in cache nor the CTP project and {@code ensureChannel} * option is set to true, a new channel will be created with this key and the role {@code "InventorySupply"}. * However, if the {@code ensureChannel} is set to false, the future is completed exceptionally with a * {@link ReferenceResolutionException}. * * @param draftBuilder the price draft builder where to set resolved references. * @param channelKey the key of the channel to resolve it's actual id on the draft. * @return a {@link CompletionStage} that contains as a result the same {@code draft} instance with resolved * supply channel reference or an exception. */ @Nonnull private CompletionStage<PriceDraftBuilder> fetchOrCreateAndResolveReference( @Nonnull final PriceDraftBuilder draftBuilder, @Nonnull final String channelKey) { final CompletionStage<PriceDraftBuilder> priceDraftCompletionStage = channelService .fetchCachedChannelId(channelKey) .thenCompose(resolvedChannelIdOptional -> resolvedChannelIdOptional .map(resolvedChannelId -> setChannelReference(resolvedChannelId, draftBuilder)) .orElseGet(() -> createChannelAndSetReference(channelKey, draftBuilder))); final CompletableFuture<PriceDraftBuilder> result = new CompletableFuture<>(); priceDraftCompletionStage .whenComplete((resolvedDraft, exception) -> { if (exception != null) { result.completeExceptionally( new ReferenceResolutionException(format(FAILED_TO_RESOLVE_CHANNEL, draftBuilder.getCountry(), draftBuilder.getValue(), exception.getMessage()), exception)); } else { result.complete(resolvedDraft); } }); return result; }
/** * Given a list of inventory entry {@code drafts}, this method resolves the references of each entry and attempts to * sync it to the CTP project depending whether the references resolution was successful. In addition the given * {@code oldInventories} list is converted to a {@link Map} of an identifier to an inventory entry, for a resources * comparison reason. * * @param oldInventories inventory entries from CTP * @param inventoryEntryDrafts drafts that need to be synced * @return a future which contains an empty result after execution of the update */ private CompletionStage<InventorySyncStatistics> syncBatch(@Nonnull final List<InventoryEntry> oldInventories, @Nonnull final List<InventoryEntryDraft> inventoryEntryDrafts) { final Map<InventoryEntryIdentifier , InventoryEntry> identifierToOldInventoryEntry = oldInventories .stream().collect(toMap(InventoryEntryIdentifier::of, identity())); final List<CompletableFuture<Void>> futures = new ArrayList<>(inventoryEntryDrafts.size()); inventoryEntryDrafts.forEach(inventoryEntryDraft -> futures.add(referenceResolver.resolveReferences(inventoryEntryDraft) .thenCompose(resolvedDraft -> syncDraft(identifierToOldInventoryEntry, resolvedDraft)) .exceptionally(referenceResolutionException -> { final String errorMessage = format(FAILED_TO_RESOLVE_REFERENCES, inventoryEntryDraft.getSku(), referenceResolutionException.getMessage()); handleError(errorMessage, referenceResolutionException, 1); return null; }) .toCompletableFuture())); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(result -> statistics); }
/** * POST /projects * * <p>Creates a new project. */ @Post("/projects") @ResponseConverter(CreateApiResponseConverter.class) public CompletionStage<ProjectDto> createProject(@RequestObject CreateProjectRequest request, @RequestObject Author author) { return mds.createProject(request.name(), author, request.owners(), request.members()) .thenCompose(projectInfo -> execute(Command.createProject(author, projectInfo.name()))) .handle((unused, thrown) -> { try { if (thrown == null) { return DtoConverter.convert(projectManager().get(request.name())); } else { return Exceptions.throwUnsafely(thrown); } } finally { if (thrown != null) { // Remove created project from metadata. mds.removeProject(request.name(), author); } } }); }
/** * GET /projects/{projectName}/repositories/{repository}/files/revisions/{revision}{path} * Returns the blob in the path. */ @Get("regex:/projects/(?<projectName>[^/]+)/repositories/(?<repositoryName>[^/]+)" + "/files/revisions/(?<revision>[^/]+)(?<path>/.*$)") public CompletionStage<EntryWithRevisionDto> getFile(@Param("projectName") String projectName, @Param("repositoryName") String repositoryName, @Param("revision") String revision, @Param("path") String path, @Param("queryType") Optional<String> queryType, @Param("expression") Optional<String> expressions) { final Query<?> query = Query.of(QueryType.valueOf(queryType.orElse("IDENTITY")), path, expressions.orElse("")); final Repository repo = projectManager().get(projectName).repos().get(repositoryName); return repo.normalize(new Revision(revision)) .thenCompose(normalized -> repo.get(normalized, query)) .thenApply(queryResult -> DtoConverter.convert(path, queryResult)); }
private CompletionStage<Response<ByteString>> compose(final RequestContext context, final RouteMatch match, final Response<ByteString> response) { if (match.shouldProxy()) { return CompletableFuture.completedFuture(response); } if (response.status().code() != Status.OK.code() || !response.payload().isPresent()) { // Do whatever suits your environment, retrieve the data from a cache, // re-execute the request or just fail. return defaultResponse(); } final String responseAsUtf8 = response.payload().get().utf8(); return composerFactory.build(context.requestScopedClient(), match.parsedPathArguments()) .composeTemplate(response.withPayload(responseAsUtf8)) .thenApply(r -> toByteString(r) .withHeaders(transformHeaders(response.headerEntries()))); }
@Override public CompletionStage<? extends ShardBackendInfo> refreshBackendInfo(final Long cookie, final ShardBackendInfo staleInfo) { final ShardState existing = state; if (existing != null) { if (!staleInfo.equals(existing.getResult())) { return existing.getStage(); } synchronized (this) { LOG.debug("Invalidating backend information {}", staleInfo); flushCache(shardName); LOG.trace("Invalidated cache %s", staleInfo); state = null; } } return getBackendInfo(cookie); }
@Nonnull private CompletionStage<Optional<String>> cacheAndFetch(@Nonnull final String key) { final Consumer<List<ProductType>> productTypePageConsumer = productTypePage -> productTypePage.forEach(type -> { final String fetchedTypeKey = type.getKey(); final String id = type.getId(); productsAttributesMetaData.put(id, getAttributeMetaDataMap(type)); if (StringUtils.isNotBlank(fetchedTypeKey)) { keyToIdCache.put(fetchedTypeKey, id); } else { syncOptions.applyWarningCallback(format("ProductType with id: '%s' has no key set. Keys are" + " required for productType matching.", id)); } }); return CtpQueryUtils.queryAll(syncOptions.getCtpClient(), ProductTypeQuery.of(), productTypePageConsumer) .thenAccept(result -> isCached = true) .thenApply(result -> Optional.ofNullable(keyToIdCache.get(key))); }
/** * Given a {@link ProductDraftBuilder} this method attempts to resolve the categories and categoryOrderHints to * return a {@link CompletionStage} which contains a new instance of the builder with the resolved references. * The key of the category references is either taken from the expanded references or taken from the value of the * id fields. * * @param draftBuilder the productDraft to resolve its category and categoryOrderHints references. * @return a {@link CompletionStage} that contains as a result a new builder instance with resolved references or, * in case an error occurs during reference resolution, a {@link ReferenceResolutionException}. */ @Nonnull public CompletionStage<ProductDraftBuilder> resolveCategoryReferences( @Nonnull final ProductDraftBuilder draftBuilder) { final Set<ResourceIdentifier<Category>> categoryResourceIdentifiers = draftBuilder.getCategories(); final Set<String> categoryKeys = new HashSet<>(); for (ResourceIdentifier<Category> categoryResourceIdentifier: categoryResourceIdentifiers) { if (categoryResourceIdentifier != null) { try { final String categoryKey = getKeyFromResourceIdentifier(categoryResourceIdentifier, options.shouldAllowUuidKeys()); categoryKeys.add(categoryKey); } catch (ReferenceResolutionException referenceResolutionException) { return exceptionallyCompletedFuture( new ReferenceResolutionException( format(FAILED_TO_RESOLVE_REFERENCE, categoryResourceIdentifier.getTypeId(), draftBuilder.getKey(),referenceResolutionException.getMessage()))); } } } return fetchAndResolveCategoryReferences(draftBuilder, categoryKeys); }
@Override public CompletionStage<JobServiceModel> scheduleDeviceMethodAsync( String jobId, String queryCondition, MethodParameterServiceModel parameter, Date startTime, long maxExecutionTimeInSeconds) throws ExternalDependencyException { try { JobResult result = this.jobClient.scheduleDeviceMethod( jobId, queryCondition, parameter.getName(), parameter.getResponseTimeout() == null ? null : parameter.getResponseTimeout().getSeconds(), parameter.getConnectionTimeout() == null ? null : parameter.getConnectionTimeout().getSeconds(), parameter.getJsonPayload(), startTime, maxExecutionTimeInSeconds); JobServiceModel jobModel = new JobServiceModel(result, null); return CompletableFuture.supplyAsync(() -> jobModel); } catch (IOException | IotHubException e) { String message = String.format("Unable to schedule device method job: %s, %s, %s", jobId, queryCondition, Json.stringify(Json.toJson(parameter))); log.error(message, e); throw new ExternalDependencyException(message, e); } }
/** * Used to render the Gradle configuration for a specific repository slug, access_token and version combination. * Will fetch the latest plugin version if it has not already been cached. * @param slug * @return */ public CompletionStage<Result> configForSlug(String slug) { final Http.Context context = Http.Context.current(); return wsClient.url("https://api.bintray.com/packages/btkelly/maven/gnag-gradle-plugin/versions/_latest") .setHeader("accept", "application/json") .setRequestTimeout(10 * 1000) .get() .thenApply(response -> { String latestVersion = response.asJson().get("name").asText(); return ok(gnagconfig.render(slug, context.session().get(TOKEN_KEY), latestVersion)); }); }
/** * Unregisters a cluster and closes all listening network interfaces associated with it. * * <p>If the cluster is not currently registered the returned future will fail with an {@link * IllegalArgumentException}. * * @param clusterId id of the cluster. * @return A future that when completed provides the unregistered cluster as it existed in the * registry, may not be the same object as the input. */ public CompletionStage<BoundCluster> unregisterAsync(Long clusterId) { if (isClosed()) { return failByClose(); } CompletableFuture<BoundCluster> future = new CompletableFuture<>(); if (clusterId == null) { future.completeExceptionally(new IllegalArgumentException("Null id provided")); } else { BoundCluster foundCluster = clusters.remove(clusterId); List<CompletableFuture<BoundNode>> closeFutures = new ArrayList<>(); if (foundCluster != null) { // Close socket on each node. for (BoundDataCenter dataCenter : foundCluster.getDataCenters()) { for (BoundNode node : dataCenter.getNodes()) { closeFutures.add(close(node)); } } CompletableFuture.allOf(closeFutures.toArray(new CompletableFuture[] {})) .whenComplete( (__, ex) -> { if (ex != null) { future.completeExceptionally(ex); } else { future.complete(foundCluster); } }); } else { future.completeExceptionally(new IllegalArgumentException("ClusterSpec not found.")); } } return future; }
/** * GET /projects/{projectName}/repos/{repoName}/tree{path}?revision={revision} * * <p>Returns the list of files in the path. */ @Get("regex:/projects/(?<projectName>[^/]+)/repos/(?<repoName>[^/]+)/tree(?<path>(|/.*))$") public CompletionStage<List<EntryDto<?>>> listFiles(@Param("path") String path, @Param("revision") @Default("-1") String revision, @RequestObject Repository repository) { final String path0 = rootDirIfEmpty(path); return listFiles(repository, path0, new Revision(revision), ImmutableMap.of(FindOption.FETCH_CONTENT, false)); }
private static CompletionStage<Object> handleWatchSuccess(Repository repository, Revision revision, String pathPattern) { final CompletableFuture<List<Commit>> historyFuture = repository.history(revision, revision, pathPattern); return repository.find(revision, pathPattern) .thenCombine(historyFuture, (entryMap, commits) -> { // the size of commits should be 1 return DtoConverter.convert(commits.get(0), entryMap.values(), repository.parent().name(), repository.name()); }); }
@Override public CompletionStage<RunOutput> runPrepared(String id, boolean daemonize) { return RktCommandHelper.sendRequest(client, RktCommandHelper.uri(apiHost, ImmutableMap .of("daemonize", ImmutableList.of(Boolean.toString(daemonize))), "run-prepared", id), RunOutput.class); }
@Override protected CompletionStage<ProductSyncStatistics> syncBatches(@Nonnull final List<List<ProductDraft>> batches, @Nonnull final CompletionStage<ProductSyncStatistics> result) { if (batches.isEmpty()) { return result; } final List<ProductDraft> firstBatch = batches.remove(0); return syncBatches(batches, result.thenCompose(subResult -> processBatch(firstBatch))); }
@Override @SuppressWarnings("unchecked") public T get(int index) { assertState(isDone(), "The PromisedValues MUST be complete before calling the get() method"); try { CompletionStage<T> future = futures.get(index); return future.toCompletableFuture().get(); } catch (InterruptedException | ExecutionException e) { return null; } }
@Override public <U> StagedFutureTimeout<U> thenIf(Function<T, Optional<U>> proc) { Objects.requireNonNull(proc, "proc cannot be null"); // don't burn a thread if the optional is empty CompletionStage<Optional<U>> nextStage = future.thenCompose(optional -> { if (optional.isPresent()) { Function<T, Optional<U>> tracedProc = tracingProc(tracing, proc); return future.thenApplyAsync(__ -> tracedProc.apply(optional.get()), executor); } return CompletableFuture.completedFuture(Optional.empty()); }); return new StagedFutureImpl<>(executor, nextStage, tracing); }
/** * Given a {@link ProductDraftBuilder} this method attempts to resolve the product type to return a * {@link CompletionStage} which contains a new instance of the builder with the resolved product type reference. * The key of the product type reference is either taken from the expanded reference or taken from the value of the * id field. * * @param draftBuilder the productDraft to resolve its product type reference. * @return a {@link CompletionStage} that contains as a result a new builder instance with resolved product type * reference or, in case an error occurs during reference resolution, * a {@link ReferenceResolutionException}. */ @Nonnull public CompletionStage<ProductDraftBuilder> resolveProductTypeReference( @Nonnull final ProductDraftBuilder draftBuilder) { final ResourceIdentifier<ProductType> productTypeResourceIdentifier = draftBuilder.getProductType(); return getProductTypeId(productTypeResourceIdentifier, format(FAILED_TO_RESOLVE_PRODUCT_TYPE, draftBuilder.getKey())) .thenApply(resolvedProductTypeIdOptional -> { resolvedProductTypeIdOptional.ifPresent(resolvedTypeId -> draftBuilder .productType(ResourceIdentifier.ofId(resolvedTypeId, ProductType.referenceTypeId()))); return draftBuilder; }); }
protected Object adapt(Object result) { if (result instanceof CompletionStage) { CompletionStage<Object> stage = (CompletionStage<Object>) result; return Single.create(emitter -> stage.whenComplete((it, e) -> { if (e != null) { emitter.onError(e); } else { emitter.onSuccess(it); } })).toFlowable(); } return result; }
@Override public CompletionStage<FetchOutput> fetch(final boolean async, final String image, String... images) { return RktCommandHelper.sendRequest( client, RktCommandHelper.uri(apiHost, ImmutableMap.of("async", ImmutableList.of(Boolean.toString(async)), "image", RktCommandHelper.merge(image, images)), "fetch"), FetchOutput.class); }
@Override protected CompletionStage<CategorySyncStatistics> syncBatches(@Nonnull final List<List<CategoryDraft>> batches, @Nonnull final CompletionStage<CategorySyncStatistics> result) { if (batches.isEmpty()) { return result; } final List<CategoryDraft> firstBatch = batches.remove(0); return syncBatches(batches, result.thenCompose(subResult -> processBatch(firstBatch))); }
@Override public CompletionStage<Collection<String>> getPermittedCourses(User user) throws MalformedURLException { URL url = parseUrl(user); WSRequest request = wsClient.url(url.toString().split("\\?")[0]); if (url.getQuery() != null) { request = request.setQueryString(url.getQuery()); } RemoteFunction<WSResponse, Collection<String>> onSuccess = response -> { JsonNode root = response.asJson(); if (root.has("exception")) { throw new RemoteException(root.get("exception").asText()); } else if (root.has("data")) { Set<String> results = new HashSet<>(); for (JsonNode course : root.get("data")) { if (course.has("course_code")) { results.add(course.get("course_code").asText()); } else { Logger.warn("Unexpected content {}", course.asText()); } } return results; } else { Logger.warn("Unexpected content {}", root.asText()); throw new RemoteException("sitnet_request_timed_out"); } }; return request.get().thenApplyAsync(onSuccess); }
public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { final CompletableFuture<Stage> upcomingStage = new CompletableFuture<>(); Platform.runLater(() -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); upcomingStage.complete(stage); }); return upcomingStage; }
@Nonnull @Override public CompletionStage<List<InventoryEntry>> fetchInventoryEntriesBySkus(@Nonnull final Set<String> skus) { final InventoryEntryQuery query = InventoryEntryQueryBuilder.of() .plusPredicates( queryModel -> queryModel.sku().isIn(skus)) .build(); return QueryExecutionUtils.queryAll(ctpClient, query); }
@Test public void should_Build_a_really_really_simple_data_loader() { AtomicBoolean success = new AtomicBoolean(); DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keysAsValues()); CompletionStage<Integer> future1 = identityLoader.load(1); future1.thenAccept(value -> { assertThat(value, equalTo(1)); success.set(true); }); identityLoader.dispatch(); await().untilAtomic(success, is(true)); }
public CompletionStage<Result> scheduleJobAsync() throws NotSupportedException, ExternalDependencyException { JsonNode json = request().body().asJson(); final JobApiModel jobApiModel = fromJson(json, JobApiModel.class); if (jobApiModel.getUpdateTwin() != null) { return jobService.scheduleTwinUpdateAsync( jobApiModel.getJobId(), jobApiModel.getQueryCondition(), jobApiModel.getUpdateTwin(), jobApiModel.getStartTimeUtc() == null ? DateTime.now(DateTimeZone.UTC).toDate() : jobApiModel.getStartTimeUtc(), jobApiModel.getMaxExecutionTimeInSeconds() == null ? 3600 : jobApiModel.getMaxExecutionTimeInSeconds()) .thenApply(job -> ok(toJson(new JobApiModel(job)))); } if (jobApiModel.getMethodParameter() != null) { return jobService.scheduleDeviceMethodAsync( jobApiModel.getJobId(), jobApiModel.getQueryCondition(), jobApiModel.getMethodParameter().toServiceModel(), jobApiModel.getStartTimeUtc() == null ? DateTime.now(DateTimeZone.UTC).toDate() : jobApiModel.getStartTimeUtc(), jobApiModel.getMaxExecutionTimeInSeconds() == null ? 3600 : jobApiModel.getMaxExecutionTimeInSeconds()) .thenApply(job -> ok(toJson(new JobApiModel(job)))); } throw new NotSupportedException(); }
@Override public CompletionStage<Boolean> checkPermission(String permissionValue, Optional<String> meta, DeadboltHandler deadboltHandler, Http.Context ctx) { return CompletableFuture.completedFuture(false); }
private <U,V> CompletableFuture<V> biApplyStage( Executor e, CompletionStage<U> o, BiFunction<? super T,? super U,? extends V> f) { CompletableFuture<U> b; if (f == null || (b = o.toCompletableFuture()) == null) throw new NullPointerException(); CompletableFuture<V> d = new CompletableFuture<V>(); if (e != null || !d.biApply(this, b, f, null)) { BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f); bipush(b, c); c.tryFire(SYNC); } return d; }
private CompletionStage<Result> updateRemote(ExamRoom room) throws MalformedURLException { if (room.getExternalRef() != null && IOP_ACTIVATED) { return externalApi.updateFacility(room) .thenApplyAsync(x -> ok("updated")) .exceptionally(throwable -> internalServerError(throwable.getMessage())); } else { return wrapAsPromise(ok()); } }
private CompletionStage<Result> makeNewReservation(ExamEnrolment enrolment, Reservation reservation, User user) { Ebean.save(reservation); enrolment.setReservation(reservation); enrolment.setReservationCanceled(false); Ebean.save(enrolment); Exam exam = enrolment.getExam(); // Send some emails asynchronously system.scheduler().scheduleOnce(Duration.create(1, TimeUnit.SECONDS), () -> { emailComposer.composeReservationNotification(user, reservation, exam, false); Logger.info("Reservation confirmation email sent to {}", user.getEmail()); }, system.dispatcher()); return wrapAsPromise(ok("ok")); }
/** * PATCH /projects/{projectName}/members/{user}?role={role} * * <p>Changes the role of a user. */ @ConsumeType("application/json-patch+json") @Patch("/projects/{projectName}/tokens/{appId}") public CompletionStage<ProjectInfo> changeTokenRole(@Param("projectName") String projectName, @Param("appId") String appId, @Param("role") String role, @RequestObject Author author) { return mds.changeTokenRole(projectName, author, appId, ProjectRole.of(role)); }
private static <T, R> CompletablePromise<R> createLinkedPromise(CompletionStage<? extends T> stage) { return new CompletablePromise<R>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { if (super.cancel(mayInterruptIfRunning)) { cancelPromise(stage, mayInterruptIfRunning); return true; } else { return false; } } }; }
@Test public void returnValueAsyncFailedAfterRetry() throws Exception { Delay<String> delay = spy(ofSeconds(1)); Retryer.ForReturnValue<String> forReturnValue = retryer.ifReturns((String s) -> s.startsWith("bad"), asList(delay)); when(action.runAsync()) .thenReturn(completedFuture("bad")) .thenReturn(completedFuture("bad2")); CompletionStage<String> stage = forReturnValue.retryAsync(action::runAsync, executor); assertPending(stage); elapse(Duration.ofSeconds(1)); assertCompleted(stage).isEqualTo("bad2"); verify(action, times(2)).runAsync(); verify(delay).beforeDelay("bad"); verify(delay).afterDelay("bad"); }
private static <T> CompletableFuture<List<T>> mapValuesToFutureOfCompletedValues( @Nonnull final List<T> entities, @Nonnull final Function<T, CompletionStage<T>> entityMapper) { return mapValuesToFutureOfCompletedValues(entities.stream(), entityMapper); }
private static <T> CompletionStage<T> exceptionally(Throwable e) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; }