List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:com.vmware.loginsightapi.LogInsightClient.java
/** * Ingest messages to loginsight/*from w ww .j a v a 2 s .co m*/ * * @param messages * IngestionRequest object with list of messages * @return IngestionResponse CompletableFuture object * @see IngestionRequest * @see IngestionResponse */ public CompletableFuture<IngestionResponse> ingest(IngestionRequest messages) { HttpPost httpPost = null; CompletableFuture<IngestionResponse> completableFuture = new CompletableFuture<IngestionResponse>(); try { httpPost = getIngestionHttpRequest(messages); logger.info("Sending : " + messages.toJson()); asyncHttpClient.execute(httpPost, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { String responseString = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); logger.warn("Response: " + responseString); completableFuture.complete(IngestionResponse.fromJsonString(responseString)); } catch (IOException e) { e.printStackTrace(); completableFuture.completeExceptionally( new LogInsightApiException("Unable to process the query response", e)); } } @Override public void failed(Exception ex) { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", ex)); } @Override public void cancelled() { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion cancelled")); } }); } catch (Exception e) { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", e)); } return completableFuture; }
From source file:io.pravega.controller.server.SegmentHelper.java
public CompletableFuture<Void> updatePolicy(String scope, String stream, ScalingPolicy policy, int segmentNumber, HostControllerStore hostControllerStore, ConnectionFactory clientCF) { final CompletableFuture<Void> result = new CompletableFuture<>(); final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore); final WireCommandType type = WireCommandType.UPDATE_SEGMENT_POLICY; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override//from w w w .j a va2s .co m public void connectionDropped() { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void segmentPolicyUpdated(WireCommands.SegmentPolicyUpdated policyUpdated) { result.complete(null); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; Pair<Byte, Integer> extracted = extractFromPolicy(policy); WireCommands.UpdateSegmentPolicy request = new WireCommands.UpdateSegmentPolicy(idGenerator.get(), Segment.getScopedName(scope, stream, segmentNumber), extracted.getLeft(), extracted.getRight()); sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri)); return result; }
From source file:io.mindmaps.graql.GraqlShell.java
public synchronized Json getAutocompleteCandidates(String queryString, int cursorPosition) throws InterruptedException, ExecutionException, IOException { sendJson(Json.object(ACTION, ACTION_AUTOCOMPLETE, QUERY, queryString, AUTOCOMPLETE_CURSOR, cursorPosition)); Json json = autocompleteResponse.get(); autocompleteResponse = new CompletableFuture<>(); return json;//w w w. j a va2 s .c o m }
From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java
@Override public CompletableFuture<HTableDescriptor> getTableDescriptor(TableName tableName) { CompletableFuture<HTableDescriptor> future = new CompletableFuture<>(); this.<List<TableSchema>>newMasterCaller() .action((controller, stub) -> this .<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableSchema>>call( controller, stub, RequestConverter.buildGetTableDescriptorsRequest(tableName), (s, c, req, done) -> s.getTableDescriptors(c, req, done), (resp) -> resp.getTableSchemaList())) .call().whenComplete((tableSchemas, error) -> { if (error != null) { future.completeExceptionally(error); return; }//from www.j av a 2 s .c om if (!tableSchemas.isEmpty()) { future.complete(ProtobufUtil.convertToHTableDesc(tableSchemas.get(0))); } else { future.completeExceptionally(new TableNotFoundException(tableName.getNameAsString())); } }); return future; }
From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java
@Override public String createEventLogRecord(final String event) { Preconditions.checkArgument(isNotBlank(event)); final CompletableFuture<CreateEvent.Response> createEventFuture = new CompletableFuture<>(); vertx.eventBus().send(EventBusAddress.eventBusAddress(EventLogRepository.VERTICLE_ID, CreateEvent.class), CreateEvent.Request.newBuilder().setEvent(event).build(), new DeliveryOptions().setSendTimeout(2000L), responseHandler(createEventFuture, CreateEvent.Response.class)); try {/*w w w . j av a 2 s. c o m*/ final CreateEvent.Response createEventResponse = createEventFuture.get(2, TimeUnit.SECONDS); return ProtobufUtils.protobuMessageToJson(createEventResponse.getId()).toString(); } catch (final InterruptedException | ExecutionException | TimeoutException ex) { log.logp(SEVERE, getClass().getName(), "createEventLogRecord", "failed", ex); throw new RuntimeException("Failed to create event log record : " + ex.getMessage()); } }
From source file:org.apache.bookkeeper.metadata.etcd.EtcdRegistrationTest.java
private void testConcurrentRegistration(boolean readonly) throws Exception { final String bookieId; if (readonly) { bookieId = runtime.getMethodName() + "-readonly:3181"; } else {/* ww w.j a v a 2 s . c o m*/ bookieId = runtime.getMethodName() + ":3181"; } final int numBookies = 10; @Cleanup("shutdown") ExecutorService executor = Executors.newFixedThreadPool(numBookies); final CyclicBarrier startBarrier = new CyclicBarrier(numBookies); final CyclicBarrier completeBarrier = new CyclicBarrier(numBookies); final CompletableFuture<Void> doneFuture = new CompletableFuture<>(); final AtomicInteger numSuccesses = new AtomicInteger(0); final AtomicInteger numFailures = new AtomicInteger(0); for (int i = 0; i < numBookies; i++) { executor.submit(() -> { try (EtcdRegistrationManager regMgr = new EtcdRegistrationManager(newEtcdClient(), scope, 1)) { try { startBarrier.await(); regMgr.registerBookie(bookieId, readonly); numSuccesses.incrementAndGet(); } catch (InterruptedException e) { log.warn("Interrupted at waiting for the other threads to start", e); } catch (BrokenBarrierException e) { log.warn("Start barrier is broken", e); } catch (BookieException e) { numFailures.incrementAndGet(); } try { completeBarrier.await(); } catch (InterruptedException e) { log.warn("Interrupted at waiting for the other threads to complete", e); } catch (BrokenBarrierException e) { log.warn("Complete barrier is broken", e); } FutureUtils.complete(doneFuture, null); } }); } doneFuture.join(); assertEquals(1, numSuccesses.get()); assertEquals(numBookies - 1, numFailures.get()); }
From source file:org.apache.pulsar.broker.web.PulsarWebResource.java
protected static CompletableFuture<ClusterData> getClusterDataIfDifferentCluster(PulsarService pulsar, String cluster, String clientAppId) { CompletableFuture<ClusterData> clusterDataFuture = new CompletableFuture<>(); if (!isValidCluster(pulsar, cluster)) { try {//w ww .j a va 2s .co m // this code should only happen with a v1 namespace format prop/cluster/namespaces if (!pulsar.getConfiguration().getClusterName().equals(cluster)) { // redirect to the cluster requested pulsar.getConfigurationCache().clustersCache().getAsync(path("clusters", cluster)) .thenAccept(clusterDataResult -> { if (clusterDataResult.isPresent()) { clusterDataFuture.complete(clusterDataResult.get()); } else { log.warn("[{}] Cluster does not exist: requested={}", clientAppId, cluster); clusterDataFuture.completeExceptionally(new RestException(Status.NOT_FOUND, "Cluster does not exist: cluster=" + cluster)); } }).exceptionally(ex -> { clusterDataFuture.completeExceptionally(ex); return null; }); } else { clusterDataFuture.complete(null); } } catch (Exception e) { clusterDataFuture.completeExceptionally(e); } } else { clusterDataFuture.complete(null); } return clusterDataFuture; }
From source file:io.pravega.client.stream.mock.MockController.java
private CompletableFuture<Void> createSegmentTx(UUID txId, Segment segment) { CompletableFuture<Void> result = new CompletableFuture<>(); FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override/*w w w . jav a 2 s .c om*/ public void connectionDropped() { result.completeExceptionally(new ConnectionClosedException()); } @Override public void wrongHost(WrongHost wrongHost) { result.completeExceptionally(new NotImplementedException()); } @Override public void transactionCreated(TransactionCreated transactionCreated) { result.complete(null); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; sendRequestOverNewConnection(new CreateTransaction(idGenerator.get(), segment.getScopedName(), txId), replyProcessor, result); return result; }
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
@Override protected CompletableFuture<Message<T>> internalReceiveAsync() { CompletableFuture<Message<T>> result = new CompletableFuture<>(); Message<T> message = null;//from ww w .j av a 2 s . com try { lock.writeLock().lock(); message = incomingMessages.poll(0, TimeUnit.MILLISECONDS); if (message == null) { pendingReceives.add(result); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); result.completeExceptionally(e); } finally { lock.writeLock().unlock(); } if (message != null) { trackMessage(message); Message<T> interceptMsg = beforeConsume(message); messageProcessed(interceptMsg); result.complete(interceptMsg); } return result; }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> deleteEpochNode(int epoch) { CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (txnsLock) { if (epochTxnMap.getOrDefault(epoch, Collections.emptySet()).isEmpty()) { epochTxnMap.remove(epoch);/*from w ww . j a v a2 s. co m*/ result.complete(null); } else { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS, "Stream: " + getName() + " Epoch: " + epoch)); } } return result; }