List of usage examples for java.util.concurrent CompletableFuture complete
public boolean complete(T value)
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> updateMarkerData(int segmentNumber, Data<Integer> data) { CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (markersLock) { if (!markers.containsKey(segmentNumber)) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Segment number: " + segmentNumber)); } else {//from www . java 2s . c om markers.compute(segmentNumber, (x, y) -> { if (y.getVersion().equals(data.getVersion())) { result.complete(null); return new Data<>(Arrays.copyOf(data.getData(), data.getData().length), data.getVersion() + 1); } else { result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, "Stream: " + getName() + " Segment number: " + segmentNumber)); return y; } }); } } return result; }
From source file:net.data.technology.jraft.extensions.http.HttpRpcClient.java
@Override public CompletableFuture<RaftResponseMessage> send(RaftRequestMessage request) { CompletableFuture<RaftResponseMessage> future = new CompletableFuture<RaftResponseMessage>(); String payload = this.gson.toJson(request); HttpPost postRequest = new HttpPost(this.serverUrl); postRequest.setEntity(new StringEntity(payload, StandardCharsets.UTF_8)); this.httpClient.execute(postRequest, new FutureCallback<HttpResponse>() { @Override/*from www . j a v a2 s. c o m*/ public void completed(HttpResponse result) { if (result.getStatusLine().getStatusCode() != 200) { logger.info("receive an response error code " + String.valueOf(result.getStatusLine().getStatusCode()) + " from server"); future.completeExceptionally(new IOException("Service Error")); } try { InputStreamReader reader = new InputStreamReader(result.getEntity().getContent()); RaftResponseMessage response = gson.fromJson(reader, RaftResponseMessage.class); future.complete(response); } catch (Throwable error) { logger.info("fails to parse the response from server due to errors", error); future.completeExceptionally(error); } } @Override public void failed(Exception ex) { future.completeExceptionally(ex); } @Override public void cancelled() { future.completeExceptionally(new IOException("request cancelled")); } }); return future; }
From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java
@Override public CompletableFuture<InstanceCommunication.MetricsData> getMetrics(int instanceId) { CompletableFuture<InstanceCommunication.MetricsData> retval = new CompletableFuture<>(); if (stub == null) { retval.completeExceptionally(new RuntimeException("Not alive")); return retval; }// ww w. ja v a 2s .co m ListenableFuture<InstanceCommunication.MetricsData> response = stub .withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS).getMetrics(Empty.newBuilder().build()); Futures.addCallback(response, new FutureCallback<InstanceCommunication.MetricsData>() { @Override public void onFailure(Throwable throwable) { retval.completeExceptionally(throwable); } @Override public void onSuccess(InstanceCommunication.MetricsData t) { retval.complete(t); } }); return retval; }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Unsubscribes from a topic on the given connection, but does not alter the subscriber list. * * @param client The client connection/*from www. ja va 2 s . co m*/ * @param topic The topic to unsubscribe from * @return Completes with true if successful. Completes with false if no broker connection is established. * Exceptionally otherwise. */ protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) { logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { if (client.isConnected()) { client.unsubscribe(topic, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error unsubscribing topic from broker", e); future.completeExceptionally(e); } return future; }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> setSegmentTable(Data<Integer> data) { Preconditions.checkNotNull(data);/*from w w w . ja va 2 s . c om*/ Preconditions.checkNotNull(data.getData()); CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (lock) { if (segmentTable == null) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Segment table for stream: " + getName())); } else if (segmentTable.getVersion().equals(data.getVersion())) { segmentTable = new Data<>(Arrays.copyOf(data.getData(), data.getData().length), data.getVersion() + 1); result.complete(null); } else { result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, "Segment table for stream: " + getName())); } } return result; }
From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java
public String editDatabaseConnection(String database) { CompletableFuture<String> future = new CompletableFuture<>(); spoonSupplier.get().getShell().getDisplay().asyncExec(() -> { DatabaseMeta databaseMeta = getDatabase(database); String originalName = databaseMeta.getName(); DatabaseDialog databaseDialog = new DatabaseDialog(spoonSupplier.get().getShell(), databaseMeta); databaseDialog.open();//from w w w .jav a 2 s.c o m if (!isDatabaseWithNameExist(databaseMeta, false)) { save(); future.complete(databaseMeta.getName()); } else { DatabaseDialog.showDatabaseExistsDialog(spoonSupplier.get().getShell(), databaseMeta); databaseMeta.setName(originalName); databaseMeta.setDisplayName(originalName); future.complete(originalName); } }); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name", future.get()); return jsonObject.toJSONString(); } catch (Exception e) { jsonObject.put("name", "None"); return jsonObject.toJSONString(); } }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> updateIndexTable(Data<Integer> updated) { Preconditions.checkNotNull(updated); Preconditions.checkNotNull(updated.getData()); final CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (lock) { if (indexTable == null) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Indextable for stream: " + getName())); } else if (indexTable.getVersion().equals(updated.getVersion())) { indexTable = new Data<>(Arrays.copyOf(updated.getData(), updated.getData().length), updated.getVersion() + 1); result.complete(null); } else {/*from www . j av a 2 s. c om*/ result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, "Indextable for stream: " + getName())); } } return result; }
From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java
protected MagicCommandOutput timeIt(TimeItOption timeItOption, String codeToExecute, Message message, int executionCount, boolean showResult) { String output = "%s %s per loop (mean std. dev. of %d run, %d loop each)"; if (timeItOption.getNumber() < 0) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Number of execution must be bigger then 0"); }/*from www . j a va 2s.c o m*/ int number = timeItOption.getNumber() == 0 ? getBestNumber(codeToExecute, showResult, message) : timeItOption.getNumber(); if (timeItOption.getRepeat() == 0) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Repeat value must be bigger then 0"); } SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount); seo.noResult(); TryResult either = kernel.executeCode(codeToExecute, seo); try { if (either.isError()) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Please correct your statement"); } List<Long> allRuns = new ArrayList<>(); List<Long> timings = new ArrayList<>(); CompletableFuture<Boolean> isReady = new CompletableFuture<>(); IntStream.range(0, timeItOption.getRepeat()).forEach(repeatIter -> { IntStream.range(0, number).forEach(numberIter -> { SimpleEvaluationObject seo2 = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount); seo2.noResult(); Long startOfEvaluationInNanoseconds = System.nanoTime(); TryResult result = kernel.executeCode(codeToExecute, seo2); Long endOfEvaluationInNanoseconds = System.nanoTime(); allRuns.add(endOfEvaluationInNanoseconds - startOfEvaluationInNanoseconds); if (repeatIter == timeItOption.getRepeat() - 1 && numberIter == number - 1) { isReady.complete(true); } }); }); if (isReady.get()) { allRuns.forEach(run -> timings.add(run / number)); //calculating average long average = timings.stream().reduce((aLong, aLong2) -> aLong + aLong2).orElse(0L) / timings.size(); double stdev = Math.pow( timings.stream().map(currentValue -> Math.pow(currentValue - average, 2)) .reduce((aDouble, aDouble2) -> aDouble + aDouble2).orElse(0.0) / timings.size(), 0.5); if (timeItOption.getQuietMode()) { output = ""; } else { output = String.format(output, format(average), format((long) stdev), timeItOption.getRepeat(), number); } return new MagicCommandOutput(MagicCommandOutput.Status.OK, output); } } catch (InterruptedException | ExecutionException e) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem with " + e.getMessage()); } return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem with timeIt operations"); }
From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java
private void doWithdraw(String path, CompletableFuture<Void> future) { if (activeTopics.contains(path)) { future.completeExceptionally(/* ww w. ja va 2 s . c o m*/ new CancellationException(String.format("%s is now a active topic", path))); } try { leaderMap.computeIf(path, localNodeId::equals, (topic, leader) -> null); candidateMap.computeIf(path, candidates -> candidates != null && candidates.contains(localNodeId), (topic, candidates) -> candidates.stream().filter(nodeId -> !localNodeId.equals(nodeId)) .collect(Collectors.toList())); future.complete(null); } catch (Exception e) { log.debug("Failed to verify (and clear) any lock this node might be holding for {}", path, e); retryWithdraw(path, future); } }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<CreateStreamResponse> checkStreamExists(StreamConfiguration configuration, long timestamp) { CompletableFuture<CreateStreamResponse> result = new CompletableFuture<>(); final long time; final StreamConfiguration config; final Data<Integer> currentState; synchronized (lock) { time = creationTime.get();//w w w .j a v a 2 s . co m config = this.configuration; currentState = this.state; } if (time != Long.MIN_VALUE) { if (config != null) { handleStreamMetadataExists(timestamp, result, time, config, currentState); } else { result.complete( new CreateStreamResponse(CreateStreamResponse.CreateStatus.NEW, configuration, time)); } } else { result.complete( new CreateStreamResponse(CreateStreamResponse.CreateStatus.NEW, configuration, timestamp)); } return result; }