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:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java

@Test
public void testShutdownPendingStartStorageContainer() throws Exception {
    // start the storage container manager
    scManager.start();/*w  w w  .  j av a  2  s . c o m*/

    long containerId = 11L;

    // mock a container and start it in the registry
    CompletableFuture<StorageContainer> startFuture = new CompletableFuture<>();
    CompletableFuture<Void> stopFuture = new CompletableFuture<>();

    StorageContainer mockSc = createStorageContainer(containerId, startFuture, stopFuture);
    when(mockScFactory.createStorageContainer(eq(containerId))).thenReturn(mockSc);

    // update assignment map
    ClusterAssignmentData cad = ClusterAssignmentData.newBuilder()
            .putServers(NetUtils.endpointToString(myEndpoint),
                    ServerAssignmentData.newBuilder().addContainers(containerId).build())
            .build();
    clusterMetadataStore.updateClusterAssignmentData(cad);

    // wait until container start is called
    verify(scRegistry, timeout(10000).times(1)).startStorageContainer(eq(containerId));
    assertEquals(0, scManager.getLiveContainers().size());
    assertEquals(1, scManager.getPendingStartStopContainers().size());
    assertTrue(scManager.getPendingStartStopContainers().contains(containerId));

    // now shutting the manager down
    cad = ClusterAssignmentData.newBuilder().build();
    clusterMetadataStore.updateClusterAssignmentData(cad);

    // the container should not be stopped since it is pending starting.
    Thread.sleep(200);
    verify(scRegistry, timeout(10000).times(0)).stopStorageContainer(eq(containerId), same(mockSc));
    assertEquals(1, scManager.getPendingStartStopContainers().size());
    assertTrue(scManager.getPendingStartStopContainers().contains(containerId));

    // now complete the start future and the container is eventually going to shutdown
    FutureUtils.complete(startFuture, mockSc);
    FutureUtils.complete(stopFuture, null);

    verify(scRegistry, timeout(10000).times(1)).stopStorageContainer(eq(containerId), same(mockSc));
    MoreAsserts.assertUtil(ignored -> scManager.getPendingStartStopContainers().size() == 0, () -> null);
    assertEquals(0, scManager.getLiveContainers().size());
    assertEquals(0, scManager.getPendingStartStopContainers().size());
}

From source file:co.runrightfast.vertx.core.application.RunRightFastVertxApplicationLauncherTest.java

@Test
public void testRunApp() throws Exception {
    ForkJoinPool.commonPool().execute(() -> RunRightFastVertxApplicationLauncher.run(() -> app));

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture future = new CompletableFuture();
    final String address = EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments");
    final Vertx vertx = app.vertxService().getVertx();
    vertx.eventBus().send(address, GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L), getVerticleDeploymentsResponseHandler(future));
    final Object result = future.get(2000L, TimeUnit.MILLISECONDS);

    final ApplicationMXBean appMXBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(),
            applicationMBeanObjectName(JmxUtils.RUNRIGHTFAST_JMX_DOMAIN, ApplicationMXBean.class),
            ApplicationMXBean.class);
    assertThat(appMXBean.getApplicationGroup(), is("co.runrightfast"));
    assertThat(appMXBean.getApplicationName(), is("test-app"));
    assertThat(appMXBean.getApplicationVersion(), is("1.0.0"));
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHConf", appMXBean.configAsHConf() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHJson", appMXBean.configAsJson() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configWithCommentsAndSourceInfo", appMXBean.configWithCommentsAndSourceInfo() });
    appMXBean.shutdown();//from   w ww  . ja  v a  2s.c  om
    app.vertxService().awaitTerminated();
}

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

public boolean deleteDatabaseConnection(String database) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        removeDatabase(database);//from ww  w  .  j  av  a 2 s . c o  m
        future.complete(true);
    });
    try {
        return future.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider.java

/**
 * Check whether the specified role can perform a lookup for the specified topic.
 *
 * For that the caller needs to have producer or consumer permission.
 *
 * @param topicName// w ww. jav  a2s .  c o  m
 * @param role
 * @return
 * @throws Exception
 */
@Override
public CompletableFuture<Boolean> canLookupAsync(TopicName topicName, String role,
        AuthenticationDataSource authenticationData) {
    CompletableFuture<Boolean> finalResult = new CompletableFuture<Boolean>();
    canProduceAsync(topicName, role, authenticationData).whenComplete((produceAuthorized, ex) -> {
        if (ex == null) {
            if (produceAuthorized) {
                finalResult.complete(produceAuthorized);
                return;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Topic [{}] Role [{}] exception occured while trying to check Produce permissions. {}",
                        topicName.toString(), role, ex.getMessage());
            }
        }
        canConsumeAsync(topicName, role, authenticationData, null).whenComplete((consumeAuthorized, e) -> {
            if (e == null) {
                if (consumeAuthorized) {
                    finalResult.complete(consumeAuthorized);
                    return;
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Topic [{}] Role [{}] exception occured while trying to check Consume permissions. {}",
                            topicName.toString(), role, e.getMessage());

                }
                finalResult.completeExceptionally(e);
                return;
            }
            finalResult.complete(false);
        });
    });
    return finalResult;
}

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

@Override
public Future<Void> set(Map<ByteBuffer, ByteBuffer> values, Callback<Void> callback) {
    values.forEach((key, value) -> {/*from  w w  w  .  j  a v  a2  s  .  c  o m*/
        ByteBuf bb = Unpooled.wrappedBuffer(key);
        byte[] keyBytes = ByteBufUtil.getBytes(bb);
        bb = Unpooled.wrappedBuffer(value);
        byte[] valBytes = ByteBufUtil.getBytes(bb);
        producer.newMessage().key(new String(keyBytes, UTF_8)).value(valBytes).sendAsync();
    });
    return producer.flushAsync().whenComplete((ignored, cause) -> {
        if (null != callback) {
            callback.onCompletion(cause, ignored);
        }
        if (null == cause) {
            readToEnd(new CompletableFuture<>());
        }
    });
}

From source file:org.apache.bookkeeper.metadata.etcd.EtcdLedgerManagerTest.java

@Test
public void testProcessLedgers() throws Exception {
    final int numLedgers = 100;
    createNumLedgers(numLedgers);//ww  w .jav  a2  s  .  com

    final CountDownLatch processLatch = new CountDownLatch(numLedgers);
    final CompletableFuture<Void> doneFuture = new CompletableFuture<>();
    lm.asyncProcessLedgers((l, cb) -> processLatch.countDown(), (rc, path, ctx) -> {
        if (Code.OK == rc) {
            FutureUtils.complete(doneFuture, null);
        } else {
            FutureUtils.completeExceptionally(doneFuture, BKException.create(rc));
        }
    }, null, Code.OK, Code.MetaStoreException);

    result(doneFuture);
    processLatch.await();
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> deleteMeter(Meter meter) {
    // Init steps
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    // Store the future related to the operation
    futures.put(key, future);//  w w  w  .j a v a2s.c  o m
    // Create the meter data
    MeterData data = new MeterData(meter, null, local);
    // Update the state of the meter. It will be pruned by observing
    // that it has been removed from the dataplane.
    try {
        // If it does not exist in the system
        if (meters.computeIfPresent(key, (k, v) -> data) == null) {
            // Complete immediately
            future.complete(MeterStoreResult.success());
        }
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    // Done, return the future
    return future;
}

From source file:org.apache.distributedlog.BKLogHandler.java

public CompletableFuture<LogRecordWithDLSN> asyncGetFirstLogRecord() {
    final CompletableFuture<LogRecordWithDLSN> promise = new CompletableFuture<LogRecordWithDLSN>();
    streamMetadataStore.logExists(logMetadata.getUri(), logMetadata.getLogName())
            .whenComplete(new FutureEventListener<Void>() {
                @Override//from   w  ww. j av  a 2  s . co  m
                public void onSuccess(Void value) {
                    readLogSegmentsFromStore(LogSegmentMetadata.COMPARATOR, LogSegmentFilter.DEFAULT_FILTER,
                            null).whenComplete(new FutureEventListener<Versioned<List<LogSegmentMetadata>>>() {

                                @Override
                                public void onSuccess(Versioned<List<LogSegmentMetadata>> ledgerList) {
                                    if (ledgerList.getValue().isEmpty()) {
                                        promise.completeExceptionally(new LogEmptyException(
                                                "Log " + getFullyQualifiedName() + " has no records"));
                                        return;
                                    }
                                    CompletableFuture<LogRecordWithDLSN> firstRecord = null;
                                    for (LogSegmentMetadata ledger : ledgerList.getValue()) {
                                        if (!ledger.isTruncated()
                                                && (ledger.getRecordCount() > 0 || ledger.isInProgress())) {
                                            firstRecord = asyncReadFirstUserRecord(ledger, DLSN.InitialDLSN);
                                            break;
                                        }
                                    }
                                    if (null != firstRecord) {
                                        FutureUtils.proxyTo(firstRecord, promise);
                                    } else {
                                        promise.completeExceptionally(new LogEmptyException(
                                                "Log " + getFullyQualifiedName() + " has no records"));
                                    }
                                }

                                @Override
                                public void onFailure(Throwable cause) {
                                    promise.completeExceptionally(cause);
                                }
                            });
                }

                @Override
                public void onFailure(Throwable cause) {
                    promise.completeExceptionally(cause);
                }
            });
    return promise;
}

From source file:com.ikanow.aleph2.storm.harvest_technology.StormHarvestTechnologyModule.java

@Override
public CompletableFuture<BasicMessageBean> onDelete(DataBucketBean to_delete, IHarvestContext context) {
    //TODO not sure what delete is suppose to do, stop this topology? I assume no
    //data is being stored in the harvest tech so nothing to delete? (see purge)
    CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    try {/*from w  w w.ja va2  s.  c  o m*/
        StormControllerUtil.stopJob(storm_controller, getJobName(to_delete));
    } catch (Exception e) {
        logger.info("Stop completing exceptionally", e);
        future.complete(new BasicMessageBean(new Date(), false, null, "onDelete", null,
                ErrorUtils.getLongForm("{0}", e), null));
        return future;
    }
    logger.info("returning completed stop");
    future.complete(new BasicMessageBean(new Date(), true, null, "onDelete", null, null, null));
    return future;
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

CompletableFuture PickUpAndFixDeadletters(String connectionString, String queueName,
        IMessageSender resubmitSender, ExecutorService executorService) throws Exception {
    CompletableFuture running = new CompletableFuture();
    QueueClient receiver = new QueueClient(
            new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK);

    running.whenComplete((r, t) -> {//w  w w.  ja v a 2s  .  co  m
        try {
            receiver.close();
        } catch (ServiceBusException e) {
            System.out.printf(e.getMessage());
        }
    });

    // register the RegisterMessageHandler callback
    receiver.registerMessageHandler(new IMessageHandler() {
        // callback invoked when the message handler loop has obtained a message
        public CompletableFuture<Void> onMessageAsync(IMessage message) {
            try {
                IMessage resubmitMessage = new Message(message.getBody());
                if (message.getLabel() != null && message.getLabel().contentEquals("Physicist")) {
                    System.out.printf(
                            "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n",
                            message.getMessageId(), message.getSequenceNumber(), message.getLabel());
                    resubmitMessage.setMessageId(message.getMessageId());
                    resubmitMessage.setLabel("Scientist");
                    resubmitMessage.setContentType(message.getContentType());
                    resubmitMessage.setTimeToLive(Duration.ofMinutes(2));
                    resubmitSender.send(resubmitMessage);
                }
                return receiver.completeAsync(message.getLockToken());
            } catch (Exception e) {
                CompletableFuture failure = new CompletableFuture();
                failure.completeExceptionally(e);
                return failure;
            }
        }

        // callback invoked when the message handler has an exception to report
        public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
            System.out.printf(exceptionPhase + "-" + throwable.getMessage());
        }
    },
            // 1 concurrent call, messages are auto-completed, auto-renew duration
            new MessageHandlerOptions(1, false, Duration.ofMinutes(1)), executorService);

    return running;
}