List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:org.apache.tinkerpop.gremlin.driver.simple.AbstractClient.java
@Override public CompletableFuture<List<ResponseMessage>> submitAsync(final RequestMessage requestMessage) throws Exception { final List<ResponseMessage> results = new ArrayList<>(); final CompletableFuture<List<ResponseMessage>> f = new CompletableFuture<>(); callbackResponseHandler.callback = response -> { if (f.isDone()) throw new RuntimeException( "A terminating message was already encountered - no more messages should have been received"); results.add(response);//www . j av a 2 s. c o m // check if the current message is terminating - if it is then we can mark complete if (!response.getStatus().getCode().equals(ResponseStatusCode.PARTIAL_CONTENT)) { f.complete(results); } }; writeAndFlush(requestMessage); return f; }
From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java
public static void dumpContainerLogToTarget(DockerClient dockerClient, String containerId) { InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec(); // docker api returns names prefixed with "/", it's part of it's legacy design, // this removes it to be consistent with what docker ps shows. final String containerName = inspectContainerResponse.getName().replace("/", ""); File output = new File(getTargetDirectory(containerName), "docker.log"); int i = 0;//from w w w .j av a 2 s. c om while (output.exists()) { LOG.info("{} exists, incrementing", output); output = new File(getTargetDirectory(containerName), "docker." + i++ + ".log"); } try (FileOutputStream os = new FileOutputStream(output)) { CompletableFuture<Boolean> future = new CompletableFuture<>(); dockerClient.logContainerCmd(containerName).withStdOut(true).withStdErr(true).withTimestamps(true) .exec(new ResultCallback<Frame>() { @Override public void close() { } @Override public void onStart(Closeable closeable) { } @Override public void onNext(Frame object) { try { os.write(object.getPayload()); } catch (IOException e) { onError(e); } } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { future.complete(true); } }); future.get(); } catch (RuntimeException | ExecutionException | IOException e) { LOG.error("Error dumping log for {}", containerName, e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.info("Interrupted dumping log from container {}", containerName, ie); } }
From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java
private CompletableFuture<AsyncConnection> getConn() { CompletableFuture<AsyncConnection> f = future.get(); if (f != null) { return f; }/*w w w.j a va2s. com*/ for (;;) { if (future.compareAndSet(null, new CompletableFuture<>())) { CompletableFuture<AsyncConnection> toComplete = future.get(); addListener(ConnectionFactory.createAsyncConnection(getConf()), (conn, error) -> { if (error != null) { toComplete.completeExceptionally(error); // we need to reset the future holder so we will get a chance to recreate an async // connection at next try. future.set(null); return; } toComplete.complete(conn); }); return toComplete; } else { f = future.get(); if (f != null) { return f; } } } }
From source file:org.apache.hadoop.hbase.client.AsyncRpcRetryingCaller.java
public AsyncRpcRetryingCaller(HashedWheelTimer retryTimer, AsyncConnectionImpl conn, long pauseNs, int maxAttempts, long operationTimeoutNs, long rpcTimeoutNs, int startLogErrorsCnt) { this.retryTimer = retryTimer; this.conn = conn; this.pauseNs = pauseNs; this.maxAttempts = maxAttempts; this.operationTimeoutNs = operationTimeoutNs; this.rpcTimeoutNs = rpcTimeoutNs; this.startLogErrorsCnt = startLogErrorsCnt; this.future = new CompletableFuture<>(); this.controller = conn.rpcControllerFactory.newController(); this.exceptions = new ArrayList<>(); this.startNs = System.nanoTime(); }
From source file:org.pac4j.vertx.cas.VertxSharedDataLogoutHandler.java
@Override public void destroySession(WebContext context) { final String logoutRequest = context.getRequestParameter("logoutRequest"); LOG.debug("logoutRequest: {}", logoutRequest); final String ticket = StringUtils.substringBetween(logoutRequest, "SessionIndex>", "</"); LOG.debug("extract ticket: {}", ticket); // get the session id first, then remove the pac4j profile from that session // TODO: ALSO MODIFY TO REMOVE VERTX USER final CompletableFuture<Void> userLogoutFuture = new CompletableFuture<>(); final String sessionId = getSessionId(ticket); sessionStore.getObservable(sessionId).map(session -> session.remove(SESSION_USER_HOLDER_KEY)) .doOnError(e -> {//from w w w . ja v a 2 s . com e.printStackTrace(); }).subscribe(s -> userLogoutFuture.complete(null)); try { userLogoutFuture.get(blockingTimeoutSeconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { userLogoutFuture.completeExceptionally(new TechnicalException(e)); } doDestroySession(ticket); }
From source file:org.apache.trafficcontrol.client.trafficops.TOSessionTest.java
@Test public void deliveryServices() throws Throwable { final HttpResponse resp = Mockito.mock(HttpResponse.class); Mockito.doReturn(new BasicStatusLine(HttpVersion.HTTP_1_0, 200, "Ok")).when(resp).getStatusLine(); Mockito.doReturn(new StringEntity(DeliveryService_Good_Response)).when(resp).getEntity(); final CompletableFuture<HttpResponse> f = new CompletableFuture<>(); f.complete(resp);//from www . j a v a 2 s . co m Mockito.doReturn(f).when(sessionMock).execute(Mockito.any(RequestBuilder.class)); final TOSession session = TOSession.builder().fromURI(baseUri).setRestClient(sessionMock).build(); CollectionResponse cResp = session.getDeliveryServices().get(); assertNotNull(cResp); assertNotNull(cResp.getResponse()); assertEquals(1, cResp.getResponse().size()); final Map<String, ?> service = cResp.getResponse().get(0); assertEquals("us-co-denver", service.get("cachegroup")); LOG.debug("Service: {}", service); }
From source file:org.apache.hadoop.hbase.client.ZKAsyncRegistry.java
private static <T> CompletableFuture<T> exec(BackgroundPathable<?> opBuilder, String path, CuratorEventProcessor<T> processor) { CompletableFuture<T> future = new CompletableFuture<>(); try {/*from w w w . j av a 2 s . com*/ opBuilder.inBackground((client, event) -> { try { future.complete(processor.process(event)); } catch (Exception e) { future.completeExceptionally(e); } }).withUnhandledErrorListener((msg, e) -> future.completeExceptionally(e)).forPath(path); } catch (Exception e) { future.completeExceptionally(e); } return future; }
From source file:com.yahoo.pulsar.common.naming.NamespaceBundleFactory.java
public NamespaceBundleFactory(PulsarService pulsar, HashFunction hashFunc) { this.hashFunc = hashFunc; this.bundlesCache = Caffeine.newBuilder().buildAsync((NamespaceName namespace, Executor executor) -> { String path = AdminResource.joinPath(LOCAL_POLICIES_ROOT, namespace.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Loading cache with bundles for {}", namespace); }//w ww . j a va 2 s .c om if (pulsar == null || pulsar.getConfigurationCache() == null) { return CompletableFuture.completedFuture(getBundles(namespace, null)); } CompletableFuture<NamespaceBundles> future = new CompletableFuture<>(); // Read the static bundle data from the policies pulsar.getLocalZkCacheService().policiesCache().getAsync(path).thenAccept(policies -> { // If no policies defined for namespace, assume 1 single bundle BundlesData bundlesData = policies.map(p -> p.bundles).orElse(null); NamespaceBundles namespaceBundles = getBundles(namespace, bundlesData); future.complete(namespaceBundles); }).exceptionally(ex -> { future.completeExceptionally(ex); return null; }); return future; }); if (pulsar != null && pulsar.getConfigurationCache() != null) { pulsar.getLocalZkCacheService().policiesCache().registerListener(this); } this.pulsar = pulsar; }
From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java
public CompletableFuture<Boolean> login(final String username, final String password) { URI uri;//from w w w . java 2 s . c o m try { uri = this.newUriBuilder("user/login.json").build(); } catch (Throwable e) { final CompletableFuture<Boolean> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } LOG.debug("Logging into: {}", uri); return ResponseFuture.builder().setHandleException((f, t) -> { f.completeExceptionally( new LoginException(String.format("Failed to login with username %s", username), t)); }).setMethod(ResponseFuture.Method.POST).setUri(uri).setSession(this.restClient()) .setBody(gson.toJson(ImmutableMap.<String, String>of("u", username, "p", password))).build() .thenApply(r -> { isLoggedIn = true; return true; }); }
From source file:msuresh.raftdistdb.RaftCluster.java
private static JSONArray CreatePartitionCluster(int numReplicas) throws ExecutionException, InterruptedException { JSONArray arr = new JSONArray(); JSONObject[] lis = new JSONObject[numReplicas]; List<Address> members = new ArrayList<>(); SetupServerAddress(numReplicas, lis, members, arr); CompletableFuture<Integer> future = new CompletableFuture<>(); List<CopycatServer> atomixList = new ArrayList<>(); for (Address a : members) { ServerSetup s = new ServerSetup(members, a, atomixList, future); s.start();//from ww w . ja v a 2 s .co m } future.get(); return arr; }