List of usage examples for java.util.concurrent CompletableFuture complete
public boolean complete(T value)
From source file:org.apache.pulsar.broker.lookup.TopicLookup.java
/** * * Lookup broker-service address for a given namespace-bundle which contains given topic. * * a. Returns broker-address if namespace-bundle is already owned by any broker * b. If current-broker receives lookup-request and if it's not a leader * then current broker redirects request to leader by returning leader-service address. * c. If current-broker is leader then it finds out least-loaded broker to own namespace bundle and * redirects request by returning least-loaded broker. * d. If current-broker receives request to own the namespace-bundle then it owns a bundle and returns * success(connect) response to client.//from w ww. j a v a 2 s.co m * * @param pulsarService * @param topicName * @param authoritative * @param clientAppId * @param requestId * @return */ public static CompletableFuture<ByteBuf> lookupTopicAsync(PulsarService pulsarService, TopicName topicName, boolean authoritative, String clientAppId, AuthenticationDataSource authenticationData, long requestId) { final CompletableFuture<ByteBuf> validationFuture = new CompletableFuture<>(); final CompletableFuture<ByteBuf> lookupfuture = new CompletableFuture<>(); final String cluster = topicName.getCluster(); // (1) validate cluster getClusterDataIfDifferentCluster(pulsarService, cluster, clientAppId).thenAccept(differentClusterData -> { if (differentClusterData != null) { if (log.isDebugEnabled()) { log.debug("[{}] Redirecting the lookup call to {}/{} cluster={}", clientAppId, differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), cluster); } validationFuture.complete(newLookupResponse(differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); } else { // (2) authorize client try { checkAuthorization(pulsarService, topicName, clientAppId, authenticationData); } catch (RestException authException) { log.warn("Failed to authorized {} on cluster {}", clientAppId, topicName.toString()); validationFuture.complete(newLookupErrorResponse(ServerError.AuthorizationError, authException.getMessage(), requestId)); return; } catch (Exception e) { log.warn("Unknown error while authorizing {} on cluster {}", clientAppId, topicName.toString()); validationFuture.completeExceptionally(e); return; } // (3) validate global namespace checkLocalOrGetPeerReplicationCluster(pulsarService, topicName.getNamespaceObject()) .thenAccept(peerClusterData -> { if (peerClusterData == null) { // (4) all validation passed: initiate lookup validationFuture.complete(null); return; } // if peer-cluster-data is present it means namespace is owned by that peer-cluster and // request should be redirect to the peer-cluster if (StringUtils.isBlank(peerClusterData.getBrokerServiceUrl()) && StringUtils.isBlank(peerClusterData.getBrokerServiceUrl())) { validationFuture.complete(newLookupErrorResponse(ServerError.MetadataError, "Redirected cluster's brokerService url is not configured", requestId)); return; } validationFuture.complete(newLookupResponse(peerClusterData.getBrokerServiceUrl(), peerClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); }).exceptionally(ex -> { validationFuture.complete( newLookupErrorResponse(ServerError.MetadataError, ex.getMessage(), requestId)); return null; }); } }).exceptionally(ex -> { validationFuture.completeExceptionally(ex); return null; }); // Initiate lookup once validation completes validationFuture.thenAccept(validaitonFailureResponse -> { if (validaitonFailureResponse != null) { lookupfuture.complete(validaitonFailureResponse); } else { pulsarService.getNamespaceService().getBrokerServiceUrlAsync(topicName, authoritative) .thenAccept(lookupResult -> { if (log.isDebugEnabled()) { log.debug("[{}] Lookup result {}", topicName.toString(), lookupResult); } if (!lookupResult.isPresent()) { lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, "No broker was available to own " + topicName, requestId)); return; } LookupData lookupData = lookupResult.get().getLookupData(); if (lookupResult.get().isRedirect()) { boolean newAuthoritative = isLeaderBroker(pulsarService); lookupfuture.complete( newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), newAuthoritative, LookupType.Redirect, requestId, false)); } else { // When running in standalone mode we want to redirect the client through the service // url, so that the advertised address configuration is not relevant anymore. boolean redirectThroughServiceUrl = pulsarService.getConfiguration() .isRunningStandalone(); lookupfuture.complete(newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), true /* authoritative */, LookupType.Connect, requestId, redirectThroughServiceUrl)); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info("Failed to lookup {} for topic {} with error {}", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn("Failed to lookup {} for topic {} with error {}", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info("Failed to lookup {} for topic {} with error {}", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn("Failed to lookup {} for topic {} with error {}", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); return lookupfuture; }
From source file:com.digitalpetri.opcua.raspberrypi.PiServer.java
private CompletableFuture<Void> shutdownFuture() { CompletableFuture<Void> future = new CompletableFuture<>(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.shutdown();/*from w w w.j a va2 s .c o m*/ future.complete(null); })); return future; }
From source file:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java
private CompletableFuture<ReadStream<Buffer>> prepareReadStream() { CompletableFuture<ReadStream<Buffer>> future = new CompletableFuture<>(); if (ReadStreamPart.class.isInstance(part)) { future.complete(((ReadStreamPart) part).getReadStream()); return future; }/*from ww w .ja v a2s . co m*/ try { InputStream inputStream = part.getInputStream(); InputStreamToReadStream inputStreamToReadStream = new InputStreamToReadStream(context, inputStream, true); inputStreamToReadStream.pause(); future.complete(inputStreamToReadStream); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:opensnap.repository.MongoRepository.java
public CompletableFuture<Long> count(String key, Object value) { CompletableFuture<Long> future = new CompletableFuture<>(); collection.find(new Document(key, value)).count().register((count, e) -> future.complete(count)); return future; }
From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableWriteFunction.java
/** * Helper method for putAsync and deleteAsync to convert Single to CompletableFuture. *///from w w w . j ava 2 s.c om private CompletableFuture<Void> asyncWriteHelper(Single<? extends Document<?>> single, String errorMessage) { CompletableFuture<Void> future = new CompletableFuture<>(); single.subscribe(new SingleSubscriber<Document>() { @Override public void onSuccess(Document v) { future.complete(null); } @Override public void onError(Throwable error) { future.completeExceptionally(new SamzaException(errorMessage, error)); } }); return future; }
From source file:pt.isel.mpd.util.HttpGwAsyncNio.java
public CompletableFuture<Response> getDataAsync(String path) { CompletableFuture<Response> promise = new CompletableFuture<>(); client.prepareGet(path).execute(new AsyncCompletionHandler<Object>() { @Override/*ww w. j a v a 2s . c o m*/ public Object onCompleted(Response response) throws Exception { promise.complete(response); return response; } }); return promise; }
From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "it is valid to pass NULL to CompletableFuture#completedFuture") private CompletableFuture<Void> closeConn() { CompletableFuture<AsyncConnection> f = future.get(); if (f == null) { return CompletableFuture.completedFuture(null); }//from w w w . j av a2 s. co m CompletableFuture<Void> closeFuture = new CompletableFuture<>(); addListener(f, (conn, error) -> { if (error == null) { IOUtils.closeQuietly(conn); } closeFuture.complete(null); }); return closeFuture; }
From source file:de.thingweb.servient.ServientTestHttp.java
@Test public void attachListenerAndsetDirectly() throws Exception { CompletableFuture<Integer> future = new CompletableFuture<>(); thing.onActionInvoke("testaction", (nv) -> { Integer newVal = ContentHelper.ensureClass(nv, Integer.class); future.complete(newVal); return null; });// w ww. j av a 2s .co m TestTools.postHttpJson("http://localhost:8080/things/simplething/testaction", "42"); assertThat("value is 42", future.get(), is(42)); }
From source file:org.ulyssis.ipp.control.CommandDispatcher.java
public Result send(Command command) { final CompletableFuture<Result> future = new CompletableFuture<>(); sendAsync(command, (c, r) -> {//from www.j a v a 2s. c o m assert (c == command); future.complete(r); }); try { return future.get(); } catch (InterruptedException e) { return Result.TIMEOUT; } catch (ExecutionException e) { LOG.error("We got an ExecutionException. This should not happen.", e.getCause()); return Result.ERROR; } }
From source file:opensnap.repository.MongoRepository.java
public CompletableFuture<T> getOne(String key, Object value) { CompletableFuture<T> future = new CompletableFuture<>(); collection.find(new Document(key, value)).one().register((document, e) -> { try {/*from ww w .ja v a2 s.co m*/ if (document != null) { future.complete(mapper.readValue(toJson(document), clazz)); } else { logger.error("No document with attribute " + key + "=" + value + " found", e); future.cancel(true); } } catch (IOException ex) { logger.error("Error while parsing document in getOne() : " + document.toString(), ex); future.cancel(true); } }); return future; }