Example usage for java.util.concurrent CompletableFuture get

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public T get() throws InterruptedException, ExecutionException 

Source Link

Document

Waits if necessary for this future to complete, and then returns its result.

Usage

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);//from  w  w  w  .  j av a2  s .  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.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public String createConnection() {
    CompletableFuture<String> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        DatabaseDialog databaseDialog = new DatabaseDialog(spoonSupplier.get().getShell(), new DatabaseMeta());
        databaseDialog.open();// w  ww  .j a  va  2s.  c o  m
        DatabaseMeta databaseMeta = databaseDialog.getDatabaseMeta();
        if (databaseMeta != null) {
            if (!isDatabaseWithNameExist(databaseMeta, true)) {
                addDatabase(databaseMeta);
                future.complete(databaseMeta.getName());
            } else {
                DatabaseDialog.showDatabaseExistsDialog(spoonSupplier.get().getShell(), databaseMeta);
            }
        }
        future.complete("None");
    });
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("name", future.get());
        return jsonObject.toJSONString();
    } catch (Exception e) {
        jsonObject.put("name", "None");
        return jsonObject.toJSONString();
    }
}

From source file:com.devicehive.resource.impl.DeviceCommandResourceImpl.java

/**
 * Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceCommand/wait">DeviceHive RESTful
 * API: DeviceCommand: wait</a>// w  w  w. j a  v a2s.c o  m
 *
 * @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable
 *                waiting.
 */
@Override
public void wait(final String deviceGuid, final String commandId, final long timeout,
        final AsyncResponse asyncResponse) {

    LOGGER.debug("DeviceCommand wait requested, deviceId = {},  commandId = {}", deviceGuid, commandId);

    asyncResponse.setTimeoutHandler(
            asyncRes -> asyncRes.resume(ResponseFactory.response(Response.Status.NO_CONTENT)));

    if (deviceGuid == null || commandId == null) {
        LOGGER.warn("DeviceCommand wait request failed. BAD REQUEST: deviceGuid and commandId required",
                deviceGuid);
        asyncResponse.resume(ResponseFactory.response(Response.Status.BAD_REQUEST));
        return;
    }

    DeviceVO device = deviceService.getDeviceWithNetworkAndDeviceClass(deviceGuid);

    if (device == null) {
        LOGGER.warn("DeviceCommand wait request failed. NOT FOUND: device {} not found", deviceGuid);
        asyncResponse.resume(ResponseFactory.response(Response.Status.NOT_FOUND));
        return;
    }

    Optional<DeviceCommand> command = commandService.findOne(Long.valueOf(commandId), device.getGuid()).join();

    if (!command.isPresent()) {
        LOGGER.warn(
                "DeviceCommand wait request failed. NOT FOUND: No command found with id = {} for deviceId = {}",
                commandId, deviceGuid);
        asyncResponse.resume(ResponseFactory.response(Response.Status.NO_CONTENT));
        return;
    }

    if (!command.get().getDeviceGuid().equals(device.getGuid())) {
        LOGGER.warn(
                "DeviceCommand wait request failed. BAD REQUEST: Command with id = {} was not sent for device with guid = {}",
                commandId, deviceGuid);
        asyncResponse.resume(ResponseFactory.response(Response.Status.BAD_REQUEST));
        return;
    }

    BiConsumer<DeviceCommand, String> callback = (com, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(Response.Status.OK, com, Policy.COMMAND_TO_DEVICE));
        }
    };

    if (!command.get().getIsUpdated()) {
        CompletableFuture<Pair<String, DeviceCommand>> future = commandService
                .sendSubscribeToUpdateRequest(Long.valueOf(commandId), deviceGuid, callback);
        future.thenAccept(pair -> {
            final DeviceCommand deviceCommand = pair.getRight();
            if (!asyncResponse.isDone() && deviceCommand.getIsUpdated()) {
                asyncResponse.resume(
                        ResponseFactory.response(Response.Status.OK, deviceCommand, Policy.COMMAND_TO_DEVICE));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });
        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable throwable) {
                try {
                    commandService.sendUnsubscribeRequest(future.get().getLeft(), null);
                } catch (InterruptedException | ExecutionException e) {
                    if (!asyncResponse.isDone()) {
                        asyncResponse.resume(ResponseFactory.response(Response.Status.INTERNAL_SERVER_ERROR));
                    }
                }
            }
        });
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(
                    ResponseFactory.response(Response.Status.OK, command.get(), Policy.COMMAND_TO_DEVICE));
        }
    }

}

From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public String editDatabaseConnection(String database) {
    CompletableFuture<String> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        DatabaseMeta databaseMeta = getDatabase(database);
        String originalName = databaseMeta.getName();
        DatabaseDialog databaseDialog = new DatabaseDialog(spoonSupplier.get().getShell(), databaseMeta);
        databaseDialog.open();/*from w  w  w . j ava2 s .c  o  m*/
        if (!isDatabaseWithNameExist(databaseMeta, false)) {
            save();
            future.complete(databaseMeta.getName());
        } else {
            DatabaseDialog.showDatabaseExistsDialog(spoonSupplier.get().getShell(), databaseMeta);
            databaseMeta.setName(originalName);
            databaseMeta.setDisplayName(originalName);
            future.complete(originalName);
        }
    });
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("name", future.get());
        return jsonObject.toJSONString();
    } catch (Exception e) {
        jsonObject.put("name", "None");
        return jsonObject.toJSONString();
    }
}

From source file:org.auraframework.modules.impl.ModulesCompilerJ2V8.java

private ModulesCompilerData compile(String entry, String options) throws Exception {
    String script = "" + "const compiler = require('" + ModulesCompilerUtil.COMPILER_JS_PATH + "');"
            + "const promise = compiler.compile('" + entry + "', " + options + ");"
            + "promise.then(onResultCallback).catch(onErrorCallback);";

    CompletableFuture<ModulesCompilerData> future = new CompletableFuture<>();

    JavaVoidCallback onErrorCallback = new JavaVoidCallback() {
        @Override/* w w  w. jav a  2 s.  c  om*/
        public void invoke(final V8Object receiver, final V8Array parameters) {
            String error = parameters.toString();
            future.completeExceptionally(new RuntimeException(error));
            logger.warning("ModulesCompilerJ2v8: error " + entry + ": " + error);
        }
    };
    JavaVoidCallback onResultCallback = new JavaVoidCallback() {
        @Override
        public void invoke(final V8Object receiver, final V8Array parameters) {
            ModulesCompilerData data = ModulesCompilerUtil.parseCompilerOutput(parameters.getObject(0));
            future.complete(data);
        }
    };

    NodeJS nodeJS = J2V8Util.createNodeJS();

    MemoryManager memoryManager = new MemoryManager(nodeJS.getRuntime());
    nodeJS.getRuntime().registerJavaMethod(onErrorCallback, "onErrorCallback");
    nodeJS.getRuntime().registerJavaMethod(onResultCallback, "onResultCallback");

    File tempScript = ModulesCompilerUtil.createTempScriptFile(script, "temp");
    try {
        nodeJS.exec(tempScript);
        while (nodeJS.isRunning()) {
            nodeJS.handleMessage();
        }
    } finally {
        memoryManager.release();
        nodeJS.release();
        tempScript.delete();
    }

    return future.get();
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

private boolean doArbitrationUpdate() {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    // TODO: currently we use 64-bit Long type for election id, should
    // we use 128-bit ?
    long nextElectId = controller.getNewMasterElectionId();
    Uint128 newElectionId = Uint128.newBuilder().setLow(nextElectId).build();
    MasterArbitrationUpdate arbitrationUpdate = MasterArbitrationUpdate.newBuilder().setDeviceId(p4DeviceId)
            .setElectionId(newElectionId).build();
    StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder().setArbitration(arbitrationUpdate)
            .build();/*from w ww. j  a va 2s.c  om*/
    log.debug("Sending arbitration update to {} with election id {}...", deviceId, newElectionId);
    arbitrationUpdateMap.put(newElectionId, result);
    try {
        streamRequestObserver.onNext(requestMsg);
        return result.get();
    } catch (StatusRuntimeException e) {
        log.error("Unable to perform arbitration update on {}: {}", deviceId, e.getMessage());
        arbitrationUpdateMap.remove(newElectionId);
        return false;
    } catch (InterruptedException | ExecutionException e) {
        log.warn("Arbitration update failed for {} due to {}", deviceId, e);
        arbitrationUpdateMap.remove(newElectionId);
        return false;
    }
}

From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java

/**
 * Test that when 2 updates loops try to make the same modification, and they
 * conflict on the write to the store, the one that receives the conflict won't
 * try to write again, as the value is now correct.
 *///from  www.j av a2 s.c  o  m
@Test
public void testConflictOnWriteBothWritingSame() throws Exception {
    try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) {
        lm.blockWrites();

        long ledgerId = 1234L;
        BookieSocketAddress b0 = new BookieSocketAddress("0.0.0.0:3181");
        BookieSocketAddress b1 = new BookieSocketAddress("0.0.0.1:3181");
        BookieSocketAddress b2 = new BookieSocketAddress("0.0.0.2:3181");

        LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(2)
                .withDigestType(DigestType.CRC32C).withPassword(new byte[0]).withWriteQuorumSize(2)
                .newEnsembleEntry(0L, Lists.newArrayList(b0, b1)).build();
        Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get();
        AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata);

        CompletableFuture<Versioned<LedgerMetadata>> loop1 = new MetadataUpdateLoop(lm, ledgerId,
                reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0),
                (currentMetadata) -> {
                    List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L));
                    ensemble.set(0, b2);
                    return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble)
                            .build();
                }, reference::compareAndSet).run();
        CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(lm, ledgerId,
                reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0),
                (currentMetadata) -> {
                    List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L));
                    ensemble.set(0, b2);
                    return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble)
                            .build();
                }, reference::compareAndSet).run();

        lm.releaseWrites();

        Assert.assertEquals(loop1.get(), loop2.get());
        Assert.assertEquals(loop1.get(), reference.get());

        Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2);
        Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b1);

        verify(lm, times(2)).writeLedgerMetadata(anyLong(), any(), any());
    }
}

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

@Test
@SuppressWarnings("unchecked")
public void testLedgerCreateByteBufRefCnt() throws Exception {
    final LedgerHandle lh = bkc.createLedger(5, 3, 2, digestType, ledgerPassword, null);

    final List<AbstractByteBufAllocator> allocs = Lists.newArrayList(new PooledByteBufAllocator(true),
            new PooledByteBufAllocator(false), new UnpooledByteBufAllocator(true),
            new UnpooledByteBufAllocator(false));

    int entryId = 0;
    for (AbstractByteBufAllocator alloc : allocs) {
        final ByteBuf data = alloc.buffer(10);
        data.writeBytes(("fragment0" + entryId).getBytes());
        assertEquals("ref count on ByteBuf should be 1", 1, data.refCnt());

        CompletableFuture<Integer> cf = new CompletableFuture<>();
        lh.asyncAddEntry(data, (rc, handle, eId, ctx) -> {
            CompletableFuture<Integer> future = (CompletableFuture<Integer>) ctx;
            future.complete(rc);/*from  w w w  . j  av  a 2 s.  co m*/
        }, cf);

        int rc = cf.get();
        assertEquals("rc code is OK", BKException.Code.OK, rc);

        for (int i = 0; i < 10; i++) {
            if (data.refCnt() == 0) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(250); // recycler runs asynchronously
        }
        assertEquals("writing entry with id " + entryId + ", ref count on ByteBuf should be 0 ", 0,
                data.refCnt());

        org.apache.bookkeeper.client.api.LedgerEntry e = lh.read(entryId, entryId).getEntry(entryId);
        assertEquals("entry data is correct", "fragment0" + entryId, new String(e.getEntryBytes()));
        entryId++;
    }

    bkc.deleteLedger(lh.ledgerId);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.TestElasticsearchIndexService.java

@Test
public void test_ageOut() throws IOException, InterruptedException, ExecutionException {

    // Call test_endToEnd_autoTime to create 5 time based indexes
    // 2015-01-01 -> 2015-05-01
    // How far is now from 2015-05-03
    final Date d = TimeUtils.getDateFromSuffix("2015.03.02").success();
    final long total_time_ms = new Date().getTime() - d.getTime();
    final long total_days = total_time_ms / (1000L * 3600L * 24L);
    final String age_out = ErrorUtils.get("{0} days", total_days);

    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with("full_name", "/test/end-end/auto-time")
            .with(DataBucketBean::data_schema,
                    BeanTemplateUtils.build(DataSchemaBean.class)
                            .with(DataSchemaBean::temporal_schema,
                                    BeanTemplateUtils.build(TemporalSchemaBean.class)
                                            .with(TemporalSchemaBean::exist_age_max, age_out).done().get())
                            .done().get())
            .done().get();//w  w  w.  ja  v a2s  .com

    final String template_name = ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty());

    test_endToEnd_autoTime(false, Optional.empty());

    _index_service._crud_factory.getClient().admin().indices().prepareCreate(template_name + "_2015.03.01_1")
            .execute().actionGet();

    final GetMappingsResponse gmr = _index_service._crud_factory.getClient().admin().indices()
            .prepareGetMappings(template_name + "*").execute().actionGet();
    assertEquals(6, gmr.getMappings().keys().size());

    CompletableFuture<BasicMessageBean> cf = _index_service.getDataService().get().handleAgeOutRequest(bucket);

    BasicMessageBean res = cf.get();

    assertEquals(true, res.success());
    assertTrue("sensible message: " + res.message(), res.message().contains(" 2 "));

    assertTrue("Message marked as loggable: " + res.details(),
            Optional.ofNullable(res.details()).filter(m -> m.containsKey("loggable")).isPresent());

    System.out.println("Return from to delete: " + res.message());

    Thread.sleep(5000L); // give the indexes time to delete

    final GetMappingsResponse gmr2 = _index_service._crud_factory.getClient().admin().indices()
            .prepareGetMappings(template_name + "*").execute().actionGet();
    assertEquals(3, gmr2.getMappings().keys().size());

    // Check some edge cases:

    // 1) Run it again, returns success but not loggable:

    CompletableFuture<BasicMessageBean> cf2 = _index_service.getDataService().get().handleAgeOutRequest(bucket);

    BasicMessageBean res2 = cf2.get();

    assertEquals(true, res2.success());
    assertTrue("sensible message: " + res2.message(), res2.message().contains(" 0 "));
    assertTrue("Message _not_ marked as loggable: " + res2.details(),
            !Optional.ofNullable(res2.details()).map(m -> m.get("loggable")).isPresent());

    // 2) No temporal settings

    final DataBucketBean bucket3 = BeanTemplateUtils.build(DataBucketBean.class)
            .with("full_name", "/test/handle/age/out/delete/not/temporal")
            .with(DataBucketBean::data_schema, BeanTemplateUtils.build(DataSchemaBean.class).done().get())
            .done().get();

    CompletableFuture<BasicMessageBean> cf3 = _index_service.getDataService().get()
            .handleAgeOutRequest(bucket3);
    BasicMessageBean res3 = cf3.get();
    // no temporal settings => returns success
    assertEquals(true, res3.success());

    // 3) Unparseable temporal settings (in theory won't validate but we can test here)

    final DataBucketBean bucket4 = BeanTemplateUtils.build(DataBucketBean.class)
            .with("full_name", "/test/handle/age/out/delete/temporal/malformed")
            .with(DataBucketBean::data_schema,
                    BeanTemplateUtils.build(DataSchemaBean.class)
                            .with(DataSchemaBean::temporal_schema,
                                    BeanTemplateUtils.build(TemporalSchemaBean.class)
                                            .with(TemporalSchemaBean::exist_age_max, "bananas").done().get())
                            .done().get())
            .done().get();

    CompletableFuture<BasicMessageBean> cf4 = _index_service.getDataService().get()
            .handleAgeOutRequest(bucket4);
    BasicMessageBean res4 = cf4.get();
    // no temporal settings => returns success
    assertEquals(false, res4.success());
}