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:org.apache.distributedlog.lock.ZKSessionLock.java

@Override
public CompletableFuture<LockWaiter> asyncTryLock(final long timeout, final TimeUnit unit) {
    final CompletableFuture<String> result = new CompletableFuture<String>();
    final boolean wait = DistributedLogConstants.LOCK_IMMEDIATE != timeout;
    if (wait) {//  w ww  .j  a  va2 s.  c om
        asyncTryLock(wait, result);
    } else {
        // try to check locks first
        zk.getChildren(lockPath, null, new AsyncCallback.Children2Callback() {
            @Override
            public void processResult(final int rc, String path, Object ctx, final List<String> children,
                    Stat stat) {
                lockStateExecutor.executeOrdered(lockPath, new SafeRunnable() {
                    @Override
                    public void safeRun() {
                        if (!lockState.inState(State.INIT)) {
                            result.completeExceptionally(new LockStateChangedException(lockPath, lockId,
                                    State.INIT, lockState.getState()));
                            return;
                        }
                        if (KeeperException.Code.OK.intValue() != rc) {
                            result.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
                            return;
                        }

                        FailpointUtils.checkFailPointNoThrow(FailpointUtils.FailPointName.FP_LockTryAcquire);

                        Collections.sort(children, MEMBER_COMPARATOR);
                        if (children.size() > 0) {
                            asyncParseClientID(zk, lockPath, children.get(0))
                                    .whenCompleteAsync(new FutureEventListener<Pair<String, Long>>() {
                                        @Override
                                        public void onSuccess(Pair<String, Long> owner) {
                                            if (!checkOrClaimLockOwner(owner, result)) {
                                                acquireFuture.complete(false);
                                            }
                                        }

                                        @Override
                                        public void onFailure(final Throwable cause) {
                                            result.completeExceptionally(cause);
                                        }
                                    }, lockStateExecutor.chooseThread(lockPath));
                        } else {
                            asyncTryLock(wait, result);
                        }
                    }
                });
            }
        }, null);
    }

    final CompletableFuture<Boolean> waiterAcquireFuture = FutureUtils.createFuture();
    waiterAcquireFuture.whenComplete((value, cause) -> acquireFuture.completeExceptionally(cause));
    return result.thenApply(new Function<String, LockWaiter>() {
        @Override
        public LockWaiter apply(final String currentOwner) {
            final Exception acquireException = new OwnershipAcquireFailedException(lockPath, currentOwner);
            FutureUtils.within(acquireFuture, timeout, unit, acquireException, lockStateExecutor, lockPath)
                    .whenComplete(new FutureEventListener<Boolean>() {

                        @Override
                        public void onSuccess(Boolean acquired) {
                            completeOrFail(acquireException);
                        }

                        @Override
                        public void onFailure(final Throwable acquireCause) {
                            completeOrFail(acquireException);
                        }

                        private void completeOrFail(final Throwable acquireCause) {
                            if (isLockHeld()) {
                                waiterAcquireFuture.complete(true);
                            } else {
                                asyncUnlock().whenComplete(new FutureEventListener<Void>() {
                                    @Override
                                    public void onSuccess(Void value) {
                                        waiterAcquireFuture.completeExceptionally(acquireCause);
                                    }

                                    @Override
                                    public void onFailure(Throwable cause) {
                                        waiterAcquireFuture.completeExceptionally(acquireCause);
                                    }
                                });
                            }
                        }
                    });
            return new LockWaiter(lockId.getLeft(), currentOwner, waiterAcquireFuture);
        }
    });
}

From source file:org.apache.james.mailbox.cassandra.mail.AttachmentLoader.java

@VisibleForTesting
CompletableFuture<List<MessageAttachment>> getAttachments(
        List<MessageAttachmentRepresentation> attachmentRepresentations) {
    CompletableFuture<Map<AttachmentId, Attachment>> attachmentsByIdFuture = attachmentsById(
            attachmentRepresentations.stream().map(MessageAttachmentRepresentation::getAttachmentId)
                    .collect(Guavate.toImmutableSet()));

    return attachmentsByIdFuture.thenApply(attachmentsById -> attachmentRepresentations.stream()
            .map(representation -> constructMessageAttachment(
                    attachmentsById.get(representation.getAttachmentId()), representation))
            .collect(Guavate.toImmutableList()));
}

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

@Override
public Future<Map<ByteBuffer, ByteBuffer>> get(Collection<ByteBuffer> keys,
        Callback<Map<ByteBuffer, ByteBuffer>> callback) {
    CompletableFuture<Void> endFuture = new CompletableFuture<>();
    readToEnd(endFuture);/*from  w w  w  .  j  a va 2  s .  co  m*/
    return endFuture.thenApply(ignored -> {
        Map<ByteBuffer, ByteBuffer> values = new HashMap<>();
        for (ByteBuffer key : keys) {
            ByteBuffer value;
            synchronized (data) {
                value = data.get(key);
            }
            if (null != value) {
                values.put(key, value);
            }
        }
        if (null != callback) {
            callback.onCompletion(null, values);
        }
        return values;
    }).whenComplete((ignored, cause) -> {
        if (null != cause && null != callback) {
            callback.onCompletion(cause, null);
        }
    });
}

From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java

/**
 * Unsubscribes from all subscribed topics, stops the reconnect strategy, disconnect and close the client.
 *
 * You can re-establish a connection calling {@link #start()} again. Do not call start, before the closing process
 * has finished completely./*from   w  w w . j a  va  2  s  .c  o m*/
 *
 * @return Returns a future that completes as soon as the disconnect process has finished.
 */
public CompletableFuture<Boolean> stop() {
    MqttAsyncClient client = this.client;
    if (client == null) {
        return CompletableFuture.completedFuture(true);
    }

    logger.trace("Closing the MQTT broker connection '{}'", host);

    // Abort a connection attempt
    isConnecting = false;

    // Cancel the timeout future. If stop is called we can safely assume there is no interest in a connection
    // anymore.
    cancelTimeoutFuture();

    // Stop the reconnect strategy
    if (reconnectStrategy != null) {
        reconnectStrategy.stop();
    }

    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    // Close connection
    if (client.isConnected()) {
        // We need to thread change here. Because paho does not allow to disconnect within a callback method
        unsubscribeAll().thenRunAsync(() -> {
            try {
                client.disconnect(100).waitForCompletion(100);
                if (client.isConnected()) {
                    client.disconnectForcibly();
                }
                future.complete(true);
            } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
                logger.debug("Error while closing connection to broker", e);
                future.complete(false);
            }
        });
    } else {
        future.complete(true);
    }

    return future.thenApply(this::finalizeStopAfterDisconnect);
}

From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java

public void runFabricTest(final SampleStore sampleStore) throws Exception {

    ////////////////////////////
    // Setup client

    //Create instance of client.
    HFClient client = HFClient.createNewInstance();

    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

    ////////////////////////////
    //Construct and run the channels
    final Collection<CompletableFuture<BlockEvent.TransactionEvent>> futures = new ArrayList<>(2);
    //  CompletableFuture<BlockEvent.TransactionEvent>[] ii = new CompletableFuture[2];
    SampleOrg sampleOrg1 = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
    Channel fooChannel = constructChannel(FOO_CHANNEL_NAME, client, sampleOrg1);
    futures.add(installInstantiate(fooChannel, client, sampleOrg1));

    SampleOrg sampleOrg2 = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
    Channel barChannel = constructChannel(BAR_CHANNEL_NAME, client, sampleOrg2);
    futures.add(installInstantiate(barChannel, client, sampleOrg2));

    final CompletableFuture<Void> voidCompletableFuture = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()]));
    voidCompletableFuture.thenApply(avoid -> {

        ArrayList<Thread> threads = new ArrayList<>();
        TestPair[] testPairs = { new TestPair(fooChannel, sampleOrg1), new TestPair(barChannel, sampleOrg2) };

        for (int i = 0; i < WORKER_COUNT; ++i) {

            Thread thread = new Thread(new Worker(i, client, testPairs));
            thread.setName("TCW_" + i);
            thread.setDaemon(true);//from w ww .jav a2  s.com
            thread.start();

            threads.add(thread);

            try {
                Thread.sleep(random.nextInt(3000)); // stage them to be doing different tasks
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        threads.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        return null;

    }).get();

    //        voidCompletableFuture.thenApply(() -> futures.stream()
    //                .map(CompletableFuture::join)
    //                .collect(Collectors.toList())
    //        );
    //
    //        CompletableFuture<BlockEvent.TransactionEvent>.allOf (futures.toArray())
    //                .thenApply(() -> futures.stream()
    //                        .map(CompletableFuture::join)
    //                        .collect(Collectors.toList())
    //                );

    //        //let bar channel just shutdown so we have both scenarios.
    //
    //        out("\nTraverse the blocks for chain %s ", barChannel.getName());
    //
    //        blockWalker(client, barChannel);
    //
    //        assertFalse(barChannel.isShutdown());
    //        assertTrue(barChannel.isInitialized());

    out("That's all folks!");

}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletableFuture<EvalNode> processNotNode(ExpAstNode expNode, Context context) {
    CompletableFuture<EvalNode> nodeFuture = evaluateNode(expNode.getNode(0), context);
    return nodeFuture.thenApply(n -> new BooleanEvalNode(!nodeAsBoolean(n)));
}

From source file:ru.histone.v2.evaluator.Evaluator.java

/**
 * [AST_ID, MACRO_BODY, NUM_OF_VARS, VARS...]
 *//*w ww. j  a v a 2s.  co m*/
private CompletableFuture<EvalNode> processMacroNode(ExpAstNode node, Context context) {
    final int bodyIndex = 0;
    final int startVarIndex = 2;
    final CompletableFuture<List<AstNode>> astArgsFuture = CompletableFuture
            .completedFuture(node.size() < startVarIndex ? Collections.<AstNode>emptyList()
                    : node.getNodes().subList(startVarIndex, node.size()));
    final CompletableFuture<List<String>> argsFuture = astArgsFuture
            .thenApply(astNodes -> astNodes.stream().map(x -> {
                final StringAstNode nameNode = ((ExpAstNode) x).getNode(0);
                return nameNode.getValue();
            }).collect(Collectors.toList()));
    return argsFuture.thenApply(args -> {
        final AstNode body = node.getNode(bodyIndex);
        return new MacroEvalNode(new HistoneMacro(args, body, context, Evaluator.this));
    });
}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletableFuture<EvalNode> getEvaluatedString(Context context, CompletableFuture<List<EvalNode>> res) {
    return res.thenApply(nodes -> {
        Optional<EvalNode> rNode = nodes.stream().filter(EvalNode::isReturn).findFirst();
        List<EvalNode> nodesToProcess = nodes;
        if (rNode.isPresent()) {
            nodesToProcess = Collections.singletonList(rNode.get());
        }/*ww  w .  j ava2 s.  c  om*/
        EvalNode result = new StringEvalNode(nodesToProcess.stream()
                .map(n -> context.call(n, TO_STRING_FUNC_NAME, Collections.singletonList(n)))
                .map(CompletableFuture::join).map(n -> n.getValue() + "").collect(Collectors.joining()));
        if (rNode.isPresent()) {
            result.setIsReturn();
        }
        return result;

    });
}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletableFuture<EvalNode> processArithmetical(ExpAstNode node, Context context) {
    CompletableFuture<List<EvalNode>> leftRightDone = evalAllNodesOfCurrent(node, context);
    return leftRightDone.thenApply(futures -> {
        EvalNode left = futures.get(0);//from   ww w  . j  a  v  a2  s. c  o m
        EvalNode right = futures.get(1);

        if ((isNumberNode(left) || left instanceof StringEvalNode)
                && (isNumberNode(right) || right instanceof StringEvalNode)) {
            Float leftValue = getValue(left).orElse(null);
            Float rightValue = getValue(right).orElse(null);
            if (leftValue == null || rightValue == null) {
                return EmptyEvalNode.INSTANCE;
            }

            Float res;
            AstType type = node.getType();
            if (type == AstType.AST_SUB) {
                res = leftValue - rightValue;
            } else if (type == AstType.AST_MUL) {
                res = leftValue * rightValue;
            } else if (type == AstType.AST_DIV) {
                res = leftValue / rightValue;
            } else {
                res = leftValue % rightValue;
            }
            if (res % 1 == 0 && res <= Long.MAX_VALUE) {
                return new LongEvalNode(res.longValue());
            } else {
                return new FloatEvalNode(res);
            }
        }
        return EmptyEvalNode.INSTANCE;
    });
}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletableFuture<EvalNode> processRelation(ExpAstNode node, Context context) {
    CompletableFuture<List<EvalNode>> leftRightDone = evalAllNodesOfCurrent(node, context);
    return leftRightDone.thenApply(f -> {
        EvalNode left = f.get(0);/*from www . j av  a2s  .  c o  m*/
        EvalNode right = f.get(1);

        final Integer compareResult;
        if (left instanceof StringEvalNode && isNumberNode(right)) {
            final Number rightValue = getNumberValue(right);
            final StringEvalNode stringLeft = (StringEvalNode) left;
            if (isNumeric(stringLeft)) {
                final Number leftValue = getNumberValue(stringLeft);
                compareResult = NUMBER_COMPARATOR.compare(leftValue, rightValue);
            } else {
                throw new NotImplementedException(); // TODO call RTTI toString right
            }
        } else if (isNumberNode(left) && right instanceof StringEvalNode) {
            final StringEvalNode stringRight = (StringEvalNode) right;
            if (isNumeric(stringRight)) {
                final Number rightValue = getNumberValue(right);
                final Number leftValue = getNumberValue(left);
                compareResult = NUMBER_COMPARATOR.compare(leftValue, rightValue);
            } else {
                throw new NotImplementedException(); // TODO call RTTI toString left
            }
        } else if (!isNumberNode(left) || !isNumberNode(right)) {
            if (left instanceof StringEvalNode && right instanceof StringEvalNode) {
                final StringEvalNode stringRight = (StringEvalNode) right;
                final StringEvalNode stringLeft = (StringEvalNode) left;
                final long leftLength = stringLeft.getValue().length();
                final long rightLength = stringRight.getValue().length();
                compareResult = Long.valueOf(leftLength).compareTo(rightLength);
            } else {
                throw new NotImplementedException(); // TODO call RTTI toBoolean for both nodes
            }
        } else {
            final Number rightValue = getNumberValue(right);
            final Number leftValue = getNumberValue(left);
            compareResult = NUMBER_COMPARATOR.compare(leftValue, rightValue);
        }

        return processRelationHelper(node.getType(), compareResult);
    });
}