Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:opensnap.repository.MongoRepository.java

public CompletableFuture<List<T>> getSome(String key, Object value) {
    CompletableFuture<List<T>> future = new CompletableFuture<>();
    List<T> list = new ArrayList<>();

    collection.find(new Document(key, value)).forEach((document) -> {
        try {//from www.j a  va 2s  .c om
            list.add(mapper.readValue(toJson(document), clazz));
        } catch (IOException e) {
            logger.error("Error while parsing document in getSome() : " + document.toString(), e);
        }
    }).register((result, e) -> future.complete(list));
    ;
    return future;
}

From source file:com.devicehive.service.DeviceCommandService.java

public CompletableFuture<List<DeviceCommand>> find(Collection<String> guids, Collection<String> names,
        Date timestampSt, Date timestampEnd, String status) {
    List<CompletableFuture<Response>> futures = guids.stream().map(guid -> {
        CommandSearchRequest searchRequest = new CommandSearchRequest();
        searchRequest.setGuid(guid);/*from w w  w  . j av  a2  s  .  c o  m*/
        if (names != null) {
            searchRequest.setNames(new HashSet<>(names));
        }
        searchRequest.setTimestampStart(timestampSt);
        searchRequest.setTimestampEnd(timestampEnd);
        searchRequest.setStatus(status);
        return searchRequest;
    }).map(searchRequest -> {
        CompletableFuture<Response> future = new CompletableFuture<>();
        rpcClient.call(
                Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
                new ResponseConsumer(future));
        return future;
    }).collect(Collectors.toList());

    // List<CompletableFuture<Response>> => CompletableFuture<List<DeviceCommand>>
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream().map(CompletableFuture::join) // List<CompletableFuture<Response>> => CompletableFuture<List<Response>>
                    .map(r -> ((CommandSearchResponse) r.getBody()).getCommands()) // CompletableFuture<List<Response>> => CompletableFuture<List<List<DeviceCommand>>>
                    .flatMap(Collection::stream) // CompletableFuture<List<List<DeviceCommand>>> => CompletableFuture<List<DeviceCommand>>
                    .collect(Collectors.toList()));
}

From source file:org.apache.pulsar.compaction.TwoPhaseCompactor.java

private CompletableFuture<PhaseOneResult> phaseOne(RawReader reader) {
    Map<String, MessageId> latestForKey = new HashMap<>();
    CompletableFuture<PhaseOneResult> loopPromise = new CompletableFuture<>();

    reader.getLastMessageIdAsync().whenComplete((lastMessageId, exception) -> {
        if (exception != null) {
            loopPromise.completeExceptionally(exception);
        } else {/*  w w  w  .  j av  a 2 s .c  om*/
            log.info("Commencing phase one of compaction for {}, reading to {}", reader.getTopic(),
                    lastMessageId);
            phaseOneLoop(reader, Optional.empty(), Optional.empty(), lastMessageId, latestForKey, loopPromise);
        }
    });
    return loopPromise;
}

From source file:com.microsoft.azure.servicebus.samples.messagebrowse.MessageBrowse.java

CompletableFuture peekMessagesAsync(IMessageReceiver receiver) {

    CompletableFuture currentTask = new CompletableFuture();
    try {/*from   w ww .  jav  a 2  s. co  m*/
        CompletableFuture.runAsync(() -> {
            while (!currentTask.isCancelled()) {
                try {
                    IMessage message = receiver.peek();
                    if (message != null) {
                        // receives message is passed to callback
                        if (message.getLabel() != null && message.getContentType() != null
                                && message.getLabel().contentEquals("Scientist")
                                && message.getContentType().contentEquals("application/json")) {

                            byte[] body = message.getBody();
                            Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                            System.out.printf(
                                    "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,"
                                            + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                                    message.getMessageId(), message.getSequenceNumber(),
                                    message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(),
                                    message.getContentType(),
                                    scientist != null ? scientist.get("firstName") : "",
                                    scientist != null ? scientist.get("name") : "");
                        } else {
                            currentTask.complete(null);
                        }
                    }
                } catch (Exception e) {
                    currentTask.completeExceptionally(e);
                }
            }
            if (!currentTask.isCancelled()) {
                currentTask.complete(null);
            }
        });
        return currentTask;
    } catch (Exception e) {
        currentTask.completeExceptionally(e);
    }
    return currentTask;
}

From source file:org.apache.bookkeeper.meta.MockLedgerManager.java

@Override
public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(long ledgerId,
        LedgerMetadata metadata) {/*w  ww. j ava 2 s  . c  o m*/
    CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>();
    executor.submit(() -> {
        if (metadataMap.containsKey(ledgerId)) {
            executeCallback(() -> promise.completeExceptionally(new BKException.BKLedgerExistException()));
        } else {
            try {
                metadataMap.put(ledgerId, Pair.of(new LongVersion(0L), serDe.serialize(metadata)));
                Versioned<LedgerMetadata> readBack = readMetadata(ledgerId);
                executeCallback(() -> promise.complete(readBack));
            } catch (Exception e) {
                LOG.error("Error reading back written metadata", e);
                executeCallback(() -> promise.completeExceptionally(new BKException.MetaStoreException()));
            }
        }
    });
    return promise;
}

From source file:msuresh.raftdistdb.TestAtomix.java

public static void createCluster(String test, int nodesInCluster)
        throws InterruptedException, ExecutionException {
    InitPortNumber();//from ww w .  j a va 2 s  . com
    try {
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < nodesInCluster; i++) {
            Address addr = new Address("localhost", portId++);
            members.add(addr);
        }
        CompletableFuture<Integer> future = new CompletableFuture<>();
        Map atomixList;
        atomixList = new HashMap();
        for (Address a : members) {
            ServerSetup s = new ServerSetup(members, a, atomixList, future);
            s.start();
        }
        future.get();
        UpdatePortNumber();

        if (test.compareTo("leaderFailure") == 0) {
            for (Object s : atomixList.keySet()) {
                LeaderReelection l = new LeaderReelection((Address) s, (CopycatServer) atomixList.get(s), true);
                l.start();
            }
            Thread.sleep(20000);
            //                for(Object s : atomixList.keySet()){
            //                    CopycatServer cs = (CopycatServer)atomixList.get(s);
            //                    while(cs.isOpen())
            //                        Thread.sleep(1000);
            //                    System.out.println("printing" + cs.toString());
            //                }
            System.out.println(
                    "Leader Reelection test is done. Program might not close properly due to a bug in Atomix. Follow manual instructions to close the process and sockets.");
        } else if (test.compareTo("replicationTest") == 0) {
            CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
            client.open().join();
            System.out.println("Adding a testkey with testval to the cluster ..");
            client.submit(new PutCommand("testkey1", "testval")).get();
            List<LeaderReelection> reelectionList = new ArrayList<>();
            System.out.println("Crashing leader to trigger a reelection .. ");
            for (Object s : atomixList.keySet()) {

                LeaderReelection l = new LeaderReelection((Address) s, (CopycatServer) atomixList.get(s),
                        false);
                l.start();
                reelectionList.add(l);
            }

            //                for(LeaderReelection l : reelectionList){
            //                    l.future.get();
            //                    
            //                }
            //                client = CopycatClient.builder(members)
            //                        .withTransport(new NettyTransport())
            //                        .build();
            //                client.open().join();
            System.out.println(" Polling the cluster for testkey ..");
            Object str = client.submit(new GetQuery("testkey1")).get();
            System.out.println("The cluster returned (which should be 'testval'):" + (String) str);
            System.out.println("closing open servers..");
            for (Object s : atomixList.keySet()) {
                CopycatServer cs = (CopycatServer) atomixList.get(s);

                if (cs.isOpen())
                    cs.close();

            }
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

}

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  ww  w.  j  ava  2s.  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;
}

From source file:com.devicehive.service.DeviceNotificationService.java

@SuppressWarnings("unchecked")
public CompletableFuture<List<DeviceNotification>> find(Set<String> guids, Set<String> names, Date timestampSt,
        Date timestampEnd) {//from w ww . j a  va 2s .  co m
    List<CompletableFuture<Response>> futures = guids.stream().map(guid -> {
        NotificationSearchRequest searchRequest = new NotificationSearchRequest();
        searchRequest.setGuid(guid);
        searchRequest.setNames(names);
        searchRequest.setTimestampStart(timestampSt);
        searchRequest.setTimestampEnd(timestampEnd);
        return searchRequest;
    }).map(searchRequest -> {
        CompletableFuture<Response> future = new CompletableFuture<>();
        rpcClient.call(
                Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
                new ResponseConsumer(future));
        return future;
    }).collect(Collectors.toList());

    // List<CompletableFuture<Response>> => CompletableFuture<List<DeviceNotification>>
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream().map(CompletableFuture::join) // List<CompletableFuture<Response>> => CompletableFuture<List<Response>>
                    .map(r -> r.getBody().cast(NotificationSearchResponse.class).getNotifications()) // CompletableFuture<List<Response>> => CompletableFuture<List<List<DeviceNotification>>>
                    .flatMap(Collection::stream) // CompletableFuture<List<List<DeviceNotification>>> => CompletableFuture<List<DeviceNotification>>
                    .collect(Collectors.toList()));
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

@Override
public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) {

    CompletableFuture<HttpResponse> promise = new CompletableFuture<>();
    URI uri;// w  w w  .  ja v a2 s  .  c om
    HttpRequestBase hcRequest;
    try {
        if (request.getMethod() == HttpMethod.POST) {
            uri = new URIBuilder(request.getUrl().toASCIIString()).build();
            hcRequest = new HttpPost(uri);
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            request.getQueryParams().entrySet()
                    .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue())));
            ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters));

        } else {
            uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams()
                    .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
                    .collect(Collectors.toList())).build();
            hcRequest = new HttpGet(uri);
        }
    } catch (URISyntaxException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue()));

    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

        hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() {

            public void completed(final HttpResponse hcResponse) {
                int statusCode = hcResponse.getStatusLine().getStatusCode();
                logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request);
                promise.complete(hcResponse);
            }

            public void failed(final Exception ex) {
                logger.debug("HTTP REQ FAILED " + request);
                logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage());
                promise.completeExceptionally(ex);
            }

            public void cancelled() {
                promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request));
            }
        });
        return null;
    });

    return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> {
        try {
            return hcResp.getEntity().getContent();
        } catch (IOException e) {
            throw new RuntimeException("Cannot read content", e);
        }
    }));

}

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

public AsyncSingleRequestRpcRetryingCaller(HashedWheelTimer retryTimer, AsyncConnectionImpl conn,
        TableName tableName, byte[] row, Callable<T> callable, long pauseNs, int maxRetries,
        long operationTimeoutNs, long rpcTimeoutNs, int startLogErrorsCnt) {
    this.retryTimer = retryTimer;
    this.conn = conn;
    this.tableName = tableName;
    this.row = row;
    this.callable = callable;
    this.pauseNs = pauseNs;
    this.maxAttempts = retries2Attempts(maxRetries);
    this.operationTimeoutNs = operationTimeoutNs;
    this.rpcTimeoutNs = rpcTimeoutNs;
    this.startLogErrorsCnt = startLogErrorsCnt;
    this.future = new CompletableFuture<>();
    this.controller = conn.rpcControllerFactory.newController();
    this.exceptions = new ArrayList<>();
    this.startNs = System.nanoTime();
}