Example usage for java.util.concurrent CompletableFuture complete

List of usage examples for java.util.concurrent CompletableFuture complete

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture complete.

Prototype

public boolean complete(T value) 

Source Link

Document

If not already completed, sets the value returned by #get() and related methods to the given value.

Usage

From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java

public CompletableFuture<InstanceCommunication.HealthCheckResult> healthCheck() {
    CompletableFuture<InstanceCommunication.HealthCheckResult> retval = new CompletableFuture<>();
    if (stub == null) {
        retval.completeExceptionally(new RuntimeException("Not alive"));
        return retval;
    }/*from  w w w. j  ava 2  s. co m*/
    ListenableFuture<InstanceCommunication.HealthCheckResult> response = stub
            .withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS).healthCheck(Empty.newBuilder().build());
    Futures.addCallback(response, new FutureCallback<InstanceCommunication.HealthCheckResult>() {
        @Override
        public void onFailure(Throwable throwable) {
            retval.completeExceptionally(throwable);
        }

        @Override
        public void onSuccess(InstanceCommunication.HealthCheckResult t) {
            retval.complete(t);
        }
    });
    return retval;
}

From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java

@Override
public CompletableFuture<InstanceCommunication.MetricsData> getAndResetMetrics() {
    CompletableFuture<InstanceCommunication.MetricsData> retval = new CompletableFuture<>();
    if (stub == null) {
        retval.completeExceptionally(new RuntimeException("Not alive"));
        return retval;
    }//from   w  w w. j  a  v  a 2 s  .c o m
    ListenableFuture<InstanceCommunication.MetricsData> response = stub
            .withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS)
            .getAndResetMetrics(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:com.vmware.loginsightapi.LogInsightClient.java

/**
 * Ingest messages to loginsight//from  ww w  . j a  va2s .  c  o  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:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

private <PREQ, PRESP, RESP> CompletableFuture<RESP> call(HBaseRpcController controller,
        MasterService.Interface stub, PREQ preq, MasterRpcCall<PRESP, PREQ> rpcCall,
        Converter<RESP, PRESP> respConverter) {
    CompletableFuture<RESP> future = new CompletableFuture<>();
    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {

        @Override/*w ww.ja  v a2 s  .  c  om*/
        public void run(PRESP resp) {
            if (controller.failed()) {
                future.completeExceptionally(controller.getFailed());
            } else {
                try {
                    future.complete(respConverter.convert(resp));
                } catch (IOException e) {
                    future.completeExceptionally(e);
                }
            }
        }
    });
    return future;
}

From source file:com.vmware.loginsightapi.LogInsightClient.java

/**
 * Performs message query. Returns a CompletableFuture for
 * MessageQueryResponse/*  w  ww  . j a  v  a 2  s.c  o  m*/
 * 
 * @param apiUrl
 *            relative url of the API
 * @return MessageQueryResponse CompletableFuture object
 * @throws LogInsightApiException
 *             Exception
 */
public CompletableFuture<MessageQueryResponse> messageQuery(String apiUrl) {
    HttpGet request = null;
    CompletableFuture<MessageQueryResponse> completableFuture = new CompletableFuture<MessageQueryResponse>();
    try {
        request = getHttpRequest(apiUrl, false);
        asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse httpResponse) {

                try {
                    InputStream responseBody = httpResponse.getEntity().getContent();
                    String responseString = IOUtils.toString(responseBody, "UTF-8");
                    logger.warn("Response: " + responseString);
                    completableFuture.complete(MessageQueryResponse.fromJsonString(responseString));
                } catch (IOException e) {
                    e.printStackTrace();
                    completableFuture.completeExceptionally(e);
                }
            }

            @Override
            public void failed(Exception ex) {
                completableFuture.completeExceptionally(new LogInsightApiException("Failed message Query", ex));
            }

            @Override
            public void cancelled() {
                completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query"));
            }

        });
    } catch (Exception ie) {
        completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie));
    }
    return completableFuture;
}

From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public String createConnection() {
    CompletableFuture<String> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        DatabaseDialog databaseDialog = new DatabaseDialog(spoonSupplier.get().getShell(), new DatabaseMeta());
        databaseDialog.open();//from  w ww .j  a  v a  2 s. com
        DatabaseMeta databaseMeta = databaseDialog.getDatabaseMeta();
        if (databaseMeta != null) {
            if (!isDatabaseWithNameExist(databaseMeta, true)) {
                addDatabase(databaseMeta);
                future.complete(databaseMeta.getName());
            } else {
                DatabaseDialog.showDatabaseExistsDialog(spoonSupplier.get().getShell(), databaseMeta);
            }
        }
        future.complete("None");
    });
    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:com.vmware.loginsightapi.LogInsightClient.java

/**
 * Performs aggregate query. Accepts callback
 * //  w  w w . j av a 2 s  . c  o m
 * @param apiUrl
 *            relative url of the API
 * @return AggregateResponse CompletableFuture
 * 
 */
public CompletableFuture<AggregateResponse> aggregateQuery(String apiUrl) {
    HttpGet request = null;
    CompletableFuture<AggregateResponse> completableFuture = new CompletableFuture<AggregateResponse>();
    try {
        request = getHttpRequest(apiUrl, true);
        logger.debug("Querying " + aggregateQueryUrl() + apiUrl);
        asyncHttpClient.execute(request, 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(AggregateResponse.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("Failed message Query", ex));
            }

            @Override
            public void cancelled() {
                completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query"));
            }

        });
    } catch (Exception ie) {
        completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie));
    }
    return completableFuture;
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> updateHistoryTable(Data<Integer> updated) {
    Preconditions.checkNotNull(updated);
    Preconditions.checkNotNull(updated.getData());

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (lock) {
        if (historyTable == null) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Historytable for stream: " + getName()));
        } else {//from w  ww  . java 2s  .c  o  m
            if (historyTable.getVersion().equals(updated.getVersion())) {
                historyTable = new Data<>(Arrays.copyOf(updated.getData(), updated.getData().length),
                        updated.getVersion() + 1);
                result.complete(null);
            } else {
                result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT,
                        "Historytable for stream: " + getName()));
            }
        }
    }
    return result;
}

From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

private <PREQ, PRESP, RESP> CompletableFuture<RESP> adminCall(HBaseRpcController controller,
        AdminService.Interface stub, PREQ preq, AdminRpcCall<PRESP, PREQ> rpcCall,
        Converter<RESP, PRESP> respConverter) {

    CompletableFuture<RESP> future = new CompletableFuture<>();
    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {

        @Override//from  ww  w  .j  ava  2 s  .c om
        public void run(PRESP resp) {
            if (controller.failed()) {
                future.completeExceptionally(new IOException(controller.errorText()));
            } else {
                try {
                    future.complete(respConverter.convert(resp));
                } catch (IOException e) {
                    future.completeExceptionally(e);
                }
            }
        }
    });
    return future;
}

From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java

@Override
public CompletableFuture<byte[]> save(Node node) {
    if (!(node instanceof CodeArea)) {
        return CompletableFuture.completedFuture(new byte[0]);
    }/*from w  ww.  ja v  a2  s.  c o m*/

    String assembledCode = ((CodeArea) node).getText();

    CompletableFuture<byte[]> future = new CompletableFuture<>();

    backgroundTaskHelper.submit(new BackgroundTask(
            Message.TASK_ASSEMBLE_FILE.format(node.getProperties().get("path").toString()), true, () -> {
                if (controller instanceof KrakatauDisassemblerController) {
                    KrakatauAssemblerSettings settings = new KrakatauAssemblerSettings();
                    settings.setPythonExecutable(new File(configuration.getString(Settings.PYTHON2_KEY)));
                    settings.setProcessCreator(processController::launchProcess);

                    try {
                        TransformationResult<byte[]> result = StandardTransformers.Assemblers.KRAKATAU
                                .assemble(assembledCode, settings);
                        if (result.getTransformationData().size() == 1) {
                            future.complete(result.getTransformationData().values().iterator().next());
                        } else {
                            future.completeExceptionally(new KrakatauException(KrakatauException.Reason.UNKNOWN,
                                    result.getStdout(), result.getStderr()));
                        }
                    } catch (TransformationException e) {
                        future.completeExceptionally(e);
                    }
                } else {
                    future.complete(new byte[0]);
                }
            }));

    return future;
}