本文整理匯總了Java中java.util.concurrent.CompletionStage類的典型用法代碼示例。如果您正苦於以下問題:Java CompletionStage類的具體用法?Java CompletionStage怎麽用?Java CompletionStage使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
CompletionStage類屬於java.util.concurrent包,在下文中一共展示了CompletionStage類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: cacheAndFetch
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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)));
}
示例2: fetchOrCreateAndResolveReference
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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;
}
示例3: close
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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);
}
示例4: returnValueAndExceptionRetriedButStillReturnBad
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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);
}
示例5: call
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
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);
}
}
示例6: fetchOrCreateAndResolveReference
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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;
}
示例7: syncBatch
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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);
}
示例8: createProject
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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);
}
}
});
}
示例9: getFile
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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));
}
示例10: compose
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
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())));
}
示例11: refreshBackendInfo
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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);
}
示例12: cacheAndFetch
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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)));
}
示例13: resolveCategoryReferences
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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);
}
示例14: scheduleDeviceMethodAsync
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
@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);
}
}
示例15: configForSlug
import java.util.concurrent.CompletionStage; //導入依賴的package包/類
/**
* 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));
});
}