@Override public CompletionStage<Boolean> test( final Http.Context context, final DeadboltHandler handler, final Executor executor) { return constraintLogic.restrict( context, handler, content, () -> roleGroups, ctx -> CompletableFuture.completedFuture(Boolean.TRUE), (ctx, dh, cnt) -> CompletableFuture.completedFuture(Boolean.FALSE)); }
public CompletableFuture<HttpResponseImpl> responseAsync(Void v) { CompletableFuture<HttpResponseImpl> cf; if (++attempts > max_attempts) { cf = CompletableFuture.failedFuture(new IOException("Too many retries")); } else { if (currentreq.timeval() != 0) { // set timer td = new TimedEvent(currentreq.timeval()); client.registerTimer(td); } Exchange exch = getExchange(); cf = requestFiltersAsync(currentreq) .thenCompose(exch::responseAsync) .thenCompose(this::responseFiltersAsync) .thenCompose( (Pair<HttpResponse, HttpRequestImpl> pair) -> { HttpResponseImpl resp = (HttpResponseImpl) pair.first; if (resp != null) { if (attempts > 1) { Log.logError("Succeeded on attempt: " + attempts); } return CompletableFuture.completedFuture(resp); } else { currentreq = pair.second; Exchange previous = exch; setExchange(new Exchange(currentreq, currentreq.getAccessControlContext())); // reads body off previous, and then waits for next response return previous .responseBodyAsync(HttpResponse.ignoreBody()) .thenCompose(this::responseAsync); } }) .handle( (BiFunction<HttpResponse, Throwable, Pair<HttpResponse, Throwable>>) Pair::new) .thenCompose( (Pair<HttpResponse, Throwable> obj) -> { HttpResponseImpl response = (HttpResponseImpl) obj.first; if (response != null) { return CompletableFuture.completedFuture(response); } // all exceptions thrown are handled here CompletableFuture<HttpResponseImpl> error = getExceptionalCF(obj.second); if (error == null) { cancelTimer(); return responseAsync(null); } else { return error; } }); } return cf; }
public void patternExamples() { String urlOne = "http://localhost:3333/one"; // #ws-composition final CompletionStage<WSResponse> responseThreePromise = ws.url(urlOne) .get() .thenCompose(responseOne -> ws.url(responseOne.getBody()).get()) .thenCompose(responseTwo -> ws.url(responseTwo.getBody()).get()); // #ws-composition // #ws-recover CompletionStage<WSResponse> responsePromise = ws.url("http://example.com").get(); CompletionStage<WSResponse> recoverPromise = responsePromise .handle( (result, error) -> { if (error != null) { return ws.url("http://backup.example.com").get(); } else { return CompletableFuture.completedFuture(result); } }) .thenCompose(Function.identity()); // #ws-recover }
@Ignore("hangs when run with other tests") @Test public void testJoinChannel() throws Exception { CountDownLatch connectedLatch = new CountDownLatch(1); String channelToJoin = "#anotherChannel"; doAnswer( invocation -> { connectedLatch.countDown(); return null; }) .when(outputIrc) .joinChannel(DEFAULT_CHANNEL_NAME); when(taskService.submitTask(any())).thenReturn(CompletableFuture.completedFuture(null)); instance.connect(); instance.connectionStateProperty().set(ConnectionState.CONNECTED); assertTrue(connectedLatch.await(TIMEOUT, TIMEOUT_UNIT)); instance.joinChannel(channelToJoin); verify(outputIrc).joinChannel(DEFAULT_CHANNEL_NAME); verify(outputIrc).joinChannel(channelToJoin); }
/** * Handles a publish request. * * @param request The publish request to handle. * @return A completable future to be completed with the publish response. */ @SuppressWarnings("unchecked") private CompletableFuture<PublishResponse> handlePublish(PublishRequest request) { if (request.session() != id) return Futures.exceptionalFuture(new UnknownSessionException("incorrect session ID")); if (request.previousVersion() != eventVersion) { return CompletableFuture.completedFuture( PublishResponse.builder() .withStatus(Response.Status.ERROR) .withError(RaftError.Type.INTERNAL_ERROR) .withVersion(eventVersion) .build()); } eventVersion = request.eventVersion(); List<CompletableFuture<Void>> futures = new ArrayList<>(request.events().size()); for (Event<?> event : request.events()) { Listeners<Object> listeners = eventListeners.get(event.name()); if (listeners != null) { futures.add(listeners.accept(event.message())); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])) .handleAsync( (result, error) -> { completeVersion = Math.max(completeVersion, request.eventVersion()); return PublishResponse.builder() .withStatus(Response.Status.OK) .withVersion(eventVersion) .build(); }, context.executor()); }
@ApiOperation( value = "To test enum parameters", notes = "", response = Void.class, tags = { "fake", }) @ApiResponses( value = { @ApiResponse(code = 400, message = "Invalid request", response = Void.class), @ApiResponse(code = 404, message = "Not found", response = Void.class) }) @RequestMapping( value = "/fake", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.GET) default CompletableFuture<ResponseEntity<Void>> testEnumParameters( @ApiParam( value = "Form parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestPart(value = "enumFormStringArray", required = false) List<String> enumFormStringArray, @ApiParam( value = "Form parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestPart(value = "enumFormString", required = false) String enumFormString, @ApiParam( value = "Header parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestHeader(value = "enum_header_string_array", required = false) List<String> enumHeaderStringArray, @ApiParam( value = "Header parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestHeader(value = "enum_header_string", required = false) String enumHeaderString, @ApiParam( value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List<String> enumQueryStringArray, @ApiParam( value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue = "-efg") String enumQueryString, @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)") @RequestPart(value = "enumQueryDouble", required = false) Double enumQueryDouble) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity<Void>(HttpStatus.OK)); }
@Override public CompletionStage<com.zeroc.Ice.Object.Ice_invokeResult> ice_invokeAsync( byte[] inEncaps, Current current) { boolean twoway = current.requestId > 0; ObjectPrx obj = current.con.createProxy(current.id); if (!twoway) { if (_startBatch) { _startBatch = false; _batchProxy = obj.ice_batchOneway(); } if (_batchProxy != null) { obj = _batchProxy; } if (!current.facet.isEmpty()) { obj = obj.ice_facet(current.facet); } final com.zeroc.Ice.Object.Ice_invokeResult success = new com.zeroc.Ice.Object.Ice_invokeResult(true, new byte[0]); if (_batchProxy != null) { obj.ice_invoke(current.operation, current.mode, inEncaps, current.ctx); return CompletableFuture.completedFuture(success); } else { final CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> future = new CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult>(); CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> r = obj.ice_oneway() .ice_invokeAsync(current.operation, current.mode, inEncaps, current.ctx); com.zeroc.Ice.Util.getInvocationFuture(r) .whenSent( (sentSynchronously, ex) -> { if (ex != null) { future.completeExceptionally(ex); } else { future.complete(success); } }); return future; } } else { if (!current.facet.isEmpty()) { obj = obj.ice_facet(current.facet); } final CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> future = new CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult>(); obj.ice_invokeAsync(current.operation, current.mode, inEncaps, current.ctx) .whenComplete( (result, ex) -> { if (ex != null) { future.completeExceptionally(ex); } else { future.complete(result); } }); return future; } }
@Override public CompletableFuture<Void> withdraw(String path) { elections.remove(path); for (LeadershipEventListener listener : listeners) { listener.event( new LeadershipEvent( Type.LEADER_BOOTED, new Leadership(path, clusterService.getLocalNode().id(), 0, 0))); } return CompletableFuture.completedFuture(null); }
public static CompletableFuture<Boolean> doesChunkExist( WorldServer world, IChunkLoader chunkLoader, Vector3i chunkCoords) { int x = chunkCoords.getX(); int z = chunkCoords.getZ(); if (!(chunkLoader instanceof IMixinAnvilChunkLoader) || !SpongeChunkLayout.instance.isValidChunk(x, chunkCoords.getY(), z)) { return CompletableFuture.completedFuture(false); } return SpongeScheduler.getInstance() .submitAsyncTask(() -> ((IMixinAnvilChunkLoader) chunkLoader).chunkExists(world, x, z)); }
@Test public void mustBeAbleToUseMapFuture() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Iterable<String> input = Arrays.asList("a", "b", "c"); Source.from(input) .mapAsync(4, elem -> CompletableFuture.completedFuture(elem.toUpperCase())) .runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); probe.expectMsgEquals("A"); probe.expectMsgEquals("B"); probe.expectMsgEquals("C"); }
@Override public CompletableFuture<Leadership> runForLeadership(String path) { elections.put(path, true); for (LeadershipEventListener listener : listeners) { listener.event( new LeadershipEvent( Type.LEADER_ELECTED, new Leadership(path, clusterService.getLocalNode().id(), 0, 0))); } return CompletableFuture.completedFuture( new Leadership(path, clusterService.getLocalNode().id(), 0, 0)); }
@Inject public JPAApiProvider(JPAConfig jpaConfig, DBApi dbApi, ApplicationLifecycle lifecycle) { // dependency on db api ensures that the databases are initialised jpaApi = new DefaultJPAApi(jpaConfig); lifecycle.addStopHook( () -> { jpaApi.shutdown(); return CompletableFuture.completedFuture(null); }); jpaApi.start(); }
@Override public Future<Void> exposeTags(@ClientId Object clientDescriptor, String... tags) { Utils.getClientIdentifier(consumer, clientDescriptor) .ifPresent( clientIdentifier -> producer.addNode( array("management", "clients", clientIdentifier.getClientId()), "tags", tags == null ? new String[0] : tags)); return CompletableFuture.completedFuture(null); }
default <R> CompletableFuture<R> applyAsync8( Function< T1, Function< T2, Function< T3, Function<T4, Function<T5, Function<T6, Function<T7, Function<T8, R>>>>>>>> fn) { return CompletableFuture.completedFuture(v8()) .thenApplyAsync( fn.apply(v1()).apply(v2()).apply(v3()).apply(v4()).apply(v5()).apply(v6()).apply(v7())); }
@Override public CompletableFuture<Void> removeListener(AtomicValueEventListener<V> listener) { checkNotNull(listener, "listener must not be null"); final MeteringAgent.Context newTimer = monitor.startTimer(REMOVE_LISTENER); MapEventListener<String, byte[]> mapListener = listeners.remove(listener); if (mapListener != null) { return backingMap.removeListener(mapListener).whenComplete((r, e) -> newTimer.stop(e)); } else { newTimer.stop(null); return CompletableFuture.completedFuture(null); } }
@Inject public EbeanDynamicEvolutions( EbeanConfig config, Environment environment, ApplicationLifecycle lifecycle) { this.config = config; this.environment = environment; start(); lifecycle.addStopHook( () -> { servers.forEach((database, server) -> server.shutdown(false, false)); return CompletableFuture.completedFuture(null); }); }
@Test public void shouldUnwrapUserFutureAndReturnIt() throws Exception { // given final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock); given(serviceMock.safeAsync()).willReturn(CompletableFuture.completedFuture("42")); // when final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync()); // then assertThat(future.get()).isEqualTo("42"); }
@SuppressWarnings("unchecked") private void mockTaskService() { doAnswer( (InvocationOnMock invocation) -> { PrioritizedTask<Boolean> prioritizedTask = invocation.getArgumentAt(0, PrioritizedTask.class); prioritizedTask.run(); Future<Boolean> result = WaitForAsyncUtils.asyncFx(prioritizedTask::getValue); return CompletableFuture.completedFuture(result.get(1, TimeUnit.SECONDS)); }) .when(instance.taskService) .submitTask(any()); }
@Override public CompletionStage<Result> newBundle() { /* Form<NewEnvironment> form = NewEnvironment.form(); final models.Environment parent = models.Environment.getByName(parentEnv); if (parent != null) { final NewEnvironment env = new NewEnvironment(); env.parent = parent.getId(); form = form.fill(env); } final List<Owner> owners = UserMembership.getOrgsForUser(request().username()); return ok(views.html.newEnvironment.render(form, owners)); */ return CompletableFuture.completedFuture(ok()); }
@Override public CompletableFuture<CommitResponse> prepareAndCommit(Transaction transaction) { Map<Database, Transaction> subTransactions = createSubTransactions(transaction); if (subTransactions.isEmpty()) { return CompletableFuture.completedFuture(CommitResponse.success(ImmutableList.of())); } else if (subTransactions.size() == 1) { Entry<Database, Transaction> entry = subTransactions.entrySet().iterator().next(); return entry.getKey().prepareAndCommit(entry.getValue()); } else { if (transactionManager == null) { throw new IllegalStateException("TransactionManager is not initialized"); } return transactionManager.execute(transaction); } }
@Override public CompletableFuture<Void> listen(Address address, Consumer<Connection> listener) { Assert.notNull(address, "address"); Assert.notNull(listener, "listener"); if (listening) return CompletableFuture.completedFuture(null); ThreadContext context = ThreadContext.currentContextOrThrow(); synchronized (this) { if (listenFuture == null) { listenFuture = new CompletableFuture<>(); listen(address, listener, context); } } return listenFuture; }
@Override public CompletableFuture<Void> destroy() { destroyed = true; executor.shutdown(); backgroundExecutor.shutdown(); communicationExecutor.shutdown(); listeners.clear(); clusterCommunicator.removeSubscriber(updateMessageSubject); clusterCommunicator.removeSubscriber(updateRequestSubject); clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject); return CompletableFuture.completedFuture(null); }
public CompletableFuture<Object> melange( int pi1, short ps1, byte pb1, double pd1, char pc1, boolean pz1, long lg1, Object po1, float pf1, CompletableFuture<String> blocker, long var) { // blocks with a lot of primitives in the stack this.setFields(pi1, ps1, pb1, pd1, pc1, pz1, lg1, po1, pf1, await(blocker) != null ? 0 : 1); return CompletableFuture.completedFuture(":"); }
public CompletableFuture<Object> melange( int pi1, short ps1, byte pb1, double pd1, char pc1, boolean pz1, long lg1, Object po1, float pf1, CompletableFuture<String> blocker, long var) { await(blocker); setFields(pi1, ps1, pb1, pd1, pc1, pz1, lg1, po1, pf1, 0); return CompletableFuture.completedFuture(":"); }
static <T> CompletableFuture<T> withFuture( Param<FutureMode> futureParam, ExecutorService asyncExec, Supplier<T> s) { switch (futureParam.get()) { case COMPLETED: // If completed, complete the future directly with the result. // No separate thread or executor is instantiated. return CompletableFuture.completedFuture(s.get()); case ASYNC: // If async, execute the supply function asynchronously, // and return a future that's completed when the supply // function returns. return CompletableFuture.supplyAsync(s, asyncExec); default: throw new IllegalStateException(); } }
@Test public void testSendActionInBackground() throws Exception { instance.connect(); String action = "test action"; when(taskService.submitTask(any())).thenReturn(CompletableFuture.completedFuture(action)); mockTaskService(); CompletableFuture<String> future = instance.sendActionInBackground(DEFAULT_CHANNEL_NAME, action); verify(pircBotX).sendIRC(); verify(outputIrc).action(DEFAULT_CHANNEL_NAME, action); assertThat(future.get(TIMEOUT, TIMEOUT_UNIT), is(action)); }
public static CompletableFuture<Optional<DataContainer>> getChunkData( WorldServer world, IChunkLoader chunkLoader, Vector3i chunkCoords) { int x = chunkCoords.getX(); int y = chunkCoords.getY(); int z = chunkCoords.getZ(); if (!(chunkLoader instanceof IMixinAnvilChunkLoader) || !SpongeChunkLayout.instance.isValidChunk(x, y, z)) { return CompletableFuture.completedFuture(Optional.empty()); } File worldDir = ((IMixinAnvilChunkLoader) chunkLoader).getWorldDir().toFile(); return SpongeScheduler.getInstance() .submitAsyncTask( () -> { DataInputStream stream = RegionFileCache.getChunkInputStream(worldDir, x, z); return Optional.ofNullable(readDataFromRegion(stream)); }); }
@Test public void shouldSucceedAfterFewAsynchronousRetries() throws Exception { // given final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock); given(serviceMock.safeAsync()) .willReturn( failedAsync(new SocketException("First")), failedAsync(new IOException("Second")), CompletableFuture.completedFuture("42")); // when final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync()); // then assertThat(future.get()).isEqualTo("42"); }
/** * Registers a cache entry listener based on the supplied configuration. * * @param configuration the listener's configuration. */ public void register(CacheEntryListenerConfiguration<K, V> configuration) { if (configuration.getCacheEntryListenerFactory() == null) { return; } EventTypeAwareListener<K, V> listener = new EventTypeAwareListener<>(configuration.getCacheEntryListenerFactory().create()); CacheEntryEventFilter<K, V> filter = event -> true; if (configuration.getCacheEntryEventFilterFactory() != null) { filter = new EventTypeFilter<K, V>( listener, configuration.getCacheEntryEventFilterFactory().create()); } Registration<K, V> registration = new Registration<>(configuration, filter, listener); dispatchQueues.putIfAbsent(registration, CompletableFuture.completedFuture(null)); }
public static void main(String... args) { CompletableFuture<String> a = CompletableFuture.supplyAsync( () -> { try { Thread.sleep(5000); return "a1"; } catch (InterruptedException e) { throw new RuntimeException(e); } }); a.thenCombineAsync(CompletableFuture.completedFuture("b2"), (x, y) -> x + " : " + y) .thenAcceptAsync(System.out::println) .join(); }