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:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testAbortTransaction() throws Exception {
    CompletableFuture<Void> transaction;
    transaction = controllerClient.abortTransaction(new StreamImpl("scope1", "stream1"), UUID.randomUUID());
    assertTrue(transaction.get() == null);

    transaction = controllerClient.abortTransaction(new StreamImpl("scope1", "stream2"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.abortTransaction(new StreamImpl("scope1", "stream3"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.abortTransaction(new StreamImpl("scope1", "stream4"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.abortTransaction(new StreamImpl("scope1", "stream5"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testCommitTransaction() throws Exception {
    CompletableFuture<Void> transaction;
    transaction = controllerClient.commitTransaction(new StreamImpl("scope1", "stream1"), UUID.randomUUID());
    assertTrue(transaction.get() == null);

    transaction = controllerClient.commitTransaction(new StreamImpl("scope1", "stream2"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.commitTransaction(new StreamImpl("scope1", "stream3"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.commitTransaction(new StreamImpl("scope1", "stream4"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.commitTransaction(new StreamImpl("scope1", "stream5"), UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testCreateTransaction() throws Exception {
    CompletableFuture<TxnSegments> transaction;
    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream1"), 0, 0, 0);
    assertEquals(new UUID(11L, 22L), transaction.get().getTxnId());
    assertEquals(2, transaction.get().getSteamSegments().getSegments().size());
    assertEquals(new Segment("scope1", "stream1", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.2));
    assertEquals(new Segment("scope1", "stream1", 1),
            transaction.get().getSteamSegments().getSegmentForKey(.8));

    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream2"), 0, 0, 0);
    assertEquals(new UUID(33L, 44L), transaction.get().getTxnId());
    assertEquals(1, transaction.get().getSteamSegments().getSegments().size());
    assertEquals(new Segment("scope1", "stream2", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.2));
    assertEquals(new Segment("scope1", "stream2", 0),
            transaction.get().getSteamSegments().getSegmentForKey(.8));

    transaction = controllerClient.createTransaction(new StreamImpl("scope1", "stream3"), 0, 0, 0);
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);
}

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

/**
 * Test that when 2 update loops both manage to write, but conflict on
 * updating the local value.//from  w w w.j  ava 2  s. c o m
 */
@Test
public void testConflictOnLocalUpdate() throws Exception {
    try (DeferCallbacksMockLedgerManager lm = spy(new DeferCallbacksMockLedgerManager(1))) {
        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");
        BookieSocketAddress b3 = new BookieSocketAddress("0.0.0.3: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();

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

        lm.runDeferred();

        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), b3);

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

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testGetURI() throws Exception {
    CompletableFuture<PravegaNodeUri> endpointForSegment;
    endpointForSegment = controllerClient.getEndpointForSegment("scope1/stream1/0");
    assertEquals(new PravegaNodeUri("localhost", SERVICE_PORT), endpointForSegment.get());

    endpointForSegment = controllerClient.getEndpointForSegment("scope1/stream2/0");
    AssertExtensions.assertThrows("Should throw Exception", endpointForSegment, throwable -> true);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testParallelGetCurrentSegments() throws Exception {
    final ExecutorService executorService = Executors.newFixedThreadPool(10);
    Semaphore createCount = new Semaphore(-19);
    AtomicBoolean success = new AtomicBoolean(true);
    for (int i = 0; i < 10; i++) {
        executorService.submit(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    CompletableFuture<StreamSegments> streamSegments;
                    streamSegments = controllerClient.getCurrentSegments("scope1", "streamparallel");
                    assertTrue(streamSegments.get().getSegments().size() == 2);
                    assertEquals(new Segment("scope1", "streamparallel", 0),
                            streamSegments.get().getSegmentForKey(0.2));
                    assertEquals(new Segment("scope1", "streamparallel", 1),
                            streamSegments.get().getSegmentForKey(0.6));
                    createCount.release();
                } catch (Exception e) {
                    log.error("Exception when getting segments: {}", e);

                    // Don't wait for other threads to complete.
                    success.set(false);//w  w  w.  ja v a2s  .c o  m
                    createCount.release(20);
                }
            }
        });
    }
    createCount.acquire();
    executorService.shutdownNow();
    assertTrue(success.get());
}

From source file:org.apache.geode.internal.cache.BackupDUnitTest.java

/**
 * Test for bug 42419/*from   w  ww  .  j a va 2  s . c o m*/
 */
@Test
public void testBackupWhileBucketIsCreated() throws Throwable {
    Host host = Host.getHost(0);
    vm0 = host.getVM(0);
    vm1 = host.getVM(1);
    final VM vm2 = host.getVM(2);

    logger.info("Creating region in VM0");
    createPersistentRegion(vm0);

    // create a bucket on vm0
    createData(vm0, 0, 1, "A", "region1");

    // create the pr on vm1, which won't have any buckets
    logger.info("Creating region in VM1");
    createPersistentRegion(vm1);

    CompletableFuture<BackupStatus> backupStatusFuture = CompletableFuture.supplyAsync(() -> backup(vm2));
    CompletableFuture<Void> createDataFuture = CompletableFuture
            .runAsync(() -> createData(vm0, 1, 5, "A", "region1"));
    CompletableFuture.allOf(backupStatusFuture, createDataFuture);

    BackupStatus status = backupStatusFuture.get();
    assertEquals(2, status.getBackedUpDiskStores().size());
    assertEquals(Collections.emptySet(), status.getOfflineDiskStores());

    validateBackupComplete();

    createData(vm0, 0, 5, "C", "region1");

    assertEquals(2, status.getBackedUpDiskStores().size());
    assertEquals(Collections.emptySet(), status.getOfflineDiskStores());

    closeCache(vm0);
    closeCache(vm1);

    // Destroy the current data
    Invoke.invokeInEveryVM(new SerializableRunnable("Clean disk dirs") {
        public void run() {
            try {
                cleanDiskDirs();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });

    restoreBackup(2);

    createPersistentRegionsAsync();

    checkData(vm0, 0, 1, "A", "region1");
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java

@Test
public void test_updateV1SourceStatus()
        throws JsonProcessingException, IOException, InterruptedException, ExecutionException, ParseException {
    @SuppressWarnings("unchecked")
    ICrudService<JsonNode> v1_share_db = this._service_context.getCoreManagementDbService()
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get();

    final DBCollection dbc = v1_share_db.getUnderlyingPlatformDriver(DBCollection.class, Optional.empty())
            .get();//from w  w w.  j av  a 2 s.  com

    v1_share_db.deleteDatastore().get();

    IManagementCrudService<SharedLibraryBean> library_db = this._service_context.getCoreManagementDbService()
            .getSharedLibraryStore();

    library_db.deleteDatastore().get();

    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final ObjectNode v1_share_1 = (ObjectNode) mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));
    final DBObject v1_share_1_dbo = (DBObject) JSON.parse(v1_share_1.toString());
    v1_share_1_dbo.put("_id", new ObjectId(v1_share_1.get("_id").asText()));

    assertEquals(0L, (long) v1_share_db.countObjects().get());
    dbc.save(v1_share_1_dbo);
    //v1_share_db.storeObjects(Arrays.asList(v1_share_1)).get();
    assertEquals(1L, (long) v1_share_db.countObjects().get());

    final SharedLibraryBean share1 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_1);

    assertEquals(0L, (long) library_db.countObjects().get());
    library_db.storeObjects(Arrays.asList(share1)).get();
    assertEquals(1L, (long) library_db.countObjects().get());

    // No error - create
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()),
                CompletableFuture.completedFuture(Arrays.asList(ErrorUtils.buildSuccessMessage("", "", "", ""))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());

        ObjectNode unchanged = (ObjectNode) v1_share_db.getRawService()
                .getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")).get().get();

        assertEquals(v1_share_1.without("_id").toString(), unchanged.without("_id").toString());
    }

    // DB call throws exception
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        assertTrue(changed.get("description").asText()
                .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // This shouldn't yet pe present
        assertFalse("Description error time travels: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] (test) (unknown): ERROR: test"));
    }

    // db call throws exception, object doesn't exist (code coverage!)
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbf", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());
    }

    // User errors (+update not create)
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()), CompletableFuture.completedFuture(
                        Arrays.asList(ErrorUtils.buildErrorMessage("test", "test", "test", "test"))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, false);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        SharedLibraryBean v2_version = library_db.getObjectById("v1_555d44e3347d336b3e8c4cbe").get().get();
        assertTrue("v2 lib bean needed updating: " + v2_version.modified(),
                new Date().getTime() - v2_version.modified().getTime() < 5000L);

        // Still has the old error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText()
                        .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // Now has the new error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] test (test): ERROR: test"));
    }

}

From source file:com.spotify.styx.cli.Main.java

private void workflowShow() throws ExecutionException, InterruptedException, IOException {
    final String cid = namespace.getString(parser.workflowShowComponentId.getDest());
    final String wid = namespace.getString(parser.workflowShowWorkflowId.getDest());

    // Fetch config and state in parallel
    final CompletableFuture<Response<ByteString>> workflowResponse = sendAsync(
            Request.forUri(apiUrl("workflows", cid, wid))).toCompletableFuture();
    final CompletableFuture<Response<ByteString>> stateResponse = sendAsync(
            Request.forUri(apiUrl("workflows", cid, wid, "state"))).toCompletableFuture();

    // Wait for both responses
    CompletableFuture.allOf(workflowResponse, stateResponse).get();

    final ByteString workflowPayload = requireSuccess(workflowResponse.get()).payload()
            .orElse(ByteString.EMPTY);//from   w w w. j  a va  2  s .  c om
    final ByteString statePayload = requireSuccess(stateResponse.get()).payload().orElse(ByteString.EMPTY);

    final Workflow workflow = deserialize(workflowPayload, Workflow.class);
    final WorkflowState workflowState = deserialize(statePayload, WorkflowState.class);

    cliOutput.printWorkflow(workflow, workflowState);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testChecktransactionState() throws Exception {
    CompletableFuture<Transaction.Status> transaction;
    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream1"),
            UUID.randomUUID());//from  w w  w. jav a  2s.  co  m
    assertEquals(Transaction.Status.OPEN, transaction.get());

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream2"),
            UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream3"),
            UUID.randomUUID());
    assertEquals(Transaction.Status.COMMITTING, transaction.get());

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream4"),
            UUID.randomUUID());
    assertEquals(Transaction.Status.COMMITTED, transaction.get());

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream5"),
            UUID.randomUUID());
    assertEquals(Transaction.Status.ABORTING, transaction.get());

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream6"),
            UUID.randomUUID());
    assertEquals(Transaction.Status.ABORTED, transaction.get());

    transaction = controllerClient.checkTransactionStatus(new StreamImpl("scope1", "stream7"),
            UUID.randomUUID());
    AssertExtensions.assertThrows("Should throw Exception", transaction, throwable -> true);
}