Java Code Examples for java.util.concurrent.CompletionStage#thenAccept()
The following examples show how to use
java.util.concurrent.CompletionStage#thenAccept() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompletableFutureTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Joining a minimal stage "by hand" works */ public void testMinimalCompletionStage_join_by_hand() { for (boolean createIncomplete : new boolean[] { true, false }) for (Integer v1 : new Integer[] { 1, null }) { CompletableFuture<Integer> f = new CompletableFuture<>(); CompletionStage<Integer> minimal = f.minimalCompletionStage(); CompletableFuture<Integer> g = new CompletableFuture<>(); if (!createIncomplete) assertTrue(f.complete(v1)); minimal.thenAccept(x -> g.complete(x)); if (createIncomplete) assertTrue(f.complete(v1)); g.join(); checkCompletedNormally(g, v1); checkCompletedNormally(f, v1); assertEquals(v1, join(minimal)); }}
Example 2
Source File: DefaultReactiveMergeEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
private CompletionStage<Void> fetchAndCopyValues( final EntityPersister persister, final Object entity, final Object target, final SessionImplementor source, final MergeContext mergeContext) { CompletionStage<Void> stage = CompletionStages.nullFuture(); // If entity == target, then nothing needs to be fetched. if ( entity != target ) { ReactiveSession session = source.unwrap(ReactiveSession.class); final Object[] mergeState = persister.getPropertyValues(entity); final Object[] managedState = persister.getPropertyValues(target); for (int i = 0; i < mergeState.length; i++) { Object fetchable = managedState[i]; // Cascade-merge mappings do not determine what needs to be fetched. // The value only needs to be fetched if the incoming value (mergeState[i]) // is initialized, but its corresponding managed state is not initialized. // Initialization must be done before copyValues executes. if ( Hibernate.isInitialized( mergeState[i] ) && !Hibernate.isInitialized( managedState[i] ) ) { stage = stage.thenCompose( v -> session.reactiveFetch( fetchable, true ) ).thenApply(ignore -> null); } } } return stage.thenAccept( v -> copyValues( persister, entity, target, source, mergeContext ) ); }
Example 3
Source File: SdkHarnessClient.java From beam with Apache License 2.0 | 6 votes |
@Override public void requestProgress() { InstructionRequest request = InstructionRequest.newBuilder() .setInstructionId(idGenerator.getId()) .setProcessBundleProgress( ProcessBundleProgressRequest.newBuilder().setInstructionId(bundleId).build()) .build(); CompletionStage<InstructionResponse> response = fnApiControlClient.handle(request); response.thenAccept( instructionResponse -> { // Don't forward empty responses. if (ProcessBundleProgressResponse.getDefaultInstance() .equals(instructionResponse.getProcessBundleProgress())) { return; } progressHandler.onProgress(instructionResponse.getProcessBundleProgress()); }); }
Example 4
Source File: NioBridge.java From java-async-util with Apache License 2.0 | 6 votes |
public static void main(final String[] args) throws IOException { final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(null); final CompletionStage<AsynchronousSocketChannel> acceptStage = accept(server); final SocketAddress addr = server.getLocalAddress(); final CompletionStage<AsynchronousSocketChannel> connectStage = connect(addr); // after connecting, write the integer 42 to the server final CompletionStage<Void> writeStage = connectStage.thenAccept(channel -> writeInt(channel, 42)); final CompletionStage<Void> readStage = acceptStage // after accepting, read an int from the socket .thenCompose(NioBridge::readInt) // print the result .thenAccept(System.out::println); // wait for the write and the read to complete writeStage.toCompletableFuture().join(); readStage.toCompletableFuture().join(); }
Example 5
Source File: PgRowPublisherOperation.java From pgadba with BSD 2-Clause "Simplified" License | 6 votes |
@Override public ParameterizedRowPublisherOperation<R> subscribe(Flow.Subscriber<? super Result.RowColumn> subscriber, CompletionStage<? extends R> result) { if (result == null) { throw new IllegalArgumentException("result is not allowed to be null"); } if (subscriber == null) { throw new IllegalArgumentException("subscriber is not allowed to be null"); } publisher.subscribe(subscriber); this.result = result; result.thenAccept(r -> { if (groupSubmission != null) { groupSubmission.addGroupResult(r); } submission.getCompletionStage().toCompletableFuture().complete(r); }); return this; }
Example 6
Source File: AsyncExamples.java From curator with Apache License 2.0 | 6 votes |
private static void handleWatchedStage(CompletionStage<WatchedEvent> watchedStage) { // async handling of Watchers is complicated because watchers can trigger multiple times // and CompletionStage don't support this behavior // thenAccept() handles normal watcher triggering. watchedStage.thenAccept(event -> { System.out.println(event.getType()); System.out.println(event); // etc. }); // exceptionally is called if there is a connection problem in which case // watchers trigger to signal the connection problem. "reset()" must be called // to reset the watched stage watchedStage.exceptionally(exception -> { AsyncEventException asyncEx = (AsyncEventException)exception; asyncEx.printStackTrace(); // handle the error as needed handleWatchedStage(asyncEx.reset()); return null; }); }
Example 7
Source File: HomeControllerTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLongResponseWhenTimeoutThenHandle() throws Exception { CountDownLatch latch = new CountDownLatch(1); WSClient ws = play.test.WSTestClient.newClient(port); Futures futures = app.injector() .instanceOf(Futures.class); CompletionStage<Result> f = futures.timeout( ws.url(url) .setRequestTimeout(Duration.of(1, SECONDS)) .get() .thenApply(result -> { try { Thread.sleep(2000L); return Results.ok(); } catch (InterruptedException e) { return Results.status( SERVICE_UNAVAILABLE); } }), 1L, TimeUnit.SECONDS ); CompletionStage<Object> res = f.handleAsync((result, e) -> { if (e != null) { log.error("Exception thrown", e); latch.countDown(); return e.getCause(); } else { return result; } }); res.thenAccept(result -> assertEquals(TimeoutException.class, result)); log.debug( "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); latch.await(5, TimeUnit.SECONDS ); assertEquals(0, latch.getCount()); log.debug("All requests have been completed. Exiting test."); }
Example 8
Source File: CompletionStageReturnValueHandler.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final DeferredResult<Object> deferredResult = new DeferredResult<Object>(); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer); @SuppressWarnings("unchecked") CompletionStage<Object> future = (CompletionStage<Object>) returnValue; future.thenAccept(new Consumer<Object>() { @Override public void accept(Object result) { deferredResult.setResult(result); } }); future.exceptionally(new Function<Throwable, Object>() { @Override public Object apply(Throwable ex) { deferredResult.setErrorResult(ex); return null; } }); }
Example 9
Source File: DataLoaderTest.java From java-dataloader with Apache License 2.0 | 5 votes |
@Test public void should_Support_loading_multiple_keys_in_one_call() { AtomicBoolean success = new AtomicBoolean(); DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keysAsValues()); CompletionStage<List<Integer>> futureAll = identityLoader.loadMany(asList(1, 2)); futureAll.thenAccept(promisedValues -> { assertThat(promisedValues.size(), is(2)); success.set(true); }); identityLoader.dispatch(); await().untilAtomic(success, is(true)); assertThat(futureAll.toCompletableFuture().join(), equalTo(asList(1, 2))); }
Example 10
Source File: DataLoaderTest.java From java-dataloader with Apache License 2.0 | 5 votes |
@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)); }
Example 11
Source File: TryTest.java From java-dataloader with Apache License 2.0 | 5 votes |
@Test public void triedStage() throws Exception { CompletionStage<Try<String>> sTry = Try.tryStage(CompletableFuture.completedFuture("Hello World")); sTry.thenAccept(stageTry -> assertSuccess(stageTry, "Hello World")); sTry.toCompletableFuture().join(); CompletableFuture<String> failure = new CompletableFuture<>(); failure.completeExceptionally(new RuntimeException("Goodbye Cruel World")); sTry = Try.tryStage(failure); sTry.thenAccept(stageTry -> assertFailure(stageTry, "Goodbye Cruel World")); sTry.toCompletableFuture().join(); }
Example 12
Source File: VertxProducerTest.java From quarkus with Apache License 2.0 | 5 votes |
public void verify() throws Exception { CountDownLatch latch = new CountDownLatch(1); CompletionStage<io.vertx.mutiny.core.buffer.Buffer> stage = vertx.fileSystem().readFile("files/lorem.txt") .subscribeAsCompletionStage(); stage.thenAccept(buffer -> latch.countDown()); latch.await(5, TimeUnit.SECONDS); }
Example 13
Source File: CompletionStageReturnValueHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final DeferredResult<Object> deferredResult = new DeferredResult<Object>(); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer); @SuppressWarnings("unchecked") CompletionStage<Object> future = (CompletionStage<Object>) returnValue; future.thenAccept(new Consumer<Object>() { @Override public void accept(Object result) { deferredResult.setResult(result); } }); future.exceptionally(new Function<Throwable, Object>() { @Override public Object apply(Throwable ex) { deferredResult.setErrorResult(ex); return null; } }); }
Example 14
Source File: TrialResource.java From Java-EE-8-and-Angular with MIT License | 5 votes |
private void rx() { System.out.println("rx called"); Client client = ClientBuilder.newClient(); WebTarget base = client.target("http://localhost:8080/ims-micro-users/resources/trials/slow"); CompletionStage<User> csf = base.request("application/json") .rx() .get(User.class); System.out.println("rx get done"); csf.thenAccept(System.out::println); System.out.println("accept ended"); }
Example 15
Source File: PublisherToCompletionStageTest.java From servicetalk with Apache License 2.0 | 5 votes |
private void verifyComplete(boolean completeBeforeListen, boolean sendData) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); AtomicReference<Collection<String>> resultRef = new AtomicReference<>(); CompletionStage<? extends Collection<String>> stage = publisher.toCompletionStage(); if (completeBeforeListen) { if (sendData) { publisher.onNext("Hello", "World"); } publisher.onComplete(); stage.thenAccept(result -> { resultRef.compareAndSet(null, result); latch.countDown(); }); } else { stage.thenAccept(result -> { resultRef.compareAndSet(null, result); latch.countDown(); }); if (sendData) { publisher.onNext("Hello", "World"); } publisher.onComplete(); } latch.await(); if (sendData) { assertThat(resultRef.get(), contains("Hello", "World")); } else { assertThat(resultRef.get(), is(empty())); } }
Example 16
Source File: AbstractReactiveFlushingEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
/** * Coordinates the processing necessary to get things ready for executions * as db calls by preping the session caches and moving the appropriate * entities and collections to their respective execution queues. * * @param event The flush event. * @throws HibernateException Error flushing caches to execution queues. */ protected CompletionStage<Void> flushEverythingToExecutions(FlushEvent event) throws HibernateException { LOG.trace( "Flushing session" ); EventSource session = event.getSession(); final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); session.getInterceptor().preFlush( persistenceContext.managedEntitiesIterator() ); CompletionStage<Void> cascades = prepareEntityFlushes(session, persistenceContext); // we could move this inside if we wanted to // tolerate collection initializations during // collection dirty checking: prepareCollectionFlushes( persistenceContext ); // now, any collections that are initialized // inside this block do not get updated - they // are ignored until the next flush return cascades.thenAccept( v -> { persistenceContext.setFlushing(true); try { int entityCount = flushEntities(event, persistenceContext); int collectionCount = flushCollections(session, persistenceContext); event.setNumberOfEntitiesProcessed(entityCount); event.setNumberOfCollectionsProcessed(collectionCount); } finally { persistenceContext.setFlushing(false); } }); //some statistics // logFlushResults( event ); }
Example 17
Source File: SdkHarnessClient.java From beam with Apache License 2.0 | 5 votes |
@Override public void split(double fractionOfRemainder) { Map<String, DesiredSplit> splits = new HashMap<>(); for (Map.Entry<LogicalEndpoint, CloseableFnDataReceiver> ptransformToInput : inputReceivers.entrySet()) { if (!ptransformToInput.getKey().isTimer()) { splits.put( ptransformToInput.getKey().getTransformId(), DesiredSplit.newBuilder() .setFractionOfRemainder(fractionOfRemainder) .setEstimatedInputElements( ((CountingFnDataReceiver) ptransformToInput.getValue()).getCount()) .build()); } } InstructionRequest request = InstructionRequest.newBuilder() .setInstructionId(idGenerator.getId()) .setProcessBundleSplit( ProcessBundleSplitRequest.newBuilder() .setInstructionId(bundleId) .putAllDesiredSplits(splits) .build()) .build(); CompletionStage<InstructionResponse> response = fnApiControlClient.handle(request); response.thenAccept( instructionResponse -> { // Don't forward empty responses representing the failure to split. if (ProcessBundleSplitResponse.getDefaultInstance() .equals(instructionResponse.getProcessBundleSplit())) { return; } splitHandler.split(instructionResponse.getProcessBundleSplit()); }); }
Example 18
Source File: PoliciesRootActor.java From ditto with Eclipse Public License 2.0 | 4 votes |
@SuppressWarnings("unused") private PoliciesRootActor(final PoliciesConfig policiesConfig, final SnapshotAdapter<Policy> snapshotAdapter, final ActorRef pubSubMediator, final ActorMaterializer materializer) { final ActorSystem actorSystem = getContext().system(); final ClusterShardingSettings shardingSettings = ClusterShardingSettings.create(actorSystem).withRole(CLUSTER_ROLE); final Props policySupervisorProps = PolicySupervisorActor.props(pubSubMediator, snapshotAdapter); final TagsConfig tagsConfig = policiesConfig.getTagsConfig(); final ActorRef persistenceStreamingActor = startChildActor(PoliciesPersistenceStreamingActorCreator.ACTOR_NAME, PoliciesPersistenceStreamingActorCreator.props(tagsConfig.getStreamingCacheSize())); pubSubMediator.tell(DistPubSubAccess.put(getSelf()), getSelf()); pubSubMediator.tell(DistPubSubAccess.put(persistenceStreamingActor), getSelf()); final ClusterConfig clusterConfig = policiesConfig.getClusterConfig(); final ActorRef policiesShardRegion = ClusterSharding.get(actorSystem) .start(PoliciesMessagingConstants.SHARD_REGION, policySupervisorProps, shardingSettings, ShardRegionExtractor.of(clusterConfig.getNumberOfShards(), actorSystem)); startChildActor(PolicyPersistenceOperationsActor.ACTOR_NAME, PolicyPersistenceOperationsActor.props(pubSubMediator, policiesConfig.getMongoDbConfig(), actorSystem.settings().config(), policiesConfig.getPersistenceOperationsConfig())); retrieveStatisticsDetailsResponseSupplier = RetrieveStatisticsDetailsResponseSupplier.of(policiesShardRegion, PoliciesMessagingConstants.SHARD_REGION, log); final HealthCheckConfig healthCheckConfig = policiesConfig.getHealthCheckConfig(); final HealthCheckingActorOptions.Builder hcBuilder = HealthCheckingActorOptions.getBuilder(healthCheckConfig.isEnabled(), healthCheckConfig.getInterval()); if (healthCheckConfig.getPersistenceConfig().isEnabled()) { hcBuilder.enablePersistenceCheck(); } final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build(); final MetricsReporterConfig metricsReporterConfig = healthCheckConfig.getPersistenceConfig().getMetricsReporterConfig(); final Props healthCheckingActorProps = DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions, MongoHealthChecker.props(), MongoMetricsReporter.props( metricsReporterConfig.getResolution(), metricsReporterConfig.getHistory(), pubSubMediator ) ); final ActorRef healthCheckingActor = startChildActor(DefaultHealthCheckingActorFactory.ACTOR_NAME, healthCheckingActorProps); final HttpConfig httpConfig = policiesConfig.getHttpConfig(); String hostname = httpConfig.getHostname(); if (hostname.isEmpty()) { hostname = LocalHostAddressSupplier.getInstance().get(); log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname); } final CompletionStage<ServerBinding> binding = Http.get(actorSystem) .bindAndHandle(createRoute(actorSystem, healthCheckingActor).flow(actorSystem, materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(actorSystem).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_health_http_endpoint", () -> { log.info("Gracefully shutting down status/health HTTP endpoint.."); return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ); binding.thenAccept(this::logServerBinding) .exceptionally(failure -> { log.error(failure, "Something very bad happened: {}", failure.getMessage()); actorSystem.terminate(); return null; }); }
Example 19
Source File: ThingsRootActor.java From ditto with Eclipse Public License 2.0 | 4 votes |
@SuppressWarnings("unused") private ThingsRootActor(final ThingsConfig thingsConfig, final ActorRef pubSubMediator, final ActorMaterializer materializer, final ThingPersistenceActorPropsFactory propsFactory) { final ActorSystem actorSystem = getContext().system(); final ClusterConfig clusterConfig = thingsConfig.getClusterConfig(); final ShardRegionExtractor shardRegionExtractor = ShardRegionExtractor.of(clusterConfig.getNumberOfShards(), actorSystem); final ThingEventPubSubFactory pubSubFactory = ThingEventPubSubFactory.of(getContext(), shardRegionExtractor); final DistributedPub<ThingEvent> distributedPub = pubSubFactory.startDistributedPub(); final ActorRef thingsShardRegion = ClusterSharding.get(actorSystem) .start(ThingsMessagingConstants.SHARD_REGION, getThingSupervisorActorProps(pubSubMediator, distributedPub, propsFactory), ClusterShardingSettings.create(actorSystem).withRole(CLUSTER_ROLE), shardRegionExtractor); startChildActor(ThingPersistenceOperationsActor.ACTOR_NAME, ThingPersistenceOperationsActor.props(pubSubMediator, thingsConfig.getMongoDbConfig(), actorSystem.settings().config(), thingsConfig.getPersistenceOperationsConfig())); retrieveStatisticsDetailsResponseSupplier = RetrieveStatisticsDetailsResponseSupplier.of(thingsShardRegion, ThingsMessagingConstants.SHARD_REGION, log); final HealthCheckConfig healthCheckConfig = thingsConfig.getHealthCheckConfig(); final HealthCheckingActorOptions.Builder hcBuilder = HealthCheckingActorOptions.getBuilder(healthCheckConfig.isEnabled(), healthCheckConfig.getInterval()); if (healthCheckConfig.getPersistenceConfig().isEnabled()) { hcBuilder.enablePersistenceCheck(); } final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build(); final MetricsReporterConfig metricsReporterConfig = healthCheckConfig.getPersistenceConfig().getMetricsReporterConfig(); final ActorRef healthCheckingActor = startChildActor(DefaultHealthCheckingActorFactory.ACTOR_NAME, DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions, MongoHealthChecker.props(), MongoMetricsReporter.props( metricsReporterConfig.getResolution(), metricsReporterConfig.getHistory(), pubSubMediator ) )); final TagsConfig tagsConfig = thingsConfig.getTagsConfig(); final ActorRef eventStreamingActor = ThingsPersistenceStreamingActorCreator.startEventStreamingActor(tagsConfig.getStreamingCacheSize(), this::startChildActor); final ActorRef snapshotStreamingActor = ThingsPersistenceStreamingActorCreator.startSnapshotStreamingActor(this::startChildActor); pubSubMediator.tell(DistPubSubAccess.put(getSelf()), getSelf()); pubSubMediator.tell(DistPubSubAccess.put(eventStreamingActor), getSelf()); pubSubMediator.tell(DistPubSubAccess.put(snapshotStreamingActor), getSelf()); final HttpConfig httpConfig = thingsConfig.getHttpConfig(); String hostname = httpConfig.getHostname(); if (hostname.isEmpty()) { hostname = LocalHostAddressSupplier.getInstance().get(); log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname); } final CompletionStage<ServerBinding> binding = Http.get(actorSystem) .bindAndHandle( createRoute(actorSystem, healthCheckingActor).flow(actorSystem, materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(getContext().getSystem()).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_health_http_endpoint", () -> { log.info("Gracefully shutting down status/health HTTP endpoint ..."); return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ); binding.thenAccept(this::logServerBinding) .exceptionally(failure -> { log.error(failure, "Something very bad happened: {}", failure.getMessage()); actorSystem.terminate(); return null; }); }
Example 20
Source File: AbstractCompletionStageTest.java From completion-stage with Apache License 2.0 | 3 votes |
@Test public void acceptShouldWork() { CompletionStage<String> completionStage = createCompletionStage(VALUE); completionStage.thenAccept(consumer); finish(completionStage); verify(consumer).accept(VALUE); }