Example usage for java.util.concurrent CountDownLatch await

List of usage examples for java.util.concurrent CountDownLatch await

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch await.

Prototype

public boolean await(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted , or the specified waiting time elapses.

Usage

From source file:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java

@Test
public void testResizeAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.resizeAsync("dummy-cluster-id", 100, new FutureCallback<Task>() {
        @Override/*from  w w w .j  ava2  s  .c om*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.couchbase.lite.syncgateway.GzippedAttachmentTest.java

public void testImageAttachmentReplication() throws Exception {
    if (!syncgatewayTestsEnabled()) {
        return;// w  w w . j  a  v  a2  s.  c  o m
    }

    URL remote = getReplicationURL();

    Database pushDB = getDatabase("pushdb");
    pushDB.delete();
    pushDB = getDatabase("pushdb");

    Database pullDB = getDatabase("pulldb");
    pullDB.delete();
    pullDB = getDatabase("pulldb");

    // Create a document with an image attached:
    Map<String, Object> props = new HashMap<String, Object>();
    props.put("foo", "bar");

    Document doc = pushDB.createDocument();
    doc.putProperties(props);
    UnsavedRevision newRev = doc.createRevision();
    newRev.setAttachment("attachment", "image/png", getAsset("attachment.png"));
    newRev.save();
    String docId = doc.getId();

    // Push:
    final CountDownLatch latch1 = new CountDownLatch(1);
    Replication pusher = pushDB.createPushReplication(remote);
    pusher.addChangeListener(new Replication.ChangeListener() {
        @Override
        public void changed(Replication.ChangeEvent event) {
            Log.e(TAG, "push 1:" + event.toString());
            if (event.getCompletedChangeCount() > 0) {
                latch1.countDown();
            }
        }
    });
    runReplication(pusher);
    assertTrue(latch1.await(5, TimeUnit.SECONDS));

    // Pull:
    Replication puller = pullDB.createPullReplication(remote);
    final CountDownLatch latch2 = new CountDownLatch(1);
    puller.addChangeListener(new Replication.ChangeListener() {
        @Override
        public void changed(Replication.ChangeEvent event) {
            Log.e(TAG, "pull 1:" + event.toString());
            if (event.getCompletedChangeCount() > 0) {
                latch2.countDown();
            }
        }
    });
    runReplication(puller);
    assertTrue(latch2.await(5, TimeUnit.SECONDS));

    // Check document:
    Document pullDoc = pullDB.getDocument(docId);
    assertNotNull(pullDoc);
    assertTrue(pullDoc.getCurrentRevisionId().startsWith("2-"));

    // Check attachment:
    Attachment attachment = pullDoc.getCurrentRevision().getAttachment("attachment");
    byte[] originalBytes = getBytesFromInputStream(getAsset("attachment.png"));
    assertEquals(originalBytes.length, attachment.getLength());
    assertEquals("image/png", attachment.getContentType());
    assertTrue(Arrays.equals(originalBytes, getBytesFromInputStream(attachment.getContent())));

    pushDB.close();
    pullDB.close();

    pushDB.delete();
    pullDB.delete();
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorParticipants.java

@Test
public void testId() throws Exception {
    LeaderSelector selector = null;/*from w w w  . j  av  a  2 s.co m*/
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                latch.countDown();
                Thread.currentThread().join();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        selector = new LeaderSelector(client, "/ls", listener);
        selector.setId("A is A");
        selector.start();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Participant leader = selector.getLeader();
        Assert.assertTrue(leader.isLeader());
        Assert.assertEquals(leader.getId(), "A is A");

        Collection<Participant> participants = selector.getParticipants();
        Assert.assertEquals(participants.size(), 1);
        Assert.assertEquals(participants.iterator().next().getId(), "A is A");
        Assert.assertEquals(participants.iterator().next().getId(), selector.getId());
    } finally {
        IOUtils.closeQuietly(selector);
        IOUtils.closeQuietly(client);
    }
}

From source file:io.smartspaces.util.process.StandardNativeApplicationRunnerCollection.java

@Override
public NativeApplicationRunnerState runNativeApplicationRunner(NativeApplicationDescription description,
        long waitTime) {
    NativeApplicationRunner runner = newNativeApplicationRunner();
    runner.configure(description);/*from  w  w  w  .  j ava  2s.  c o m*/

    final CountDownLatch runnerComplete = new CountDownLatch(BLOCKING_RUN_COUNTDOWN_COUNT);
    runner.addNativeApplicationRunnerListener(new BaseNativeApplicationRunnerListener() {

        @Override
        public void onNativeApplicationRunnerStartupFailed(NativeApplicationRunner runner) {
            runnerComplete.countDown();
        }

        @Override
        public void onNativeApplicationRunnerShutdown(NativeApplicationRunner runner) {
            runnerComplete.countDown();
        }
    });

    addNativeApplicationRunner(runner);

    try {
        if (!runnerComplete.await(waitTime, TimeUnit.MILLISECONDS)) {
            SimpleSmartSpacesException.throwFormattedException("The command %s did not complete in %d msec",
                    description, waitTime);
        }
    } catch (SimpleSmartSpacesException e) {
        throw e;
    } catch (InterruptedException e) {
        SimpleSmartSpacesException.throwFormattedException("The command %s wait was interrupted", description);
    }

    return runner.getState();
}

From source file:net.minecraftforge.fml.common.FMLCommonHandler.java

/**
 * Delayed System.exit() until the server is actually stopped/done saving.
 *
 * For internal use only!// ww w  .jav a 2  s . com
 *
 * @param retVal Exit code for System.exit()
 */
public void handleExit(int retVal) {
    CountDownLatch latch = exitLatch;

    if (latch != null) {
        try {
            FMLLog.info("Waiting for the server to terminate/save.");
            if (!latch.await(10, TimeUnit.SECONDS)) {
                FMLLog.warning("The server didn't stop within 10 seconds, exiting anyway.");
            } else {
                FMLLog.info("Server terminated.");
            }
        } catch (InterruptedException e) {
            FMLLog.warning("Interrupted wait, exiting.");
        }
    }

    System.exit(retVal);
}

From source file:org.springframework.cloud.stream.config.MessageChannelConfigurerTests.java

@Test
public void testMessageConverterConfigurer() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    MessageHandler messageHandler = new MessageHandler() {
        @Override// w w  w  .ja v  a 2  s  .  co  m
        public void handleMessage(Message<?> message) throws MessagingException {
            assertThat(message.getPayload()).isInstanceOf(Tuple.class);
            assertThat(((Tuple) message.getPayload()).getFieldNames().get(0)).isEqualTo("message");
            assertThat(((Tuple) message.getPayload()).getValue(0)).isEqualTo("Hi");
            latch.countDown();
        }
    };
    testSink.input().subscribe(messageHandler);
    testSink.input().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build());
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
    testSink.input().unsubscribe(messageHandler);
}

From source file:com.networknt.client.oauth.OauthHelper.java

public static Result<TokenResponse> getTokenFromSamlResult(SAMLBearerRequest tokenRequest) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from  w  w w . j  a  v  a 2s . c o  m*/
        connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL,
                tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                        : OptionMap.EMPTY)
                .get();
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR));
    }
    try {
        IClientRequestComposable requestComposer = ClientRequestComposerProvider.getInstance()
                .getComposer(ClientRequestComposerProvider.ClientRequestComposers.SAML_BEARER_REQUEST_COMPOSER);

        connection.getIoThread()
                .execute(new TokenRequestAction(tokenRequest, requestComposer, connection, reference, latch));

        latch.await(4, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }
    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}

From source file:com.microsoft.office.integration.test.EventsAsyncTestCase.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ICalendars cals = Me.getCalendars();
    final CountDownLatch cdl = new CountDownLatch(1);
    // an empty iterator will be returned for any entity set unless you call fetch()
    Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            cdl.countDown();/*w ww  .j  a va 2s.  co  m*/
        }

        public void onSuccess(Void result) {
            Iterator<ICalendar> iterator = cals.iterator();
            if (iterator.hasNext()) {
                calendar = iterator.next();
            }
            cdl.countDown();
        }
    });

    cdl.await(60000, TimeUnit.MILLISECONDS);
    if (calendar == null) {
        fail("No calendar found");
    }
}

From source file:com.vmware.photon.controller.api.client.resource.ImagesApiTest.java

@Test
public void testGetAllImagesAsync() throws IOException, InterruptedException {
    Image image1 = new Image();
    image1.setId("image1");

    Image image2 = new Image();
    image2.setId("image2");

    final ResourceList<Image> imageResourceList = new ResourceList<>(Arrays.asList(image1, image2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(imageResourceList);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ImagesApi imagesApi = new ImagesApi(this.restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.getImagesAsync(new FutureCallback<ResourceList<Image>>() {
        @Override/*  w w  w  . jav a  2s  . co  m*/
        public void onSuccess(@Nullable ResourceList<Image> result) {
            assertEquals(result.getItems(), imageResourceList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));

}

From source file:com.vmware.photon.controller.api.client.resource.ImagesRestApiTest.java

@Test
public void testGetAllImagesAsync() throws IOException, InterruptedException {
    Image image1 = new Image();
    image1.setId("image1");

    Image image2 = new Image();
    image2.setId("image2");

    final ResourceList<Image> imageResourceList = new ResourceList<>(Arrays.asList(image1, image2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(imageResourceList);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ImagesApi imagesApi = new ImagesRestApi(this.restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.getImagesAsync(new FutureCallback<ResourceList<Image>>() {
        @Override/*  w  ww .  j a va 2s . c  om*/
        public void onSuccess(@Nullable ResourceList<Image> result) {
            assertEquals(result.getItems(), imageResourceList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));

}