List of usage examples for java.util.concurrent CompletableFuture complete
public boolean complete(T value)
From source file:io.pravega.client.stream.mock.MockController.java
private boolean deleteSegment(String name, PravegaNodeUri uri) { CompletableFuture<Boolean> result = new CompletableFuture<>(); FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override/* w ww.j a va 2s . c o m*/ public void connectionDropped() { result.completeExceptionally(new ConnectionClosedException()); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally(new NotImplementedException()); } @Override public void segmentDeleted(WireCommands.SegmentDeleted segmentDeleted) { result.complete(true); } @Override public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) { result.complete(false); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; DeleteSegment command = new WireCommands.DeleteSegment(idGenerator.get(), name); sendRequestOverNewConnection(command, replyProcessor, result); return getAndHandleExceptions(result, RuntimeException::new); }
From source file:org.apache.pulsar.broker.web.PulsarWebResource.java
public static CompletableFuture<ClusterData> checkLocalOrGetPeerReplicationCluster(PulsarService pulsarService, NamespaceName namespace) {//from w w w . j a v a 2 s .co m if (!namespace.isGlobal()) { return CompletableFuture.completedFuture(null); } final CompletableFuture<ClusterData> validationFuture = new CompletableFuture<>(); final String localCluster = pulsarService.getConfiguration().getClusterName(); final String path = AdminResource.path(POLICIES, namespace.toString()); pulsarService.getConfigurationCache().policiesCache().getAsync(path).thenAccept(policiesResult -> { if (policiesResult.isPresent()) { Policies policies = policiesResult.get(); if (policies.replication_clusters.isEmpty()) { String msg = String.format( "Namespace does not have any clusters configured : local_cluster=%s ns=%s", localCluster, namespace.toString()); log.warn(msg); validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg)); } else if (!policies.replication_clusters.contains(localCluster)) { ClusterData ownerPeerCluster = getOwnerFromPeerClusterList(pulsarService, policies.replication_clusters); if (ownerPeerCluster != null) { // found a peer that own this namespace validationFuture.complete(ownerPeerCluster); return; } String msg = String.format( "Namespace missing local cluster name in clusters list: local_cluster=%s ns=%s clusters=%s", localCluster, namespace.toString(), policies.replication_clusters); log.warn(msg); validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg)); } else { validationFuture.complete(null); } } else { String msg = String.format("Policies not found for %s namespace", namespace.toString()); log.error(msg); validationFuture.completeExceptionally(new RestException(Status.NOT_FOUND, msg)); } }).exceptionally(ex -> { String msg = String.format( "Failed to validate global cluster configuration : cluster=%s ns=%s emsg=%s", localCluster, namespace, ex.getMessage()); log.error(msg); validationFuture.completeExceptionally(new RestException(ex)); return null; }); return validationFuture; }
From source file:com.ikanow.aleph2.analytics.storm.services.RemoteStormController.java
/** * Attempts to stop the given job_name, if the job is not found it will throw an exception. * /*from w w w . jav a2 s . c o m*/ */ @Override public CompletableFuture<BasicMessageBean> stopJob(String job_name) { logger.info("Stopping job: " + job_name); CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>(); try { String actual_job_name = getJobTopologySummaryFromJobPrefix(job_name).get_name(); if (actual_job_name != null) { synchronized (client) { client.killTopology(actual_job_name); } } } catch (Exception ex) { //let die for now, usually happens when top doesn't exist logger.info(ErrorUtils.getLongForm( "Error stopping job: " + job_name + " this is typical with storm because the job may not exist that we try to kill {0}", ex)); return FutureUtils.returnError(ex); } future.complete(ErrorUtils.buildSuccessMessage(this, "stopJob", "Stopped job successfully")); return future; }
From source file:io.liveoak.container.BasicServerTest.java
@Test public void testServer() throws Exception { CompletableFuture<StompMessage> peopleCreationNotification = new CompletableFuture<>(); CompletableFuture<StompMessage> bobCreationNotification = new CompletableFuture<>(); StompClient stompClient = new StompClient(); CountDownLatch subscriptionLatch = new CountDownLatch(1); stompClient.connect("localhost", 8080, (client) -> { stompClient.subscribe("/testApp/memory/people/*", (subscription) -> { subscription.onMessage((msg) -> { System.err.println("******* MESSAGE: " + msg); if (msg.headers().get("location").equals("/testApp/memory/people")) { peopleCreationNotification.complete(msg); } else { bobCreationNotification.complete(msg); }//from w w w .j av a 2s .c om }); subscription.onReceipt(() -> { subscriptionLatch.countDown(); }); }); }); subscriptionLatch.await(); Header header = new BasicHeader("Accept", "application/json"); HttpGet getRequest = null; HttpPost postRequest = null; HttpPut putRequest = null; CloseableHttpResponse response = null; System.err.println("TEST #1"); // Root object should exist. getRequest = new HttpGet("http://localhost:8080/testApp/memory"); getRequest.addHeader(header); response = this.httpClient.execute(getRequest); // { // "id" : "memory", // "self" : { // "href" : "/memory" // }, // "content" : [ ] // } assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); ResourceState state = decode(response); assertThat(state).isNotNull(); assertThat(state.members().size()).isEqualTo(0); response.close(); System.err.println("TEST #2"); // people collection should not exist. getRequest = new HttpGet("http://localhost:8080/testApp/memory/people"); response = this.httpClient.execute(getRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404); response.close(); System.err.println("TEST #3"); // create people collection with direct PUT putRequest = new HttpPut("http://localhost:8080/testApp/memory/people"); putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }")); putRequest.setHeader("Content-Type", "application/json"); response = this.httpClient.execute(putRequest); System.err.println("response: " + response); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201); response.close(); System.err.println("TEST #4"); // people collection should exist now. getRequest = new HttpGet("http://localhost:8080/testApp/memory/people"); response = this.httpClient.execute(getRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); response.close(); assertThat(peopleCreationNotification.getNow(null)).isNull(); System.err.println("TEST #5"); // people collection should be enumerable from the root getRequest = new HttpGet("http://localhost:8080/testApp/memory?expand=members"); getRequest.addHeader(header); response = this.httpClient.execute(getRequest); // { // "id" : "memory", // "self" : { // "href" : "/memory" // }, // "content" : [ { // "id" : "people", // "self" : { // "href" : "/memory/people" // }, // "content" : [ ] // } ] // } assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); state = decode(response); assertThat(state).isNotNull(); assertThat(state.members().size()).isEqualTo(1); ResourceState memoryCollection = state.members().get(0); assertThat(memoryCollection.id()).isEqualTo("people"); assertThat(memoryCollection.uri().toString()).isEqualTo("/testApp/memory/people"); System.err.println("TEST #6"); // Post a person postRequest = new HttpPost("http://localhost:8080/testApp/memory/people"); postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }")); postRequest.setHeader("Content-Type", "application/json"); response = httpClient.execute(postRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201); state = decode(response); assertThat(state).isNotNull(); assertThat(state).isInstanceOf(ResourceState.class); assertThat(state.id()).isNotNull(); assertThat(state.getProperty("name")).isEqualTo("bob"); // check STOMP System.err.println("TEST #STOMP"); StompMessage obj = bobCreationNotification.get(30000, TimeUnit.SECONDS); assertThat(obj).isNotNull(); ResourceState bobObjState = decode(obj.content()); assertThat(bobObjState.getProperty("name")).isEqualTo("bob"); assertThat(state.getProperty(LiveOak.ID)).isEqualTo(bobObjState.getProperty(LiveOak.ID)); response.close(); }
From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java
private int getBestNumber(String codeToExecute, boolean showResult, Message message) { for (int value = 0; value < 10;) { Double numberOfExecution = Math.pow(10, value); CompletableFuture<Boolean> keepLooking = new CompletableFuture<>(); Long startTime = System.nanoTime(); IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> { SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel, new Message(new Header(message.type(), message.getHeader().getSession())), 0); if (!showResult) { simpleEvaluationObject.noResult(); }//from w w w . j a v a 2 s . com kernel.executeCode(codeToExecute, simpleEvaluationObject); if (numberOfExecution.intValue() - 1 == indexOfExecution) { if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) { keepLooking.complete(false); } else { keepLooking.complete(true); } } }); try { if (keepLooking.get()) { value++; } else { return numberOfExecution.intValue(); } } catch (ExecutionException | InterruptedException e) { throw new IllegalStateException("Cannot create best number of execution."); } } throw new IllegalStateException("Cannot create best number of execution."); }
From source file:io.pravega.client.stream.mock.MockController.java
private boolean createSegment(String name, PravegaNodeUri uri) { CompletableFuture<Boolean> result = new CompletableFuture<>(); FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override/* w ww. j av a 2 s. c om*/ public void connectionDropped() { result.completeExceptionally(new ConnectionClosedException()); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally(new NotImplementedException()); } @Override public void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) { result.complete(false); } @Override public void segmentCreated(WireCommands.SegmentCreated segmentCreated) { result.complete(true); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; CreateSegment command = new WireCommands.CreateSegment(idGenerator.get(), name, WireCommands.CreateSegment.NO_SCALE, 0); sendRequestOverNewConnection(command, replyProcessor, result); return getAndHandleExceptions(result, RuntimeException::new); }
From source file:org.apache.distributedlog.impl.subscription.ZKSubscriptionsStore.java
private void getLastCommitPositions(final CompletableFuture<Map<String, DLSN>> result, List<String> subscribers) { List<CompletableFuture<Pair<String, DLSN>>> futures = new ArrayList<CompletableFuture<Pair<String, DLSN>>>( subscribers.size());// ww w . ja v a 2s .c o m for (String s : subscribers) { final String subscriber = s; CompletableFuture<Pair<String, DLSN>> future = // Get the last commit position from zookeeper getSubscriber(subscriber).getLastCommitPositionFromZK() .thenApply(dlsn -> Pair.of(subscriber, dlsn)); futures.add(future); } FutureUtils.collect(futures).thenAccept((subscriptions) -> { Map<String, DLSN> subscriptionMap = new HashMap<String, DLSN>(); for (Pair<String, DLSN> pair : subscriptions) { subscriptionMap.put(pair.getLeft(), pair.getRight()); } result.complete(subscriptionMap); }); }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> updateActiveTx(int epoch, UUID txId, Data<Integer> data) { Preconditions.checkNotNull(data);//from www . j a v a 2s .co m CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (txnsLock) { if (!activeTxns.containsKey(txId.toString())) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Transaction: " + txId.toString())); } else { activeTxns.compute(txId.toString(), (x, y) -> new Data<>(data.getData(), y.getVersion() + 1)); result.complete(null); } } return result; }
From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java
@Override public CompletableFuture<MeterStoreResult> deleteMeter(Meter meter) { // Init steps CompletableFuture<MeterStoreResult> future = new CompletableFuture<>(); MeterKey key = MeterKey.key(meter.deviceId(), meter.id()); // Store the future related to the operation futures.put(key, future);/*www. ja v a2s . c o m*/ // Create the meter data MeterData data = new MeterData(meter, null, local); // Update the state of the meter. It will be pruned by observing // that it has been removed from the dataplane. try { // If it does not exist in the system if (meters.computeIfPresent(key, (k, v) -> data) == null) { // Complete immediately future.complete(MeterStoreResult.success()); } } catch (StorageException e) { futures.remove(key); future.completeExceptionally(e); } // Done, return the future return future; }
From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java
CompletableFuture<Pair<HRegionInfo, ServerName>> getRegion(byte[] regionName) { if (regionName == null) { return failedFuture(new IllegalArgumentException("Pass region name")); }//from www. j a va 2s . c om CompletableFuture<Pair<HRegionInfo, ServerName>> future = new CompletableFuture<>(); AsyncMetaTableAccessor.getRegion(metaTable, regionName).whenComplete((p, err) -> { if (err != null) { future.completeExceptionally(err); } else if (p != null) { future.complete(p); } else { metaTable.scanAll(new Scan().setReadType(ReadType.PREAD).addFamily(HConstants.CATALOG_FAMILY)) .whenComplete((results, err2) -> { if (err2 != null) { future.completeExceptionally(err2); return; } String encodedName = Bytes.toString(regionName); if (results != null && !results.isEmpty()) { for (Result r : results) { if (r.isEmpty() || MetaTableAccessor.getHRegionInfo(r) == null) continue; RegionLocations rl = MetaTableAccessor.getRegionLocations(r); if (rl != null) { for (HRegionLocation h : rl.getRegionLocations()) { if (h != null && encodedName.equals(h.getRegionInfo().getEncodedName())) { future.complete(new Pair<>(h.getRegionInfo(), h.getServerName())); return; } } } } } future.complete(null); }); } }); return future; }