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.eclipse.hono.service.AbstractApplication.java

/**
 * Starts up this application./*from w w  w .  jav  a2  s.  co m*/
 * <p>
 * The start up process entails the following steps:
 * <ol>
 * <li>invoke <em>deployRequiredVerticles</em> to deploy the verticle(s) implementing the service's functionality</li>
 * <li>invoke <em>deployServiceVerticles</em> to deploy the protocol specific service endpoints</li>
 * <li>invoke <em>postRegisterServiceVerticles</em> to perform any additional post deployment steps</li>
 * <li>start the health check server</li>
 * </ol>
 * 
 * @param args The command line arguments provided to the application.
 */
public void run(final ApplicationArguments args) {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    } else if (serviceFactories.isEmpty()) {
        throw new IllegalStateException("no service factory has been configured");
    }

    healthCheckServer = new HealthCheckServer(vertx, config);

    final Future<Void> future = deployRequiredVerticles(config.getMaxInstances())
            .compose(s -> deployServiceVerticles()).compose(s -> postRegisterServiceVerticles())
            .compose(s -> healthCheckServer.start());

    final CompletableFuture<Void> started = new CompletableFuture<>();
    future.setHandler(result -> {
        if (result.failed()) {
            started.completeExceptionally(result.cause());
        } else {
            started.complete(null);
        }
    });

    final int startupTimeoutSeconds = config.getStartupTimeout();

    try {
        log.debug("Waiting for {} seconds to start up", startupTimeoutSeconds);
        started.get(startupTimeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.error("startup timed out after {} seconds, shutting down ...", startupTimeoutSeconds);
        shutdown();
    } catch (InterruptedException e) {
        log.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
    } catch (ExecutionException e) {
        log.error("exception occurred during startup, shutting down ...", e);
        shutdown();
    }
}

From source file:spring.travel.site.services.HttpClient.java

private <T> CompletableFuture<T> execute(Supplier<Request> requestSupplier, Consumer<Request> requestConsumer,
        ResponseMapper<T> responseMapper) {
    CompletableFuture<T> future = new CompletableFuture<>();
    try {// www.  j  a  va  2s  .  c  om
        Request request = requestSupplier.get();
        requestConsumer.accept(request);
        asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<T>() {
            @Override
            public T onCompleted(Response response) throws Exception {
                T t = responseMapper.map(response);
                future.complete(t);
                return t;
            }

            @Override
            public void onThrowable(Throwable t) {
                future.completeExceptionally(t);
            }
        });
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}

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);
                }/*  ww  w .j a  v a 2  s  .  c  om*/
            });
            // 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.distributedlog.BookKeeperClient.java

public CompletableFuture<Void> deleteLedger(long lid, final boolean ignoreNonExistentLedger) {
    BookKeeper bk;/*w  w w  .j  a  v  a 2 s  .  c om*/
    try {
        bk = get();
    } catch (IOException ioe) {
        return FutureUtils.exception(ioe);
    }
    final CompletableFuture<Void> promise = new CompletableFuture<Void>();
    bk.asyncDeleteLedger(lid, new AsyncCallback.DeleteCallback() {
        @Override
        public void deleteComplete(int rc, Object ctx) {
            if (BKException.Code.OK == rc) {
                promise.complete(null);
            } else if (BKException.Code.NoSuchLedgerExistsException == rc) {
                if (ignoreNonExistentLedger) {
                    promise.complete(null);
                } else {
                    promise.completeExceptionally(BKException.create(rc));
                }
            } else {
                promise.completeExceptionally(BKException.create(rc));
            }
        }
    }, null);
    return promise;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.RenovatorTest.java

@Test
public void testHaltingScenario() throws DeserializeException, LoginException, RepositoryException,
        InterruptedException, ExecutionException, PersistenceException {
    assertEquals("Renovator: relocator test", instance.getName());
    Map<String, Object> values = new HashMap<>();
    values.put("sourceJcrPath", "/content/dam/folderA");
    values.put("destinationJcrPath", "/content/dam/folderB");
    instance.init(rr, values);//from w w w .  ja v a 2 s. co  m

    CompletableFuture<Boolean> f = new CompletableFuture<>();

    instance.defineAction("Halt", rr, am -> {
        instance.halt();
        try {
            assertTrue(instance.updateProgress() < 1.0);
            assertFalse(instance.getInfo().isIsRunning());
            f.complete(true);
        } catch (Throwable t) {
            f.completeExceptionally(t);
        }
    });
    instance.run(rr);
    assertTrue(f.get());
    verify(rr, atLeastOnce()).commit();
}

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

private void checkAndReadNext(CompletableFuture<Void> endFuture) {
    reader.hasMessageAvailableAsync().whenComplete((hasMessageAvailable, cause) -> {
        if (null != cause) {
            endFuture.completeExceptionally(cause);
        } else {// w  ww  . ja v a 2 s. c  o  m
            if (hasMessageAvailable) {
                readNext(endFuture);
            } else {
                endFuture.complete(null);
            }
        }
    });
}

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

private CompletableFuture<Void> closeLedger(LedgerHandle lh) {
    CompletableFuture<Void> bkf = new CompletableFuture<>();
    lh.asyncClose((rc, ledger, ctx) -> {
        if (rc != BKException.Code.OK) {
            bkf.completeExceptionally(BKException.create(rc));
        } else {/* w  ww.  ja v a  2  s .c o m*/
            bkf.complete(null);
        }
    }, null);
    return bkf;
}

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 {/* w  w w .ja  va2s.  c  o m*/
            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:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java

private CompletableFuture<Void> toOutputStreamSync(OutputStream outputStream, boolean autoCloseOutputStream) {
    CompletableFuture<Void> future = new CompletableFuture<>();

    try (InputStream inputStream = part.getInputStream()) {
        IOUtils.copyLarge(inputStream, outputStream);
    } catch (Throwable e) {
        future.completeExceptionally(e);
    }//  www .  jav  a  2s  .c om

    if (autoCloseOutputStream) {
        try {
            outputStream.close();
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    }

    future.complete(null);
    return future;
}

From source file:org.apache.distributedlog.impl.subscription.ZKSubscriptionsStore.java

@Override
public CompletableFuture<Map<String, DLSN>> getLastCommitPositions() {
    final CompletableFuture<Map<String, DLSN>> result = new CompletableFuture<Map<String, DLSN>>();
    try {//from  w  w  w. java 2  s  .co  m
        this.zkc.get().getChildren(this.zkPath, false, new AsyncCallback.Children2Callback() {
            @Override
            public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
                if (KeeperException.Code.NONODE.intValue() == rc) {
                    result.complete(new HashMap<String, DLSN>());
                } else if (KeeperException.Code.OK.intValue() != rc) {
                    result.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path));
                } else {
                    getLastCommitPositions(result, children);
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException zkce) {
        result.completeExceptionally(zkce);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        result.completeExceptionally(new DLInterruptedException("getLastCommitPositions was interrupted", ie));
    }
    return result;
}