本文整理匯總了Java中java.util.concurrent.CompletableFuture.thenAccept方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletableFuture.thenAccept方法的具體用法?Java CompletableFuture.thenAccept怎麽用?Java CompletableFuture.thenAccept使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.thenAccept方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: main
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
public static void main(String [] args) throws Exception{
HttpClient client = HttpClient
.newBuilder()
.build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://httpbin.org/get"))
.GET()
.version(HttpClient.Version.HTTP_1_1)
.build();
CompletableFuture<HttpResponse<String>> responseFuture =
client.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture<Void> processedFuture =
responseFuture.thenAccept(response -> {
System.out.println("Status code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
});
//wait for the CompleteableFuture to complete
CompletableFuture.allOf(processedFuture).join();
}
示例2: runAsyncAuthGeneratorTest
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
public void runAsyncAuthGeneratorTest(final TestContext context,
final Function<AtomicInteger, AsyncAuthorizationGenerator<TestProfile>> authGenFactory) throws Exception {
final Async async = context.async();
final AtomicInteger monitor = new AtomicInteger(0);
// Need to mock the AsyncWebContext for this to work
final AsyncWebContext webContext = MockAsyncWebContextBuilder.from(rule.vertx(), asynchronousComputationAdapter)
.build();
final CompletableFuture<Consumer<TestProfile>> completableFuture = authGenFactory.apply(monitor)
.generate(webContext, TestProfile.from(new TestCredentials("name", "password")));
completableFuture.thenAccept(i -> executionContext.runOnContext(() -> {
assertThat(monitor.get(), is(1));
async.complete();
}));
}
示例3: testGetProfileSuccessfullyWithAuthenticators
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 1000)
public void testGetProfileSuccessfullyWithAuthenticators(final TestContext testContext) {
final Async async = testContext.async();
final AsyncBaseClient<TestCredentials, TestProfile> client = happyPathClient();
client.addAuthorizationGenerator(successfulPermissionAuthGenerator(PERMISSION_ADMIN));
client.addAuthorizationGenerator(successfulPermissionAuthGenerator(PERMISSION_SYSTEM));
final TestCredentials credentials = new TestCredentials(HAPPY_PATH_NAME, HAPPY_PATH_PASSWORD);
// We don't care about web contexts right now
final CompletableFuture<Optional<TestProfile>> profileFuture = client.getUserProfileFuture(credentials, webContext);
profileFuture.thenAccept(o -> o.ifPresent(p -> {
LOG.debug("Profile future completed " + System.currentTimeMillis());
rule.vertx().runOnContext(v -> {
assertThat(p.getId(), is(HAPPY_PATH_NAME));
assertThat(p.getPermissions().size(), is(2));
assertThat(p.getPermissions(), is(new HashSet(Arrays.asList(PERMISSION_ADMIN, PERMISSION_SYSTEM))));
async.complete();
});
}));
}
示例4: should_Represent_failures_and_successes_simultaneously
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void should_Represent_failures_and_successes_simultaneously() throws ExecutionException, InterruptedException {
AtomicBoolean success = new AtomicBoolean();
List<Collection<Integer>> loadCalls = new ArrayList<>();
DataLoader<Integer, Object> evenLoader = idLoaderOddEvenExceptions(new DataLoaderOptions(), loadCalls);
CompletableFuture<Object> future1 = evenLoader.load(1);
CompletableFuture<Object> future2 = evenLoader.load(2);
CompletableFuture<Object> future3 = evenLoader.load(3);
CompletableFuture<Object> future4 = evenLoader.load(4);
CompletableFuture<List<Object>> result = evenLoader.dispatch();
result.thenAccept(promisedValues -> success.set(true));
await().untilAtomic(success, is(true));
assertThat(future1.isCompletedExceptionally(), is(true));
assertThat(cause(future1), instanceOf(IllegalStateException.class));
assertThat(future2.get(), equalTo(2));
assertThat(future3.isCompletedExceptionally(), is(true));
assertThat(future4.get(), equalTo(4));
assertThat(loadCalls, equalTo(singletonList(asList(1, 2, 3, 4))));
}
示例5: refreshAnnotationsView
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Refreshes the view for Annotations that already exist but are modified.
* @param observationUuid
*/
public void refreshAnnotationsView(Set<UUID> observationUuid) {
CopyOnWriteArrayList<Annotation> annotations = new CopyOnWriteArrayList<>();
final AnnotationService annotationService = toolBox.getServices().getAnnotationService();
CompletableFuture[] futures = observationUuid.stream()
.map(uuid -> annotationService.findByUuid(uuid)
.thenAccept(annotations::add))
.toArray(i -> new CompletableFuture[i]);
CompletableFuture<Void> all = CompletableFuture.allOf(futures);
final EventBus eventBus = toolBox.getEventBus();
all.thenAccept(v -> {
eventBus.send(new AnnotationsChangedEvent(annotations));
});
}
示例6: testGetProfileWithNoAuthenticators
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 1000)
public void testGetProfileWithNoAuthenticators(final TestContext testContext) {
final Async async = testContext.async();
final AsyncClient<TestCredentials, TestProfile> client = happyPathClient();
final TestCredentials credentials = new TestCredentials(HAPPY_PATH_NAME, HAPPY_PATH_PASSWORD);
// We don't care about web contexts right now
final CompletableFuture<Optional<TestProfile>> profileFuture = client.getUserProfileFuture(credentials, webContext);
profileFuture.thenAccept(o -> o.ifPresent(p -> {
rule.vertx().runOnContext(v -> {
assertThat(p.getId(), is(HAPPY_PATH_NAME));
async.complete();
});
}));
}
示例7: testFromNonBlockingSupplierOnContext
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 1000)
public void testFromNonBlockingSupplierOnContext(final TestContext testContext) {
final Context context = rule.vertx().getOrCreateContext();
Async async = testContext.async();
final List<Integer> ints = Arrays.asList(1);
final CompletableFuture<Integer> future = new VertxAsynchronousComputationAdapter(rule.vertx(), context)
.fromNonBlockingOnContext(() -> {
ints.set(0, 2);
return 1;
});
future.thenAccept(i -> {
assertThat(i, is(1));
assertThat(ints, is(Arrays.asList(2)));
async.complete();
});
}
示例8: testOtherExceptionThrownDuringResultTransformation
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 1000)
public void testOtherExceptionThrownDuringResultTransformation(final TestContext testContext) {
final Async async = testContext.async();
final AsyncWebContext asyncWebContext = MockAsyncWebContextBuilder.from(rule.vertx(), asynchronousComputationAdapter).build();
final HttpAction forbiddenAction = HttpAction.forbidden("Forbidden", asyncWebContext);
final CompletableFuture<HttpAction> okFuture = this.<Integer>delayedResult(100, () -> 2)
.<HttpAction>thenApply(v -> {
throw forbiddenAction;
})
.handle(softenBiFunction(AsyncExceptionHandler::extractAsyncHttpAction));
okFuture.thenAccept(a -> {
assertThat(a.getCode(), is(403));
async.complete();
});
}
示例9: addFree
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void addFree(StorageToken token, int i, int j) throws Exception {
System.out.println("Sending tx " + i + "-" + j);
RemoteCall<TransactionReceipt> add = token.add_free(new Uint64(i), new Uint64(j));
CompletableFuture<TransactionReceipt> future = add.sendAsync();
futures.add(future);
future.thenAccept(r -> System.out.printf("Gas used %d-%d: %s\n", i, j, r.getGasUsed()));
}
示例10: sendData
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void sendData() throws ExecutionException, InterruptedException {
if (concurrentCalls >= concurrentCallsLimit) {
System.out.println("MAX LIMIT REACHED!");
} else if (incomingRequests.size() > 0) {
requestDone = true;
concurrentCalls++;
System.out.println("+ CONCURRENT CALLS: " + concurrentCalls);
// Get this batch from the incoming requests
Set<ActorRef> batched = incomingRequests.keySet().stream().limit(batchSize).collect(Collectors.toSet());
// Get the ids from the incoming requests
String ids = generateIdsString(batched);
// Remove the batch actors from the incoming request maps
for (ActorRef actorRef : batched) {
incomingRequests.remove(actorRef);
}
CompletableFuture<String> serviceResponse = callService(ids);
serviceResponse.thenAccept(s -> {
batched.stream().forEach(actorRef -> {
actorRef.tell(s, getSelf());
inFlightRequests.remove(actorRef);
});
concurrentCalls--;
System.out.println("- CONCURRENT CALLS: " + concurrentCalls);
});
}
}
示例11: test1
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Basic test of exitValue and onExit.
*/
@Test
public static void test1() {
try {
int[] exitValues = {0, 1, 10};
for (int value : exitValues) {
Process p = JavaChild.spawn("exit", Integer.toString(value));
CompletableFuture<Process> future = p.onExit();
future.thenAccept( (ph) -> {
int actualExitValue = ph.exitValue();
printf(" javaChild done: %s, exitStatus: %d%n",
ph, actualExitValue);
Assert.assertEquals(actualExitValue, value, "actualExitValue incorrect");
Assert.assertEquals(ph, p, "Different Process passed to thenAccept");
});
Process h = future.get();
Assert.assertEquals(h, p);
Assert.assertEquals(p.exitValue(), value);
Assert.assertFalse(p.isAlive(), "Process should not be alive");
p.waitFor();
}
} catch (IOException | InterruptedException | ExecutionException ex) {
Assert.fail(ex.getMessage(), ex);
} finally {
destroyProcessTree(ProcessHandle.current());
}
}
示例12: exceptionalResult
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(expected = IntentionalException.class) // Exception should be thrown out to context
public void exceptionalResult(final TestContext testContext) {
final IntentionalException e = new IntentionalException();
final Async async = testContext.async();
final CompletableFuture<Integer> future = exceptionHandler.applyExceptionHandling(delayedException(125, e),
webContext);
future.thenAccept(i -> {
assertThat(i, is(nullValue()));
assertThat(thrown.get(), is(e));
async.complete();
});
}
示例13: fireClickEvent
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void fireClickEvent(ClickInventoryEvent e)
{
Optional<Player> optional = Sponge.getServer().getPlayer(playerUniqueId);
if (!optional.isPresent())
{
return;
}
Player player = optional.get();
CompletableFuture<Boolean> future = CompletableFuture.completedFuture(Boolean.TRUE);
for (SlotTransaction slotTransaction : e.getTransactions())
{
Slot slot = slotTransaction.getSlot();
SlotIndex pos = SpongeUnimplemented.getSlotOrdinal(slot);
if (SpongeUnimplemented.isSlotInInventory(slot, e.getTargetInventory()) && slotToListen.matches(pos))
{
e.setCancelled(true);
boolean allowAction = actionIntervalManager.allowAction(player, acceptableActionIntervalTick);
if (allowAction && itemsInSlots.containsKey(pos))
{
future = future.thenApplyAsync(p -> processClickEvent(e, player, pos) && p, executorService);
}
}
}
future.thenAccept(shouldKeepInventoryOpen ->
{
if (!shouldKeepInventoryOpen)
{
SpongeUnimplemented.closeInventory(player, plugin);
}
});
}
示例14: handle
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public void handle(RoutingContext rc) {
final CompletableFuture<List<CommonProfile>> profileFuture = getUserProfiles(rc, asynchronousComputationAdapter);
profileFuture.thenAccept(profile -> {
rc.put("userProfiles", profile);
engine.render(rc, "", "templates/protectedIndex.hbs", res -> {
if (res.succeeded()) {
generatedContentConsumer.accept(rc, res.result());
} else {
rc.fail(res.cause());
}
});
});
}
示例15: isAuthorized
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<Boolean> isAuthorized(final AsyncWebContext context, final List<CommonProfile> profiles) {
CommonHelper.assertNotNull("csrfTokenGenerator", csrfTokenGenerator);
final CompletableFuture<String> tokenFuture = csrfTokenGenerator.get(context);
final CompletableFuture<Boolean> result = new CompletableFuture<>();
tokenFuture.thenAccept(token -> context.getExecutionContext().runOnContext(() -> {
context.setRequestAttribute(Pac4jConstants.CSRF_TOKEN, token);
final Cookie cookie = new Cookie(Pac4jConstants.CSRF_TOKEN, token);
if (domain != null) {
cookie.setDomain(domain);
} else {
cookie.setDomain(context.getServerName());
}
if (path != null) {
cookie.setPath(path);
}
if (httpOnly != null) {
cookie.setHttpOnly(httpOnly.booleanValue());
}
if (secure != null) {
cookie.setSecure(secure.booleanValue());
}
context.addResponseCookie(cookie);
result.complete(true);
}));
return result;
}