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:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
    for (int value = 0; value < 10;) {
        Double numberOfExecution = Math.pow(10, value);
        CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();

        Long startTime = System.nanoTime();
        IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
            SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel,
                    new Message(new Header(message.type(), message.getHeader().getSession())), 0);
            if (!showResult) {
                simpleEvaluationObject.noResult();
            }//  w w  w . j  a va2 s  .co  m

            kernel.executeCode(codeToExecute, simpleEvaluationObject);
            if (numberOfExecution.intValue() - 1 == indexOfExecution) {
                if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
                    keepLooking.complete(false);
                } else {
                    keepLooking.complete(true);
                }
            }
        });

        try {
            if (keepLooking.get()) {
                value++;
            } else {
                return numberOfExecution.intValue();
            }
        } catch (ExecutionException | InterruptedException e) {
            throw new IllegalStateException("Cannot create best number of execution.");
        }
    }

    throw new IllegalStateException("Cannot create best number of execution.");
}

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   ww w . ja  va2  s  .  co  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:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> setSegmentTable(Data<Integer> data) {
    Preconditions.checkNotNull(data);/*from  w  w w  .ja  va  2 s. c  o  m*/
    Preconditions.checkNotNull(data.getData());

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (lock) {
        if (segmentTable == null) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Segment table for stream: " + getName()));
        } else if (segmentTable.getVersion().equals(data.getVersion())) {
            segmentTable = new Data<>(Arrays.copyOf(data.getData(), data.getData().length),
                    data.getVersion() + 1);
            result.complete(null);
        } else {
            result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT,
                    "Segment table 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/* w  ww .j  a  v  a 2 s.co m*/
        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:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

/**
 * Test of startUp method, of class OrientDBVerticle.
 *///from   w w  w  .j a  v  a 2 s . c  om
@Test
public void testVerticle() throws Exception {
    log.info("test_eventBus_GetVerticleDeployments");
    final Vertx vertx = vertxService.getVertx();

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture<GetVerticleDeployments.Response> getVerticleDeploymentsFuture = new CompletableFuture<>();
    final long timeout = 60000L;
    vertx.eventBus().send(EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments"),
            GetVerticleDeployments.Request.newBuilder().build(), new DeliveryOptions().setSendTimeout(timeout),
            responseHandler(getVerticleDeploymentsFuture, GetVerticleDeployments.Response.class));
    final GetVerticleDeployments.Response getVerticleDeploymentsResponse = getVerticleDeploymentsFuture
            .get(timeout, TimeUnit.MILLISECONDS);
    final int totalHealthCheckCount = getVerticleDeploymentsResponse.getDeploymentsList().stream()
            .collect(Collectors.summingInt(VerticleDeployment::getHealthChecksCount));

    final CompletableFuture<RunVerticleHealthChecks.Response> future = new CompletableFuture<>();
    vertx.eventBus().send(EventBusAddress.eventBusAddress(verticleManagerId, "run-verticle-healthchecks"),
            RunVerticleHealthChecks.Request.newBuilder().build(),
            addRunRightFastHeaders(new DeliveryOptions().setSendTimeout(timeout)),
            responseHandler(future, RunVerticleHealthChecks.Response.class));

    final RunVerticleHealthChecks.Response response = future.get(timeout, TimeUnit.MILLISECONDS);
    assertThat(response.getResultsCount(), is(totalHealthCheckCount));

}

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

public CompletableFuture<Void> update(DeviceCommand cmd, DeviceCommandWrapper commandWrapper) {
    if (cmd == null) {
        throw new NoSuchElementException("Command not found");
    }//from  ww  w.j a va  2s .  co m
    cmd.setIsUpdated(true);

    if (commandWrapper.getCommand() != null) {
        cmd.setCommand(commandWrapper.getCommand().orElse(null));
    }
    if (commandWrapper.getTimestamp() != null && commandWrapper.getTimestamp().isPresent()) {
        cmd.setTimestamp(commandWrapper.getTimestamp().get());
    }
    if (commandWrapper.getParameters() != null) {
        cmd.setParameters(commandWrapper.getParameters().orElse(null));
    }
    if (commandWrapper.getLifetime() != null) {
        cmd.setLifetime(commandWrapper.getLifetime().orElse(null));
    }
    if (commandWrapper.getStatus() != null) {
        cmd.setStatus(commandWrapper.getStatus().orElse(null));
    }
    if (commandWrapper.getResult() != null) {
        cmd.setResult(commandWrapper.getResult().orElse(null));
    }

    hiveValidator.validate(cmd);

    CompletableFuture<Response> future = new CompletableFuture<>();
    rpcClient.call(Request.newBuilder().withBody(new CommandUpdateRequest(cmd)).build(),
            new ResponseConsumer(future));
    return future.thenApply(response -> null);
}

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

public CompletableFuture<Void> deleteLedger(long lid, final boolean ignoreNonExistentLedger) {
    BookKeeper bk;//w  w  w. jav a2 s . c  o  m
    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:org.eclipse.smarthome.binding.mqtt.generic.internal.generic.ChannelState.java

/**
 * Subscribes to the state topic on the given connection and informs about updates on the given listener.
 *
 * @param connection A broker connection
 * @param scheduler A scheduler to realize the timeout
 * @param timeout A timeout in milliseconds. Can be 0 to disable the timeout and let the future return earlier.
 * @param channelStateUpdateListener An update listener
 * @return A future that completes with true if the subscribing worked, with false if the stateTopic is not set
 *         and exceptionally otherwise.//ww  w.  j a  v  a 2s. co m
 */
public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection,
        ScheduledExecutorService scheduler, int timeout) {
    if (hasSubscribed) {
        return CompletableFuture.completedFuture(null);
    }

    this.connection = connection;

    if (StringUtils.isBlank(config.stateTopic)) {
        return CompletableFuture.completedFuture(null);
    }

    this.future = new CompletableFuture<>();
    connection.subscribe(config.stateTopic, this).thenRun(() -> {
        hasSubscribed = true;
        if (timeout > 0 && !future.isDone()) {
            this.scheduledFuture = scheduler.schedule(this::receivedOrTimeout, timeout, TimeUnit.MILLISECONDS);
        } else {
            receivedOrTimeout();
        }
    }).exceptionally(this::subscribeFail);
    return future;
}

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

@Override
public CompletableFuture<Void> grantPermissionAsync(NamespaceName namespaceName, Set<AuthAction> actions,
        String role, String authDataJson) {
    CompletableFuture<Void> result = new CompletableFuture<>();

    try {//from w  w w.jav a  2 s  .  c  o m
        validatePoliciesReadOnlyAccess();
    } catch (Exception e) {
        result.completeExceptionally(e);
    }

    ZooKeeper globalZk = configCache.getZooKeeper();
    final String policiesPath = String.format("/%s/%s/%s", "admin", POLICIES, namespaceName.toString());

    try {
        Stat nodeStat = new Stat();
        byte[] content = globalZk.getData(policiesPath, null, nodeStat);
        Policies policies = getThreadLocal().readValue(content, Policies.class);
        policies.auth_policies.namespace_auth.put(role, actions);

        // Write back the new policies into zookeeper
        globalZk.setData(policiesPath, getThreadLocal().writeValueAsBytes(policies), nodeStat.getVersion());

        configCache.policiesCache().invalidate(policiesPath);

        log.info("[{}] Successfully granted access for role {}: {} - namespace {}", role, role, actions,
                namespaceName);
        result.complete(null);
    } catch (KeeperException.NoNodeException e) {
        log.warn("[{}] Failed to set permissions for namespace {}: does not exist", role, namespaceName);
        result.completeExceptionally(new IllegalArgumentException("Namespace does not exist" + namespaceName));
    } catch (KeeperException.BadVersionException e) {
        log.warn("[{}] Failed to set permissions for namespace {}: concurrent modification", role,
                namespaceName);
        result.completeExceptionally(new IllegalStateException(
                "Concurrent modification on zk path: " + policiesPath + ", " + e.getMessage()));
    } catch (Exception e) {
        log.error("[{}] Failed to get permissions for namespace {}", role, namespaceName, e);
        result.completeExceptionally(
                new IllegalStateException("Failed to get permissions for namespace " + namespaceName));
    }

    return result;
}

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

@Override
public CompletableFuture<MeterStoreResult> updateMeter(Meter meter) {
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    futures.put(key, future);//from  ww w. j av a2  s  .c  o  m

    MeterData data = new MeterData(meter, null, local);
    try {
        if (meters.computeIfPresent(key, (k, v) -> data) == null) {
            future.complete(MeterStoreResult.fail(MeterFailReason.INVALID_METER));
        }
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    return future;
}