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:io.pravega.controller.store.stream.InMemoryStream.java

private void handleStreamMetadataExists(final long timestamp, CompletableFuture<CreateStreamResponse> result,
        final long time, final StreamConfiguration config, Data<Integer> currentState) {
    if (currentState != null) {
        State stateVal = (State) SerializationUtils.deserialize(currentState.getData());
        if (stateVal.equals(State.UNKNOWN) || stateVal.equals(State.CREATING)) {
            CreateStreamResponse.CreateStatus status;
            status = (time == timestamp) ? CreateStreamResponse.CreateStatus.NEW
                    : CreateStreamResponse.CreateStatus.EXISTS_CREATING;
            result.complete(new CreateStreamResponse(status, config, time));
        } else {//  w ww.ja va 2  s  .c  o  m
            result.complete(
                    new CreateStreamResponse(CreateStreamResponse.CreateStatus.EXISTS_ACTIVE, config, time));
        }
    } else {
        CreateStreamResponse.CreateStatus status = (time == timestamp) ? CreateStreamResponse.CreateStatus.NEW
                : CreateStreamResponse.CreateStatus.EXISTS_CREATING;

        result.complete(new CreateStreamResponse(status, config, time));
    }
}

From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

public MagicCommandOutput time(String codeToExecute, Message message, int executionCount, boolean showResult) {
    CompletableFuture<TimeMeasureData> compileTime = new CompletableFuture<>();

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    long currentThreadId = Thread.currentThread().getId();

    Long startWallTime = System.nanoTime();
    Long startCpuTotalTime = threadMXBean.getCurrentThreadCpuTime();
    Long startUserTime = threadMXBean.getCurrentThreadUserTime();

    SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel, message,
            executionCount);/* w  ww  . j  a  v a2s . co m*/
    if (!showResult) {
        simpleEvaluationObject.noResult();
    }

    TryResult either = kernel.executeCode(codeToExecute, simpleEvaluationObject);

    Long endWallTime = System.nanoTime();
    Long endCpuTotalTime = threadMXBean.getThreadCpuTime(currentThreadId);
    Long endUserTime = threadMXBean.getThreadUserTime(currentThreadId);

    compileTime.complete(new TimeMeasureData(endCpuTotalTime - startCpuTotalTime, endUserTime - startUserTime,
            endWallTime - startWallTime));
    String messageInfo = "CPU times: user %s, sys: %s, total: %s \nWall Time: %s\n";

    try {
        TimeMeasureData timeMeasuredData = compileTime.get();

        return new MagicCommandOutput(MagicCommandOutput.Status.OK,
                String.format(messageInfo, format(timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime() - timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime()), format(timeMeasuredData.getWallTime())),
                either, simpleEvaluationObject);

    } catch (InterruptedException | ExecutionException e) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "There occurs problem during measuring time for your statement.");
    }
}

From source file:org.apache.bookkeeper.bookie.BookieWriteToJournalTest.java

/**
 * test that Bookie calls correctly Journal.forceLedger and is able to return the correct LastAddPersisted entry id.
 *///  www  . j a v a2 s .c om
@Test
public void testForceLedger() throws Exception {

    File journalDir = tempDir.newFolder();
    Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir));
    File ledgerDir = tempDir.newFolder();
    Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(ledgerDir));
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
    conf.setJournalDirName(journalDir.getPath()).setLedgerDirNames(new String[] { ledgerDir.getPath() });

    Bookie b = new Bookie(conf);
    b.start();

    long ledgerId = 1;
    long entryId = 0;
    Object expectedCtx = "foo";
    byte[] masterKey = new byte[64];

    CompletableFuture<Long> latchForceLedger1 = new CompletableFuture<>();
    CompletableFuture<Long> latchForceLedger2 = new CompletableFuture<>();
    CompletableFuture<Long> latchAddEntry = new CompletableFuture<>();
    final ByteBuf data = buildEntry(ledgerId, entryId, -1);
    final long expectedEntryId = entryId;
    b.forceLedger(ledgerId, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> {
        if (rc != BKException.Code.OK) {
            latchForceLedger1.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc));
            return;
        }
        complete(latchForceLedger1, null);
    }, expectedCtx);
    result(latchForceLedger1);

    b.addEntry(data, true /* ackBeforesync */,
            (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> {
                if (rc != BKException.Code.OK) {
                    latchAddEntry.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc));
                    return;
                }
                latchAddEntry.complete(entryId);
            }, expectedCtx, masterKey);
    assertEquals(expectedEntryId, result(latchAddEntry).longValue());

    // issue a new "forceLedger"
    b.forceLedger(ledgerId, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> {
        if (rc != BKException.Code.OK) {
            latchForceLedger2.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc));
            return;
        }
        complete(latchForceLedger2, null);
    }, expectedCtx);
    result(latchForceLedger2);

    b.shutdown();
}

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

@Override
CompletableFuture<Integer> createNewTransaction(final UUID txId, final long timestamp,
        final long leaseExpiryTime, final long maxExecutionExpiryTime, final long scaleGracePeriod) {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    createNewTransactionNode(txId, timestamp, leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod)
            .whenComplete((value, ex) -> {
                if (ex != null) {
                    if (ExceptionHelpers.getRealException(ex) instanceof StoreException.DataNotFoundException) {
                        FutureHelpers.completeAfter(() -> createNewTransactionNode(txId, timestamp,
                                leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod), future);
                    } else {
                        future.completeExceptionally(ex);
                    }/* w ww.j a  v  a  2s . co m*/
                } else {
                    future.complete(value);
                }
            });
    return future;
}

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

/**
 * Subscribes to a topic on the given connection, but does not alter the subscriber list.
 *
 * @param topic The topic to subscribe to.
 * @return Completes with true if successful. Exceptionally otherwise.
 *//*from   w ww.  java  2 s  .  c  o  m*/
protected CompletableFuture<Boolean> subscribeRaw(String topic) {
    logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host);
    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    try {
        MqttAsyncClient client = this.client;
        if (client != null && client.isConnected()) {
            client.subscribe(topic, qos, future, actionCallback);
        } else {
            future.complete(false);
        }
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        logger.info("Error subscribing to topic {}", topic, e);
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.java

private Future<Void> doAsync(Thunk task) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    Job job = new Job("Async task") {
        protected IStatus run(IProgressMonitor monitor) {
            try {
                task.call();/*ww  w. j av a  2s .c o  m*/
                result.complete(null);
            } catch (Throwable e) {
                result.completeExceptionally(e);
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
    return result;
}

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

private <T> CompletableFuture<T> getInformation(Class<T> infoType, InformationSubject subject, String detail) {
    CompletableFuture<T> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }/*from ww w  . j  a  va2  s  .  c om*/
    send(new InformationRequestMessage(subject, detail), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.InformationResponseMessage)) {
            InformationResponseMessage response = m.secureCast();
            Object value = response.getValue();
            if (!response.getResponseType().isCompatibleTo(infoType)) {
                future.completeExceptionally(new UnexpectedResultTypeException(value, infoType));
            } else {
                future.complete(infoType.cast(value));
            }
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

From source file:io.pravega.controller.server.SegmentHelper.java

/**
 * This method sends segment sealed message for the specified segment.
 * It owns up the responsibility of retrying the operation on failures until success.
 *
 * @param scope               stream scope
 * @param stream              stream name
 * @param segmentNumber       number of segment to be sealed
 * @param hostControllerStore host controller store
 * @param clientCF            connection factory
 * @return void/*  ww w . j  a va  2  s.  c om*/
 */
public CompletableFuture<Boolean> sealSegment(final String scope, final String stream, final int segmentNumber,
        final HostControllerStore hostControllerStore, final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.SEAL_SEGMENT;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override
        public void connectionDropped() {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped));
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost));
        }

        @Override
        public void segmentSealed(WireCommands.SegmentSealed segmentSealed) {
            result.complete(true);
        }

        @Override
        public void segmentIsSealed(WireCommands.SegmentIsSealed segmentIsSealed) {
            result.complete(true);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.SealSegment request = new WireCommands.SealSegment(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber));
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:io.pravega.client.stream.mock.MockController.java

private CompletableFuture<Void> abortTxSegment(UUID txId, Segment segment) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/* w w w.  j a  v a2 s  . com*/
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void transactionCommitted(TransactionCommitted transactionCommitted) {
            result.completeExceptionally(new RuntimeException("Transaction already committed."));
        }

        @Override
        public void transactionAborted(TransactionAborted transactionAborted) {
            result.complete(null);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    sendRequestOverNewConnection(new AbortTransaction(idGenerator.get(), segment.getScopedName(), txId),
            replyProcessor, result);
    return result;
}

From source file:io.pravega.controller.server.SegmentHelper.java

public CompletableFuture<UUID> createTransaction(final String scope, final String stream,
        final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final CompletableFuture<UUID> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.CREATE_TRANSACTION;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override//from  w ww.ja  v a  2 s .c o  m
        public void connectionDropped() {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped));
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost));
        }

        @Override
        public void transactionCreated(WireCommands.TransactionCreated transactionCreated) {
            result.complete(txId);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.CreateTransaction request = new WireCommands.CreateTransaction(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber), txId);
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}