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.apache.pulsar.broker.authorization.AuthorizationService.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/*from  w w w. j  a  v a2 s  . c  om*/
 * @param role
 * @return
 * @throws Exception
 */
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, null, 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.compaction.TwoPhaseCompactor.java

private CompletableFuture<Void> deleteLedger(BookKeeper bk, LedgerHandle lh) {
    CompletableFuture<Void> bkf = new CompletableFuture<>();
    bk.asyncDeleteLedger(lh.getId(), (rc, ctx) -> {
        if (rc != BKException.Code.OK) {
            bkf.completeExceptionally(BKException.create(rc));
        } else {//from   w  ww .  j  a  v a 2s  . c o  m
            bkf.complete(null);
        }
    }, null);
    return bkf;
}

From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableReadFunction.java

/**
 * Helper method to read bytes from binaryDocument and release the buffer.
 *//*  w w w .j a va 2 s .c  om*/
private void handleGetAsyncBinaryDocument(BinaryDocument binaryDocument, CompletableFuture<V> future,
        String key) {
    ByteBuf buffer = binaryDocument.content();
    try {
        byte[] bytes;
        if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.readableBytes() == buffer.array().length) {
            bytes = buffer.array();
        } else {
            bytes = new byte[buffer.readableBytes()];
            buffer.readBytes(bytes);
        }
        future.complete(valueSerde.fromBytes(bytes));
    } catch (Exception e) {
        future.completeExceptionally(new SamzaException(
                String.format("Failed to deserialize value of key %s with given serde", key), e));
    } finally {
        ReferenceCountUtil.release(buffer);
    }
}

From source file:org.onlab.netty.NettyMessaging.java

private void dispatchLocally(InternalMessage message) throws IOException {
    String type = message.type();
    if (REPLY_MESSAGE_TYPE.equals(type)) {
        try {/*from  w w  w  .j ava2 s .  com*/
            CompletableFuture<byte[]> futureResponse = responseFutures.getIfPresent(message.id());
            if (futureResponse != null) {
                futureResponse.complete(message.payload());
            } else {
                log.warn("Received a reply for message id:[{}]. " + " from {}. But was unable to locate the"
                        + " request handle", message.id(), message.sender());
            }
        } finally {
            responseFutures.invalidate(message.id());
        }
        return;
    }
    Consumer<InternalMessage> handler = handlers.get(type);
    if (handler != null) {
        handler.accept(message);
    } else {
        log.debug("No handler registered for {}", type);
    }
}

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

public Pair<String, CompletableFuture<List<DeviceCommand>>> sendSubscribeRequest(final Set<String> devices,
        final Set<String> names, final Date timestamp, final BiConsumer<DeviceCommand, String> callback)
        throws InterruptedException {

    final String subscriptionId = UUID.randomUUID().toString();
    Collection<CompletableFuture<Collection<DeviceCommand>>> futures = devices.stream()
            .map(device -> new CommandSubscribeRequest(subscriptionId, device, names, timestamp))
            .map(subscribeRequest -> {
                CompletableFuture<Collection<DeviceCommand>> future = new CompletableFuture<>();
                Consumer<Response> responseConsumer = response -> {
                    String resAction = response.getBody().getAction();
                    if (resAction.equals(Action.COMMAND_SUBSCRIBE_RESPONSE.name())) {
                        future.complete(response.getBody().cast(CommandSubscribeResponse.class).getCommands());
                    } else if (resAction.equals(Action.COMMAND_EVENT.name())) {
                        callback.accept(response.getBody().cast(CommandEvent.class).getCommand(),
                                subscriptionId);
                    } else {
                        logger.warn("Unknown action received from backend {}", resAction);
                    }// w ww  .j a v  a2s . c o m
                };
                Request request = Request.newBuilder().withBody(subscribeRequest)
                        .withPartitionKey(subscribeRequest.getDevice()).withSingleReply(false).build();
                rpcClient.call(request, responseConsumer);
                return future;
            }).collect(Collectors.toList());

    CompletableFuture<List<DeviceCommand>> future = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> futures.stream()
                    .map(CompletableFuture::join).flatMap(Collection::stream).collect(Collectors.toList()));
    return Pair.of(subscriptionId, future);
}

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

private Handler<AsyncResult<Message<GetVerticleDeployments.Response>>> getVerticleDeploymentsResponseHandler(
        final CompletableFuture future) {
    return result -> {
        if (result.succeeded()) {
            log.logp(INFO, getClass().getName(), "test_vertx_default_options.success",
                    JsonUtils.toVertxJsonObject(ProtobufUtils.protobuMessageToJson(result.result().body()))
                            .encodePrettily());
            future.complete(result.result().body());
        } else {/*from w w  w .  j  a v  a 2s  .  c  o m*/
            log.logp(SEVERE, getClass().getName(), "test_vertx_default_options.failure",
                    "get-verticle-deployments failed", result.cause());
            future.completeExceptionally(result.cause());
        }
    };
}

From source file:opensnap.repository.MongoRepository.java

public CompletableFuture<List<T>> getAll() {
    CompletableFuture<List<T>> future = new CompletableFuture<>();
    List<T> list = new ArrayList<>();

    collection.find(Document.valueOf("{_id:{ $exists: true }}")).forEach((document) -> {
        try {/*from w  w w.j a v  a  2 s  . co m*/
            list.add(mapper.readValue(toJson(document), clazz));
        } catch (IOException e) {
            logger.error("Error while parsing document in getAll() : " + document.toString(), e);
        }

    }).register((result, e) -> future.complete(list));
    return future;
}

From source file:io.pravega.service.server.host.stat.AutoScaleProcessorTest.java

@Test(timeout = 10000)
public void scaleTest() {
    CompletableFuture<Void> result = new CompletableFuture<>();
    CompletableFuture<Void> result2 = new CompletableFuture<>();
    CompletableFuture<Void> result3 = new CompletableFuture<>();
    EventStreamWriter<ScaleEvent> writer = createWriter(event -> {
        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1)
                && event.getDirection() == ScaleEvent.UP) {
            result.complete(null);
        }/*from   ww  w.j a v  a2 s . com*/

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2)
                && event.getDirection() == ScaleEvent.DOWN) {
            result2.complete(null);
        }

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3)
                && event.getDirection() == ScaleEvent.DOWN) {
            result3.complete(null);
        }
    });

    AutoScaleProcessor monitor = new AutoScaleProcessor(writer,
            AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0)
                    .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0)
                    .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1)
                    .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(),
            executor, maintenanceExecutor);

    String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0);
    String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0);
    String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0);
    monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);

    long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis();
    monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback));
    monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback));

    monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback,
            1001, 500, 200, 200);

    monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0,
            0.0, 0.0, 0.0);

    monitor.notifySealed(streamSegmentName1);
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result3));
}

From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessorTest.java

@Test(timeout = 10000)
public void scaleTest() {
    CompletableFuture<Void> result = new CompletableFuture<>();
    CompletableFuture<Void> result2 = new CompletableFuture<>();
    CompletableFuture<Void> result3 = new CompletableFuture<>();
    EventStreamWriter<AutoScaleEvent> writer = createWriter(event -> {
        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1)
                && event.getDirection() == AutoScaleEvent.UP) {
            result.complete(null);
        }//from  w w w .  j  a  va  2  s. c  o  m

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2)
                && event.getDirection() == AutoScaleEvent.DOWN) {
            result2.complete(null);
        }

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3)
                && event.getDirection() == AutoScaleEvent.DOWN) {
            result3.complete(null);
        }
    });

    AutoScaleProcessor monitor = new AutoScaleProcessor(writer,
            AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0)
                    .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0)
                    .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1)
                    .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(),
            executor, maintenanceExecutor);

    String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0);
    String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0);
    String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0);
    monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);

    long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis();
    monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback));
    monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback));

    monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback,
            1001, 500, 200, 200);

    monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0,
            0.0, 0.0, 0.0);

    monitor.notifySealed(streamSegmentName1);
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result3));
}

From source file:org.onlab.netty.NettyMessaging.java

protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    try {/* w  w w. j  a v  a  2s  .c om*/
        if (ep.equals(localEp)) {
            dispatchLocally(message);
            future.complete(null);
        } else {
            Channel channel = null;
            try {
                channel = channels.borrowObject(ep);
                channel.writeAndFlush(message).addListener(channelFuture -> {
                    if (!channelFuture.isSuccess()) {
                        future.completeExceptionally(channelFuture.cause());
                    } else {
                        future.complete(null);
                    }
                });
            } finally {
                channels.returnObject(ep, channel);
            }
        }
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}