Example usage for java.util.concurrent CompletableFuture thenApply

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

Introduction

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

Prototype

public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn) 

Source Link

Usage

From source file:de.ks.text.view.AsciiDocViewer.java

public void preload(Collection<AsciiDocContent> load) {
    ActivityExecutor executorService = controller.getExecutorService();
    JavaFXExecutorService javaFXExecutor = controller.getJavaFXExecutor();
    load.forEach(t -> {//from   w w  w .  j a  va  2s.  c om
        CompletableFuture<Pair<String, String>> completableFuture = CompletableFuture
                .supplyAsync(() -> preProcess(t.getAdoc()), executorService)//
                .thenApply(desc -> {
                    if (desc == null || desc.trim().isEmpty()) {
                        return "";
                    } else {
                        return parser.parse(desc);
                    }
                })//
                .thenApply(html -> Pair.of(t.getIdentifier(), html));
        completableFuture.thenApply(pair -> {
            preloaded.put(pair.getKey(), pair.getValue());
            return pair;
        }).thenAcceptAsync(pair -> {
            if (currentIdentifier.getValueSafe().equals(pair.getKey())) {
                String html = pair.getValue();
                currentHtml.set(html);
                webView.getEngine().loadContent(html);
            }
        }, javaFXExecutor)//
                .exceptionally(e -> {
                    log.error("Could not parse adoc", e);
                    return null;
                });
    });
}

From source file:com.ikanow.aleph2.data_import_manager.analytics.actors.DataBucketAnalyticsChangeActor.java

/** Combine the analytic thread level results and the per-job results into a single reply
 * @param top_level/*from  w w w .  ja  va2 s  . c o m*/
 * @param per_job
 * @param source
 * @return
 */
protected final static CompletableFuture<BucketActionReplyMessage> combineResults(
        final CompletableFuture<BasicMessageBean> top_level,
        final List<CompletableFuture<BasicMessageBean>> per_job, final String source) {
    if (per_job.isEmpty()) {
        return top_level.thenApply(reply -> new BucketActionHandlerMessage(source, reply));
    } else { // slightly more complex:

        // First off wait for them all to complete:
        final CompletableFuture<?>[] futures = per_job.toArray(new CompletableFuture<?>[0]);

        return top_level.thenCombine(CompletableFuture.allOf(futures), (thread, __) -> {
            List<BasicMessageBean> replies = Stream.concat(Lambdas.get(() -> {
                if (thread.success() && ((null == thread.message()) || thread.message().isEmpty())) {
                    // Ignore top level, it's not very interesting
                    return Stream.empty();
                } else
                    return Stream.of(thread);
            }), per_job.stream().map(cf -> cf.join())

            ).collect(Collectors.toList());

            return (BucketActionReplyMessage) new BucketActionCollectedRepliesMessage(source, replies,
                    Collections.emptySet(), Collections.emptySet());
        }).exceptionally(t -> {
            return (BucketActionReplyMessage) new BucketActionHandlerMessage(source,
                    ErrorUtils.buildErrorMessage(DataBucketAnalyticsChangeActor.class.getSimpleName(), source,
                            ErrorUtils.getLongForm("{0}", t)));
        });
    }
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

@Override
public synchronized CompletableFuture<Void> setAutoCommit(boolean useAutoCommit) {
    if (useAutoCommit == _autocommit) {
        return CompletableFuture.completedFuture(null);
    }// www  .j a  va2  s. c o  m
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }
    send(new SetFeatureMessage().setAutoCommit(useAutoCommit), new ConfirmationResponseHandler(future,
            MessageType.SetFeatureCompleteMessage, "waiting for a server settings complete message"));
    return future.thenApply(v -> {
        _autocommit = useAutoCommit;
        return null;
    });
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

@Override
public CompletableFuture<Pair<Integer, List<Integer>>> getActiveEpoch(boolean ignoreCached) {
    CompletableFuture<Data<T>> historyTableFuture = ignoreCached ? getHistoryTableFromStore()
            : getHistoryTable();/*from www.j a  va  2  s  .c om*/

    return historyTableFuture.thenApply(table -> TableHelper.getActiveEpoch(table.getData()));
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

@Override
public CompletableFuture<Boolean> deleteObjectBySpec(final QueryComponent<O> unique_spec) {
    try {//from  w w  w .java  2  s.c o  m
        // Delete and return the object
        final CompletableFuture<Optional<O>> ret_val = updateAndReturnObjectBySpec(unique_spec,
                Optional.of(false), CrudUtils.update(_state.bean_clazz).deleteObject(), Optional.of(true),
                Arrays.asList(_ID), true);

        // Return a future that just wraps ret_val - ie returns true if the doc is present, ie was just deleted
        return ret_val.thenApply(opt -> opt.isPresent());
    } catch (Exception e) {
        return FutureUtils.<Boolean>returnError(e);
    }
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

@Override
public CompletableFuture<List<ScaleMetadata>> getScaleMetadata() {
    return verifyLegalState().thenCompose(v -> getHistoryTable())
            .thenApply(x -> TableHelper.getScaleMetadata(x.getData()))
            .thenCompose(listOfScaleRecords -> FutureHelpers
                    .allOfWithResults(listOfScaleRecords.stream().map(record -> {
                        long scaleTs = record.getLeft();
                        CompletableFuture<List<Segment>> list = FutureHelpers.allOfWithResults(
                                record.getRight().stream().map(this::getSegment).collect(Collectors.toList()));

                        return list.thenApply(segments -> new ScaleMetadata(scaleTs, segments));
                    }).collect(Collectors.toList())));
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleProducer(final CommandProducer cmdProducer) {
    checkArgument(state == State.Connected);
    CompletableFuture<Boolean> authorizationFuture;
    if (service.isAuthorizationEnabled()) {
        authorizationFuture = service.getAuthorizationManager()
                .canProduceAsync(DestinationName.get(cmdProducer.getTopic().toString()), authRole);
    } else {//  w w w.j  a  v a2 s.  c om
        authorizationFuture = CompletableFuture.completedFuture(true);
    }

    // Use producer name provided by client if present
    final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName()
            : service.generateUniqueProducerName();
    final String topicName = cmdProducer.getTopic();
    final long producerId = cmdProducer.getProducerId();
    final long requestId = cmdProducer.getRequestId();
    authorizationFuture.thenApply(isAuthorized -> {
        if (isAuthorized) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Client is authorized to Produce with role {}", remoteAddress, authRole);
            }
            CompletableFuture<Producer> producerFuture = new CompletableFuture<>();
            CompletableFuture<Producer> existingProducerFuture = producers.putIfAbsent(producerId,
                    producerFuture);

            if (existingProducerFuture != null) {
                if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) {
                    Producer producer = existingProducerFuture.getNow(null);
                    log.info("[{}] Producer with the same id is already created: {}", remoteAddress, producer);
                    ctx.writeAndFlush(Commands.newProducerSuccess(requestId, producer.getProducerName()));
                    return null;
                } else {
                    // There was an early request to create a producer with
                    // same producerId. This can happen when
                    // client
                    // timeout is lower the broker timeouts. We need to wait
                    // until the previous producer creation
                    // request
                    // either complete or fails.
                    ServerError error = !existingProducerFuture.isDone() ? ServerError.ServiceNotReady
                            : getErrorCode(existingProducerFuture);
                    log.warn("[{}][{}] Producer is already present on the connection", remoteAddress,
                            topicName);
                    ctx.writeAndFlush(Commands.newError(requestId, error,
                            "Producer is already present on the connection"));
                    return null;
                }
            }

            log.info("[{}][{}] Creating producer. producerId={}", remoteAddress, topicName, producerId);

            service.getTopic(topicName).thenAccept((Topic topic) -> {
                // Before creating producer, check if backlog quota exceeded
                // on topic
                if (topic.isBacklogQuotaExceeded(producerName)) {
                    IllegalStateException illegalStateException = new IllegalStateException(
                            "Cannot create producer on topic with backlog quota exceeded");
                    BacklogQuota.RetentionPolicy retentionPolicy = topic.getBacklogQuota().getPolicy();
                    if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) {
                        ctx.writeAndFlush(
                                Commands.newError(requestId, ServerError.ProducerBlockedQuotaExceededError,
                                        illegalStateException.getMessage()));
                    } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) {
                        ctx.writeAndFlush(
                                Commands.newError(requestId, ServerError.ProducerBlockedQuotaExceededException,
                                        illegalStateException.getMessage()));
                    }
                    producerFuture.completeExceptionally(illegalStateException);
                    producers.remove(producerId, producerFuture);
                    return;
                }

                disableTcpNoDelayIfNeeded(topicName, producerName);

                Producer producer = new Producer(topic, ServerCnx.this, producerId, producerName, authRole);

                try {
                    topic.addProducer(producer);

                    if (isActive()) {
                        if (producerFuture.complete(producer)) {
                            log.info("[{}] Created new producer: {}", remoteAddress, producer);
                            ctx.writeAndFlush(Commands.newProducerSuccess(requestId, producerName));
                            return;
                        } else {
                            // The producer's future was completed before by
                            // a close command
                            producer.closeNow();
                            log.info("[{}] Cleared producer created after timeout on client side {}",
                                    remoteAddress, producer);
                        }
                    } else {
                        producer.closeNow();
                        log.info("[{}] Cleared producer created after connection was closed: {}", remoteAddress,
                                producer);
                        producerFuture.completeExceptionally(
                                new IllegalStateException("Producer created after connection was closed"));
                    }
                } catch (BrokerServiceException ise) {
                    log.error("[{}] Failed to add producer to topic {}: {}", remoteAddress, topicName,
                            ise.getMessage());
                    ctx.writeAndFlush(Commands.newError(requestId,
                            BrokerServiceException.getClientErrorCode(ise), ise.getMessage()));
                    producerFuture.completeExceptionally(ise);
                }

                producers.remove(producerId, producerFuture);
            }).exceptionally(exception -> {
                Throwable cause = exception.getCause();
                if (!(cause instanceof ServiceUnitNotReadyException)) {
                    // Do not print stack traces for expected exceptions
                    log.error("[{}] Failed to create topic {}", remoteAddress, topicName, exception);
                }

                // If client timed out, the future would have been completed
                // by subsequent close. Send error back to
                // client, only if not completed already.
                if (producerFuture.completeExceptionally(exception)) {
                    ctx.writeAndFlush(Commands.newError(requestId,
                            BrokerServiceException.getClientErrorCode(cause), cause.getMessage()));
                }
                producers.remove(producerId, producerFuture);

                return null;
            });
        } else {
            String msg = "Client is not authorized to Produce";
            log.warn("[{}] {} with role {}", remoteAddress, msg, authRole);
            ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg));
        }
        return null;
    });
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleSubscribe(final CommandSubscribe subscribe) {
    checkArgument(state == State.Connected);
    CompletableFuture<Boolean> authorizationFuture;
    if (service.isAuthorizationEnabled()) {
        authorizationFuture = service.getAuthorizationManager()
                .canConsumeAsync(DestinationName.get(subscribe.getTopic()), authRole);
    } else {/*from w w  w  . j a v a2  s  .c o  m*/
        authorizationFuture = CompletableFuture.completedFuture(true);
    }
    final String topicName = subscribe.getTopic();
    final String subscriptionName = subscribe.getSubscription();
    final long requestId = subscribe.getRequestId();
    final long consumerId = subscribe.getConsumerId();
    final SubType subType = subscribe.getSubType();
    final String consumerName = subscribe.getConsumerName();
    final boolean isDurable = subscribe.getDurable();
    final MessageIdImpl startMessageId = subscribe.hasStartMessageId()
            ? new MessageIdImpl(subscribe.getStartMessageId().getLedgerId(),
                    subscribe.getStartMessageId().getEntryId(), subscribe.getStartMessageId().getPartition())
            : null;

    final int priorityLevel = subscribe.hasPriorityLevel() ? subscribe.getPriorityLevel() : 0;

    authorizationFuture.thenApply(isAuthorized -> {
        if (isAuthorized) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Client is authorized to subscribe with role {}", remoteAddress, authRole);
            }

            log.info("[{}] Subscribing on topic {} / {}", remoteAddress, topicName, subscriptionName);

            CompletableFuture<Consumer> consumerFuture = new CompletableFuture<>();
            CompletableFuture<Consumer> existingConsumerFuture = consumers.putIfAbsent(consumerId,
                    consumerFuture);

            if (existingConsumerFuture != null) {
                if (existingConsumerFuture.isDone() && !existingConsumerFuture.isCompletedExceptionally()) {
                    Consumer consumer = existingConsumerFuture.getNow(null);
                    log.info("[{}] Consumer with the same id is already created: {}", remoteAddress, consumer);
                    ctx.writeAndFlush(Commands.newSuccess(requestId));
                    return null;
                } else {
                    // There was an early request to create a consumer with same consumerId. This can happen when
                    // client timeout is lower the broker timeouts. We need to wait until the previous consumer
                    // creation request either complete or fails.
                    log.warn("[{}][{}][{}] Consumer is already present on the connection", remoteAddress,
                            topicName, subscriptionName);
                    ServerError error = !existingConsumerFuture.isDone() ? ServerError.ServiceNotReady
                            : getErrorCode(existingConsumerFuture);
                    ctx.writeAndFlush(Commands.newError(requestId, error,
                            "Consumer is already present on the connection"));
                    return null;
                }
            }

            service.getTopic(topicName).thenCompose(topic -> topic.subscribe(ServerCnx.this, subscriptionName,
                    consumerId, subType, priorityLevel, consumerName, isDurable, startMessageId))
                    .thenAccept(consumer -> {
                        if (consumerFuture.complete(consumer)) {
                            log.info("[{}] Created subscription on topic {} / {}", remoteAddress, topicName,
                                    subscriptionName);
                            ctx.writeAndFlush(Commands.newSuccess(requestId), ctx.voidPromise());
                        } else {
                            // The consumer future was completed before by a close command
                            try {
                                consumer.close();
                                log.info("[{}] Cleared consumer created after timeout on client side {}",
                                        remoteAddress, consumer);
                            } catch (BrokerServiceException e) {
                                log.warn(
                                        "[{}] Error closing consumer created after timeout on client side {}: {}",
                                        remoteAddress, consumer, e.getMessage());
                            }
                            consumers.remove(consumerId, consumerFuture);
                        }

                    }) //
                    .exceptionally(exception -> {
                        log.warn("[{}][{}][{}] Failed to create consumer: {}", remoteAddress, topicName,
                                subscriptionName, exception.getCause().getMessage(), exception);

                        // If client timed out, the future would have been completed by subsequent close. Send error
                        // back to client, only if not completed already.
                        if (consumerFuture.completeExceptionally(exception)) {
                            ctx.writeAndFlush(Commands.newError(requestId,
                                    BrokerServiceException.getClientErrorCode(exception.getCause()),
                                    exception.getCause().getMessage()));
                        }
                        consumers.remove(consumerId, consumerFuture);

                        return null;

                    });
        } else {
            String msg = "Client is not authorized to subscribe";
            log.warn("[{}] {} with role {}", remoteAddress, msg, authRole);
            ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg));
        }
        return null;
    });
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

@Override
public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) {

    CompletableFuture<HttpResponse> promise = new CompletableFuture<>();
    URI uri;// w  w w  .  j ava 2  s . co m
    HttpRequestBase hcRequest;
    try {
        if (request.getMethod() == HttpMethod.POST) {
            uri = new URIBuilder(request.getUrl().toASCIIString()).build();
            hcRequest = new HttpPost(uri);
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            request.getQueryParams().entrySet()
                    .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue())));
            ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters));

        } else {
            uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams()
                    .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
                    .collect(Collectors.toList())).build();
            hcRequest = new HttpGet(uri);
        }
    } catch (URISyntaxException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue()));

    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

        hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() {

            public void completed(final HttpResponse hcResponse) {
                int statusCode = hcResponse.getStatusLine().getStatusCode();
                logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request);
                promise.complete(hcResponse);
            }

            public void failed(final Exception ex) {
                logger.debug("HTTP REQ FAILED " + request);
                logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage());
                promise.completeExceptionally(ex);
            }

            public void cancelled() {
                promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request));
            }
        });
        return null;
    });

    return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> {
        try {
            return hcResp.getEntity().getContent();
        } catch (IOException e) {
            throw new RuntimeException("Cannot read content", e);
        }
    }));

}

From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java

@Override
public ManagementFuture<Boolean> updateObjectBySpec(final QueryComponent<DataBucketStatusBean> unique_spec,
        final Optional<Boolean> upsert, final UpdateComponent<DataBucketStatusBean> update) {
    final MethodNamingHelper<DataBucketStatusBean> helper = BeanTemplateUtils.from(DataBucketStatusBean.class);

    if (upsert.orElse(false)) {
        throw new RuntimeException("This method is not supported with upsert set and true");
    }/*from  ww  w .  j  a v  a 2  s.  c  om*/

    final Collection<BasicMessageBean> errors = validateUpdateCommand(update);
    if (!errors.isEmpty()) {
        return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(false),
                CompletableFuture.completedFuture(errors));
    }

    // Now perform the update and based on the results we may need to send out instructions
    // to any listening buckets

    final CompletableFuture<Optional<DataBucketStatusBean>> update_reply = _underlying_data_bucket_status_db
            .get().updateAndReturnObjectBySpec(unique_spec, Optional.of(false), update, Optional.of(false),
                    Arrays.asList(helper.field(DataBucketStatusBean::_id),
                            helper.field(DataBucketStatusBean::confirmed_suspended),
                            helper.field(DataBucketStatusBean::confirmed_multi_node_enabled),
                            helper.field(DataBucketStatusBean::confirmed_master_enrichment_type),
                            helper.field(DataBucketStatusBean::suspended),
                            helper.field(DataBucketStatusBean::quarantined_until),
                            helper.field(DataBucketStatusBean::node_affinity)),
                    true);

    try {
        // What happens now depends on the contents of the message         

        // Maybe the user wanted to suspend/resume the bucket:

        final CompletableFuture<Collection<BasicMessageBean>> suspend_future = Lambdas
                .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> {
                    if (update.getAll().containsKey(helper.field(DataBucketStatusBean::suspended))) {

                        // (note this handles suspending the bucket if no handlers are available)
                        return getOperationFuture(update_reply, sb -> sb.suspended(),
                                _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(),
                                _actor_context, _bucket_action_retry_store.get());
                    } else { // (this isn't an error, just nothing to do here)
                        return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList());
                    }
                });

        // Maybe the user wanted to set quarantine on/off:

        final CompletableFuture<Collection<BasicMessageBean>> quarantine_future = Lambdas
                .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> {
                    if (update.getAll().containsKey(helper.field(DataBucketStatusBean::quarantined_until))) {

                        // (note this handles suspending the bucket if no handlers are available)
                        return getOperationFuture(update_reply, sb -> { // (this predicate is slightly more complex)
                            return (null != sb.quarantined_until())
                                    || (new Date().getTime() < sb.quarantined_until().getTime());
                        }, _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(),
                                _actor_context, _bucket_action_retry_store.get());
                    } else { // (this isn't an error, just nothing to do here)
                        return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList());
                    }
                });

        return FutureUtils.createManagementFuture(update_reply.thenApply(o -> o.isPresent()), // whether we updated
                suspend_future.thenCombine(quarantine_future,
                        (f1, f2) -> Stream.concat(f1.stream(), f2.stream()).collect(Collectors.toList())));
        //(+combine error messages from suspend/quarantine operations)
    } catch (Exception e) {
        // This is a serious enough exception that we'll just leave here
        return FutureUtils.createManagementFuture(FutureUtils.returnError(e));
    }
}