Example usage for java.util.concurrent CompletableFuture whenComplete

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

Introduction

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

Prototype

public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 

Source Link

Usage

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

private CompletableFuture<Void> waitProcedureResult(CompletableFuture<Long> procFuture) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    procFuture.whenComplete((procId, error) -> {
        if (error != null) {
            future.completeExceptionally(error);
            return;
        }/*from   ww w  .  jav a2s.c  o m*/
        getProcedureResult(procId, future);
    });
    return future;
}

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

private void scheduleTimeout(CompletableFuture<RawMessage> future) {
    Future<?> timeout = scheduler.schedule(() -> {
        future.completeExceptionally(new TimeoutException("Timeout"));
    }, 10, TimeUnit.SECONDS);/*from   w w  w.j  ava  2  s .  c  o m*/
    future.whenComplete((res, exception) -> {
        timeout.cancel(true);
    });
}

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

private void phaseTwoLoop(RawReader reader, MessageId to, Map<String, MessageId> latestForKey, LedgerHandle lh,
        Semaphore outstanding, CompletableFuture<Void> promise) {
    reader.readNextAsync().whenCompleteAsync((m, exception) -> {
        if (exception != null) {
            promise.completeExceptionally(exception);
            return;
        } else if (promise.isDone()) {
            return;
        }/* ww  w  . j  av a  2s.  c o  m*/
        MessageId id = m.getMessageId();
        Optional<RawMessage> messageToAdd = Optional.empty();
        if (RawBatchConverter.isReadableBatch(m)) {
            try {
                messageToAdd = RawBatchConverter.rebatchMessage(m,
                        (key, subid) -> latestForKey.get(key).equals(subid));
            } catch (IOException ioe) {
                log.info("Error decoding batch for message {}. Whole batch will be included in output", id,
                        ioe);
                messageToAdd = Optional.of(m);
            }
        } else {
            Pair<String, Integer> keyAndSize = extractKeyAndSize(m);
            MessageId msg;
            if (keyAndSize == null) { // pass through messages without a key
                messageToAdd = Optional.of(m);
            } else if ((msg = latestForKey.get(keyAndSize.getLeft())) != null && msg.equals(id)) { // consider message only if present into latestForKey map
                if (keyAndSize.getRight() <= 0) {
                    promise.completeExceptionally(new IllegalArgumentException(
                            "Compaction phase found empty record from sorted key-map"));
                }
                messageToAdd = Optional.of(m);
            } else {
                m.close();
                // Reached to last-id and phase-one found it deleted-message while iterating on ledger so, not
                // present under latestForKey. Complete the compaction.
                if (to.equals(id)) {
                    promise.complete(null);
                }
            }
        }

        messageToAdd.ifPresent((toAdd) -> {
            try {
                outstanding.acquire();
                CompletableFuture<Void> addFuture = addToCompactedLedger(lh, toAdd)
                        .whenComplete((res, exception2) -> {
                            outstanding.release();
                            if (exception2 != null) {
                                promise.completeExceptionally(exception2);
                            }
                        });
                if (to.equals(id)) {
                    addFuture.whenComplete((res, exception2) -> {
                        if (exception2 == null) {
                            promise.complete(null);
                        }
                    });
                }
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                promise.completeExceptionally(ie);
            }
        });
        phaseTwoLoop(reader, to, latestForKey, lh, outstanding, promise);
    }, scheduler);
}

From source file:org.apache.pulsar.io.kafka.connect.PulsarOffsetBackingStore.java

void readToEnd(CompletableFuture<Void> future) {
    synchronized (this) {
        if (outstandingReadToEnd != null) {
            outstandingReadToEnd.whenComplete((result, cause) -> {
                if (null != cause) {
                    future.completeExceptionally(cause);
                } else {
                    future.complete(result);
                }/*from   w w w  . j av a  2 s .c  o  m*/
            });
            // return if the outstanding read has been issued
            return;
        } else {
            outstandingReadToEnd = future;
            future.whenComplete((result, cause) -> {
                synchronized (PulsarOffsetBackingStore.this) {
                    outstandingReadToEnd = null;
                }
            });
        }
    }
    producer.flushAsync().whenComplete((ignored, cause) -> {
        if (null != cause) {
            future.completeExceptionally(cause);
        } else {
            checkAndReadNext(future);
        }
    });
}

From source file:org.apache.servicecomb.common.rest.AbstractRestInvocation.java

protected void executeHttpServerFilters(Response response) {
    HttpServerFilterBeforeSendResponseExecutor exec = new HttpServerFilterBeforeSendResponseExecutor(
            httpServerFilters, invocation, responseEx);
    CompletableFuture<Void> future = exec.run();
    future.whenComplete((v, e) -> {
        if (invocation != null) {
            invocation.getInvocationStageTrace().finishServerFiltersResponse();
        }//w w  w  . jav a 2  s .c o  m

        onExecuteHttpServerFiltersFinish(response, e);
    });
}

From source file:org.apache.servicecomb.demo.springmvc.client.TestDownload.java

private <T> CompletableFuture<T> checkFuture(CompletableFuture<T> future) {
    Error error = new Error();
    future.whenComplete((result, e) -> {
        Object value = result;/*from  ww w  . jav a2 s . c  om*/
        if (File.class.isInstance(value)) {
            File file = (File) value;
            value = readFileToString(file);
            file.delete();
        } else if (byte[].class.isInstance(value)) {
            value = new String((byte[]) value);
        }

        TestMgr.check(content, value, error);
    });

    return future;
}

From source file:org.apache.servicecomb.foundation.vertx.http.ReadStreamPart.java

protected void onFileOpened(File file, AsyncResult<AsyncFile> ar, CompletableFuture<File> future) {
    if (ar.failed()) {
        future.completeExceptionally(ar.cause());
        return;//from www.j  a v a2s . co m
    }

    AsyncFile asyncFile = ar.result();
    CompletableFuture<Void> saveFuture = saveToWriteStream(asyncFile);
    saveFuture.whenComplete((v, saveException) -> {
        asyncFile.close(closeAr -> {
            if (closeAr.failed()) {
                LOGGER.error("Failed to close file {}.", file);
            }

            // whatever close success or failed
            // will not affect to result
            // result just only related to write
            if (saveException == null) {
                future.complete(file);
                return;
            }

            future.completeExceptionally(saveException);
        });
    });
}

From source file:org.apache.zeppelin.cluster.ClusterManagerServer.java

public void unicastClusterEvent(String host, int port, String msg) {
    LOGGER.info("send unicastClusterEvent message {}", msg);

    Address address = Address.from(host, port);
    CompletableFuture<byte[]> response = messagingService.sendAndReceive(address, ZEPL_CLUSTER_EVENT_TOPIC,
            msg.getBytes(), Duration.ofSeconds(2));
    response.whenComplete((r, e) -> {
        if (null == e) {
            LOGGER.error(e.getMessage(), e);
        } else {//www .  j  a v a 2s. c om
            LOGGER.info("unicastClusterEvent success! {}", msg);
        }
    });
}

From source file:org.apache.zeppelin.cluster.ClusterManagerServer.java

public void broadcastClusterEvent(String msg) {
    LOGGER.info("send broadcastClusterEvent message {}", msg);

    for (Node node : clusterNodes) {
        if (StringUtils.equals(node.address().host(), zeplServerHost)
                && node.address().port() == raftServerPort) {
            // skip myself
            continue;
        }//from  w  w w. j  av  a2s .  com

        CompletableFuture<byte[]> response = messagingService.sendAndReceive(node.address(),
                ZEPL_CLUSTER_EVENT_TOPIC, msg.getBytes(), Duration.ofSeconds(2));
        response.whenComplete((r, e) -> {
            if (null == e) {
                LOGGER.error(e.getMessage(), e);
            } else {
                LOGGER.info("broadcastClusterNoteEvent success! {}", msg);
            }
        });
    }
}