List of usage examples for java.util.concurrent CompletableFuture supplyAsync
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
From source file:grakn.core.daemon.executor.Executor.java
public CompletableFuture<Result> executeAsync(List<String> command, File workingDirectory) { return CompletableFuture.supplyAsync(() -> executeAndWait(command, workingDirectory)); }
From source file:com.linecorp.armeria.server.http.auth.AuthServiceTest.java
@Override protected void configureServer(ServerBuilder sb) throws Exception { // Auth with arbitrary authorizer Authorizer<HttpRequest> authorizer = (ctx, req) -> CompletableFuture .supplyAsync(() -> "unit test".equals(req.headers().get(HttpHeaderNames.AUTHORIZATION))); sb.serviceAt("/", new AbstractHttpService() { @Override//from w ww. j a v a2 s. c o m protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK); } }.decorate(HttpAuthService.newDecorator(authorizer)).decorate(LoggingService::new)); // Auth with HTTP basic final Map<String, String> usernameToPassword = ImmutableMap.of("brown", "cony", "pangyo", "choco"); Authorizer<BasicToken> httpBasicAuthorizer = (ctx, token) -> { String username = token.username(); String password = token.password(); return CompletableFuture.completedFuture(password.equals(usernameToPassword.get(username))); }; sb.serviceAt("/basic", new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK); } }.decorate(new HttpAuthServiceBuilder().addBasicAuth(httpBasicAuthorizer).newDecorator()) .decorate(LoggingService::new)); // Auth with OAuth1a Authorizer<OAuth1aToken> oAuth1aAuthorizer = (ctx, token) -> CompletableFuture .completedFuture("dummy_signature".equals(token.signature())); sb.serviceAt("/oauth1a", new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK); } }.decorate(new HttpAuthServiceBuilder().addOAuth1a(oAuth1aAuthorizer).newDecorator()) .decorate(LoggingService::new)); // Auth with OAuth2 Authorizer<OAuth2Token> oAuth2aAuthorizer = (ctx, token) -> CompletableFuture .completedFuture("dummy_oauth2_token".equals(token.accessToken())); sb.serviceAt("/oauth2", new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK); } }.decorate(new HttpAuthServiceBuilder().addOAuth2(oAuth2aAuthorizer).newDecorator()) .decorate(LoggingService::new)); // Auth with all predicates above! HttpService compositeService = new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK); } }; HttpAuthService compositeAuth = new HttpAuthServiceBuilder().add(authorizer) .addBasicAuth(httpBasicAuthorizer).addOAuth1a(oAuth1aAuthorizer).addOAuth2(oAuth2aAuthorizer) .build(compositeService); sb.serviceAt("/composite", compositeAuth.decorate(LoggingService::new)); }
From source file:ch.sdi.report.SdiReporter.java
/** * Adds given ReportMsg to the internal memory * <p>/* w w w. j a va 2s . c o m*/ * @param aMsg */ public void add(ReportMsg aMsg) { // Since wie are already in a call from a logger there would be an error entry if we call // the logger again ("Recursive call to appender "). So log this asynchroneously: CompletableFuture.supplyAsync(() -> "adding a message").thenAcceptAsync(myLog::trace); myMessages.add(aMsg); }
From source file:org.trustedanalytics.kafka.adminapi.api.ApiController.java
@RequestMapping(method = RequestMethod.GET, value = "/topics/{topic}") @ResponseBody//from w ww .j a v a2 s . c o m public DeferredResult<List<String>> readTopic(@PathVariable final String topic) { LOG.info("readTopic invoked: {}", topic); if (StringUtils.isEmpty(topic)) { throw new InvalidTopicException("Missing mandatory topic name"); } Topic.validate(topic); if (!kafkaService.topicExists(topic)) { throw new UnknownTopicOrPartitionException("Topic does not exist: " + topic); } DeferredResult<List<String>> deferredResult = new DeferredResult<>(); CompletableFuture.supplyAsync(() -> kafkaService.readTopic(topic)) .whenCompleteAsync((result, throwable) -> { deferredResult.setResult(result); deferredResult.setErrorResult(throwable); }); return deferredResult; }
From source file:co.runrightfast.core.application.services.healthchecks.impl.HealthChecksServiceImpl.java
@Override public CompletableFuture<Collection<HealthCheck.Result>> runHealthChecksAsync() { return CompletableFuture.supplyAsync(this::runHealthChecks); }
From source file:ws.salient.session.Sessions.java
public CompletableFuture execute(List<Command> commands) { Instant now = Instant.now(); CompletableFuture result;/*from w w w. j av a 2 s . c o m*/ try { commands.stream().filter(command -> command instanceof ModifyProfile).forEach((command) -> { log.info(toJson(command)); profiles.modified(command.getAccountId()); }); commands.stream().filter(command -> command.getKnowledgeBaseId() != null).forEach((command) -> { String knowledgeBaseId = command.getKnowledgeBaseId(); Map<String, String> aliases = profiles.getAliases(command.getAccountId(), command.getProfiles()); if (aliases.containsKey(knowledgeBaseId)) { knowledgeBaseId = aliases.get(knowledgeBaseId); } command.setKnowledgeBaseId(knowledgeBaseId); }); commands.forEach((command) -> { command.setTimestamp(now); }); // Load knowledge bases in parallel List<CompletableFuture<KnowledgeBase>> knowledgeBases = commands.stream() .filter(command -> command.getKnowledgeBaseId() != null) .collect(Collectors.groupingBy((command) -> { // Group commands by knowledgeBaseId return command.getKnowledgeBaseId(); })).values().stream().map((kbaseCommands) -> { return CompletableFuture.supplyAsync(() -> { // Load each knowledge base return repository.getKnowledgeBase(kbaseCommands.get(0).getKnowledgeBaseId()); }); }).collect(Collectors.toList()); CompletableFuture.allOf(knowledgeBases.toArray(new CompletableFuture[knowledgeBases.size()])).get(); // Load sessions in parallel List<CompletableFuture<Session>> sessions = commands.stream() .filter(command -> command.getSessionId() != null).collect(Collectors.groupingBy((command) -> { // Group commands by sessionId return command.getSessionId(); })).values().stream().map((sessionCommands) -> { return CompletableFuture.supplyAsync(() -> { // Load each session return getSession(sessionCommands.get(0)); }); }).collect(Collectors.toList()); CompletableFuture.allOf(sessions.toArray(new CompletableFuture[sessions.size()])).get(); result = CompletableFuture.runAsync(() -> { int requestIndex = 0; for (Command command : commands) { if (command.getSessionId() != null) { command.setTimestamp(now); Session session = getSession(command); session.accept(command); store.put(session, command, requestIndex); requestIndex++; } } }, commandExecutor).thenRun(() -> { this.sessions.forEach((id, session) -> { if (session.expired(now)) { if (session.getProcessCount() == 0) { int oldcount = sessions.size(); sessions.remove(id); session.dispose(); log.info("Session count was " + oldcount + " now " + sessions.size()); } } }); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return result; }
From source file:Main.java
private Future<?> getOperationResult(List<BlockingQueue<T>> queues, Function<Stream<T>, ?> f) { BlockingQueue<T> queue = new LinkedBlockingQueue<>(); queues.add(queue);// www . ja va 2 s .c om Spliterator<T> spliterator = new BlockingQueueSpliterator<>(queue); Stream<T> source = StreamSupport.stream(spliterator, false); return CompletableFuture.supplyAsync(() -> f.apply(source)); }
From source file:io.dropwizard.revolver.core.RevolverCommand.java
@SuppressWarnings("unchecked") public CompletableFuture<ResponseType> executeAsync(final RequestType request) { final RequestType normalizedRequest = RevolverCommandHelper.normalize(request); final TraceInfo traceInfo = normalizedRequest.getTrace(); addContextInfo(request, traceInfo);//from w w w . j ava2 s .co m final Stopwatch watch = Stopwatch.createStarted(); final Future<ResponseType> responseFuture = new RevolverCommandHandler( RevolverCommandHelper.setter(this, request.getApi()), this.context, this, normalizedRequest) .queue(); return CompletableFuture.supplyAsync(() -> { String errorMessage = null; try { return responseFuture.get(); } catch (Throwable t) { errorMessage = RevolverExceptionHelper.getLeafErrorMessage(t); throw new RevolverExecutionException(RevolverExecutionException.Type.SERVICE_ERROR, String.format("Error executing command %s", RevolverCommandHelper.getName(request)), RevolverExceptionHelper.getLeafThrowable(t)); } finally { publishTrace(Trace.builder().caller(this.clientConfiguration.getClientName()) .service(this.serviceConfiguration.getService()).api(request.getApi()) .duration(watch.stop().elapsed(TimeUnit.MILLISECONDS)) .transactionId(traceInfo.getTransactionId()).requestId(traceInfo.getRequestId()) .parentRequestId(traceInfo.getParentRequestId()).timestamp(traceInfo.getTimestamp()) .attributes(traceInfo.getAttributes()).error(!Strings.isNullOrEmpty(errorMessage)) .errorReason(errorMessage).build()); removeContextInfo(); } }); }
From source file:ai.grakn.client.LoaderClient.java
/** * A completable future that polls the Task Controller to check for the status of the * given ID. It terminates when the status of that task is COMPLETED, FAILED or STOPPED. * * @param id ID of the task to wait on completion * @return Completable future that will await completion of the given task *//*from w w w . j av a 2 s . c o m*/ private CompletableFuture<Json> makeTaskCompletionFuture(String id) { return CompletableFuture.supplyAsync(() -> { while (true) { try { Json taskState = getStatus(id); TaskStatus status = TaskStatus.valueOf(taskState.at(TASK_STATUS_PARAMETER).asString()); if (status == COMPLETED || status == FAILED || status == STOPPED) { return taskState; } } catch (IllegalArgumentException e) { // Means the task has not yet been stored: we want to log the error, but continue looping LOG.warn(format("Task [%s] not found on server. Attempting to get status again.", id)); } catch (HttpRetryException e) { LOG.warn(format("Could not communicate with host %s for task [%s] ", uri, id)); if (retry) { LOG.warn(format("Attempting communication again with host %s for task [%s]", uri, id)); } else { throw new RuntimeException(e); } } catch (Throwable t) { throw new RuntimeException(t); } finally { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }); }
From source file:com.hurence.logisland.engine.vanilla.stream.amqp.AmqpClientPipelineStream.java
private void handleConnectionFailure(boolean remoteClose) { try {//from w ww . j a v a 2s . c o m if (protonConnection != null) { protonConnection.closeHandler(null); protonConnection.disconnectHandler(null); if (remoteClose) { protonConnection.close(); protonConnection.disconnect(); } } } finally { if (connectionControl.shouldReconnect()) { connectionControl .scheduleReconnect((vertx) -> CompletableFuture.supplyAsync(this::setupConnection)); } } }