本文整理汇总了Java中java.util.concurrent.CompletableFuture.thenCompose方法的典型用法代码示例。如果您正苦于以下问题:Java CompletableFuture.thenCompose方法的具体用法?Java CompletableFuture.thenCompose怎么用?Java CompletableFuture.thenCompose使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.thenCompose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: rejectConnectionsAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Indicates that the node should stop accepting new connections.
*
* @param after If non-zero, after how many successful startup messages should stop accepting
* connections.
* @param scope The scope to reject connections, either stop listening for connections, or accept
* connections but don't respond to startup requests.
* @return future that completes when listening channel is unbound (if {@link RejectScope#UNBIND}
* was used) or immediately if {@link RejectScope#REJECT_STARTUP} was used or after > 0.
*/
@Override
public CompletionStage<Void> rejectConnectionsAsync(int after, RejectScope scope) {
RejectState state;
if (after <= 0) {
logger.debug("Rejecting new connections with scope {}", scope);
state = new RejectState(false, Integer.MIN_VALUE, scope);
} else {
logger.debug("Rejecting new connections after {} attempts with scope {}", after, scope);
state = new RejectState(true, after, scope);
}
rejectState.set(state);
if (after <= 0 && scope != RejectScope.REJECT_STARTUP) {
CompletableFuture<Void> unbindFuture = unbind();
// if scope is STOP, disconnect existing connections after unbinding.
if (scope == RejectScope.STOP) {
return unbindFuture.thenCompose(n -> disconnectConnections());
} else {
return unbindFuture;
}
} else {
return CompletableFuture.completedFuture(null);
}
}
示例2: testCompletedThenComposeCancelled
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* This test is one part of verifying https://github.com/tunnelvisionlabs/java-threading/issues/11.
*/
@Test
public void testCompletedThenComposeCancelled() {
CompletableFuture<Void> future = new CompletableFuture<>();
future.complete(null);
CompletableFuture<Void> composed = future.thenCompose(s -> Futures.completedCancelled());
Assert.assertTrue(composed.isDone());
Assert.assertTrue(composed.isCompletedExceptionally());
if (Async.REQUIRE_UNWRAP_FOR_COMPLETED_ANTECEDENT) {
Assert.assertFalse("The current runtime does not preserve cancellation when the antecedent is pre-completed", composed.isCancelled());
thrown.expect(CompletionException.class);
thrown.expectCause(isA(CancellationException.class));
composed.join();
} else {
Assert.assertTrue(composed.isCancelled());
thrown.expect(CancellationException.class);
composed.join();
}
}
示例3: exchange
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Start a key exchange process
*
* @param groupId
* the id of the group for which a key exchange will be initiated
* @param aHandler
* the handler which succeeds or fails in accordance to the key
* exchange outcome
* @return A Future representation of the key
*/
public CompletableFuture<BigInteger> exchange(int groupId, Handler<AsyncResult<BigInteger>> aHandler) {
conf.getLogger().info(getNode().toString() + Constants.NEGO_CALL + groupId);
Group g = groupMappings.get(groupId);
ExchangeState state = stateMappings.get(groupId);
state.registerHandler(aHandler);
CompletableFuture<Void> res = broadcast(g);
CompletableFuture<BigInteger> future = res.thenCompose(s -> compute(g));
long timer[] = new long[1];
timer[0] = vertx.setTimer(conf.getExchangeTimeout(), id -> {
if (future.isDone() && !future.isCompletedExceptionally()) {
aHandler.handle(Future.succeededFuture());
vertx.cancelTimer(timer[0]);
} else {
aHandler.handle(Future.failedFuture(Constants.EXCEPTIONTIMEOUTEXCEEDED + Constants.NEGO_TIMEOUT));
future.completeExceptionally(
new TimeoutException(Constants.EXCEPTIONTIMEOUTEXCEEDED + conf.getExchangeTimeout()));
vertx.cancelTimer(timer[0]);
}
});
future.exceptionally(e -> {
aHandler.handle(Future.failedFuture(e.getMessage()));
vertx.cancelTimer(timer[0]);
return future.join();
});
return future;
}
示例4: sendNext
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private CompletableFuture<List<SmtpResponse>> sendNext(CompletableFuture<List<SmtpResponse>> prevFuture, Iterator<Object> iterator) {
if (!iterator.hasNext()) {
return prevFuture;
}
return prevFuture.thenCompose(responses -> {
if (SmtpResponses.isError(responses.get(responses.size() - 1))) {
return CompletableFuture.completedFuture(responses);
}
Object nextObject = iterator.next();
CompletableFuture<List<SmtpResponse>> f = writeObjectsAndCollectResponses(1, nextObject)
.thenApply(mergeResponses(responses));
return sendNext(f, iterator);
});
}
示例5: flatMapConstN
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String flatMapConstN() throws InterruptedException, ExecutionException {
CompletableFuture<String> f = constFuture;
for (int i = 0; i < N.n; i++)
f = f.thenCompose(flatMapF);
return f.get();
}
示例6: push0
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private static CompletableFuture<?> push0(AbstractService service,
String projectName, String repositoryName,
Revision normalizedRev, Author author,
String commitSummary, String commitDetail, Markup commitMarkup,
Change<?> change) {
final CompletableFuture<Map<String, Change<?>>> f = normalizeChanges(
service.projectManager(), projectName, repositoryName, normalizedRev, ImmutableList.of(change));
return f.thenCompose(
changes -> service.execute(
Command.push(author, projectName, repositoryName, normalizedRev,
commitSummary, commitDetail, commitMarkup, changes.values())));
}
示例7: flatMapPromise
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String flatMapPromise() throws InterruptedException, ExecutionException {
CompletableFuture<String> p = new CompletableFuture<String>();
p.thenCompose(flatMapF);
p.complete(string);
return p.get();
}
示例8: login
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public CompletableFuture<TaggedResponse> login(String userName, String authToken, AuthMechanism authMechanism) {
CompletableFuture<? extends ImapResponse> loginFuture;
switch (authMechanism) {
case XOAUTH2:
loginFuture = oauthLogin(userName, authToken);
break;
case PLAIN:
loginFuture = authPlain(userName, authToken);
break;
default:
loginFuture = passwordLogin(userName, authToken);
break;
}
return loginFuture.thenCompose(response -> {
if (response instanceof ContinuationResponse) {
ContinuationResponse continuationResponse = ((ContinuationResponse) response);
return this.<TaggedResponse>send(ImapCommandType.BLANK).thenApply(blankResponse -> {
throw AuthenticationFailedException.fromContinuation(blankResponse.getMessage(), continuationResponse.getMessage());
});
}
TaggedResponse taggedResponse = ((TaggedResponse) response);
if (taggedResponse.getCode() == ResponseCode.OK) {
startKeepAlive();
return CompletableFuture.completedFuture(taggedResponse);
}
CompletableFuture<TaggedResponse> future = new CompletableFuture<>();
future.completeExceptionally(new AuthenticationFailedException(response.getMessage()));
return future;
});
}
示例9: testThenComposeAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public void testThenComposeAsync() throws Exception {
// Composing CompletableFuture is complete
CompletableFuture<String> cf1 = CompletableFuture.completedFuture("one");
// Composing function returns a CompletableFuture executed asynchronously
CountDownLatch cdl = new CountDownLatch(1);
CompletableFuture<String> cf2 = cf1.thenCompose(str -> CompletableFuture.supplyAsync(() -> {
while (true) {
try {
cdl.await();
break;
}
catch (InterruptedException e) {
}
}
return str + ", two";
}));
// Ensure returned CompletableFuture completes after call to thenCompose
// This guarantees that any premature internal completion will be
// detected
cdl.countDown();
String val = cf2.get();
Assert.assertNotNull(val);
Assert.assertEquals(val, "one, two");
}
示例10: commit
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Commits a transaction.
*
* @param transactionId transaction identifier
* @param transactionParticipants set of transaction participants
* @return future for commit result
*/
CompletableFuture<CommitStatus> commit(TransactionId transactionId,
Set<TransactionParticipant> transactionParticipants) {
int totalUpdates = transactionParticipants.stream()
.map(TransactionParticipant::totalUpdates)
.reduce(Math::addExact)
.orElse(0);
if (totalUpdates == 0) {
return CompletableFuture.completedFuture(CommitStatus.SUCCESS);
} else if (totalUpdates == 1) {
return transactionParticipants.stream()
.filter(p -> p.totalUpdates() == 1)
.findFirst()
.get()
.prepareAndCommit()
.thenApply(v -> v ? CommitStatus.SUCCESS : CommitStatus.FAILURE);
} else {
CompletableFuture<CommitStatus> status = transactions.put(transactionId, Transaction.State.PREPARING)
.thenCompose(v -> this.doPrepare(transactionParticipants))
.thenCompose(result -> result
? transactions.put(transactionId, Transaction.State.COMMITTING)
.thenCompose(v -> doCommit(transactionParticipants))
.thenApply(v -> CommitStatus.SUCCESS)
: transactions.put(transactionId, Transaction.State.ROLLINGBACK)
.thenCompose(v -> doRollback(transactionParticipants))
.thenApply(v -> CommitStatus.FAILURE));
return status.thenCompose(v -> transactions.remove(transactionId).thenApply(u -> v));
}
}
示例11: flatMapPromiseN
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String flatMapPromiseN() throws InterruptedException, ExecutionException {
CompletableFuture<String> p = new CompletableFuture<>();
CompletableFuture<String> f = p;
for (int i = 0; i < N.n; i++)
f = f.thenCompose(flatMapF);
p.complete(string);
return f.get();
}
示例12: indirectClientIsFirstClientAvailable
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Test
public void indirectClientIsFirstClientAvailable(final TestContext testContext) {
final Async async = testContext.async();
final CompletableFuture<HttpAction> future = authenticator.authenticate(webContext, Arrays.asList(getIndirectClient()));
final CompletableFuture<String> requestedUrlFuture = future.thenCompose(a -> {
assertThat(a, is(notNullValue()));
assertThat(a.getCode(), is(HttpConstants.TEMP_REDIRECT));
assertThat(responseHeaders.get(HttpConstants.LOCATION_HEADER), is(AUTH_REDIRECT_URL));
return webContext.getSessionStore().get(webContext, Pac4jConstants.REQUESTED_URL);
});
assertSuccessfulEvaluation(requestedUrlFuture, s -> {
assertThat(s, is(MockAsyncWebContextBuilder.DEFAULT_FULL_REQUEST_URL));
}, async);
}
示例13: create
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<U> create(final C credentials, final AsyncWebContext context) {
try {
final CompletableFuture<T> tokenFuture = new CompletableFuture<>();
try {
tokenFuture.complete(getAccessToken(credentials));
} catch (HttpAction action) {
tokenFuture.completeExceptionally(action);
}
return tokenFuture.thenCompose(this::retrieveUserProfileFromToken);
} catch (final OAuthException e) {
throw new TechnicalException(e);
}
}
示例14: save
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Save the given user profile (replace the current one if multi profiles are not supported, add it otherwise).
*
* @param saveInSession if the user profile must be saved in session
* @param profile a given user profile
* @param multiProfile whether multiple profiles are supported
*/
public CompletableFuture<Void> save(final boolean saveInSession, final U profile, final boolean multiProfile) {
final String clientName = retrieveClientName(profile);
final CompletableFuture<Map<String, U>> profilesFuture;
if (multiProfile) {
profilesFuture = retrieveAll(saveInSession).thenApply(profiles -> {
profiles.remove(clientName);
return profiles;
});
} else {
profilesFuture = completedFuture(new LinkedHashMap<String, U>());
}
final CompletableFuture<Map<String, U>> updatedProfilesFuture = profilesFuture.thenApply(profiles -> {
profiles.put(clientName, profile);
return profiles;
});
return updatedProfilesFuture.thenCompose(profiles -> {
CompletableFuture<Void> saveFuture = (saveInSession ?
this.context.getSessionStore().set(context, USER_PROFILES, profiles) :
completedFuture(null))
.thenAccept(v -> this.context.setRequestAttribute(USER_PROFILES, profiles));
return saveFuture;
});
}
示例15: retrieveAll
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Retrieve the map of profiles from the session or the request.
*
* @param readFromSession if the user profiles must be read from session
* @return the map of profiles
*/
protected CompletableFuture<Map<String, U>> retrieveAll(final boolean readFromSession) {
final Map<String, U> profiles = new LinkedHashMap<>();
final Object request = this.context.getRequestAttribute(USER_PROFILES);
if (request != null) {
if (request instanceof Map) {
profiles.putAll((Map<String, U>) request);
}
if (request instanceof CommonProfile) {
profiles.put(retrieveClientName((U) request), (U) request);
}
}
if (readFromSession) {
final CompletableFuture<Object> sessionAttributeFuture = this.context.getSessionStore().get(context, USER_PROFILES);
return sessionAttributeFuture.thenCompose(sessionAttribute -> {
final CompletableFuture<Map<String, U>> future = new CompletableFuture<>();
this.context.getExecutionContext().runOnContext(() -> {
if (sessionAttribute instanceof Map) {
profiles.putAll((Map<String, U>) sessionAttribute);
}
if (sessionAttribute instanceof CommonProfile) {
profiles.put(retrieveClientName((U) sessionAttribute), (U) sessionAttribute);
}
future.complete(profiles);
});
return future;
});
} else {
return completedFuture(profiles);
}
}