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:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Before
public void setUp() throws Exception {
    directories = platformService.getBattleLobbyTempDirectories();
    if (!(directories.getRoot().exists() || directories.getRoot().mkdirs())) {
        fail("Could not create tmp root");
    }/*  w  w w.j a  v  a2s  .c o  m*/

    // give file creation some time to complete
    Thread.sleep(250);

    tempWatcher = new RecursiveTempWatcher(directories);

    CountDownLatch latch = new CountDownLatch(1);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            tempWatcher.start();
            latch.countDown();
        }
    });
    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("Service did not start.");
    }
    // give watchers some time to wind up
    Thread.sleep(250);
}

From source file:com.datatorrent.demos.dimensions.ads.HDHTApplicationTest.java

@Test
public void testApplication() throws Exception {
    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "1");

    conf.set("dt.operator.QueryResult.prop.configProperties(metadata.broker.list)", "localhost:9092");

    conf.set("dt.operator.Store.fileStore.basePath", "target/HDSApplicationTestStore");

    conf.set("dt.operator.Query.brokerSet", "localhost:9092");
    conf.set("dt.operator.Query.topic", kafkaQueryTopic);
    conf.set("dt.operator.QueryResult.topic", kafkaQueryResultTopic);

    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "2");
    conf.set("dt.operator.InputGenerator.numPublishers", "2");
    conf.set("dt.loggers.level", "server.*:INFO");

    lma.prepareDAG(new ApplicationWithHDHT(), conf);
    LocalMode.Controller lc = lma.getController();
    //lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();/*from  ww  w.  j a  v a 2s .c om*/

    //Write messages to kafkaQueryTopic
    KafkaTestProducer kafkaQuery = new KafkaTestProducer(kafkaQueryTopic);
    String testQuery = "{\n" + " \"id\": \"query1\",\n"
            + " \"dimensionSelector\": \"time=MINUTES:publisherId\",\n" + " \"keys\": {\n"
            + "  \"publisherId\": 1\n" + " }\n" + "}";

    List<String> testQueryMessages = new ArrayList<String>();
    testQueryMessages.add(testQuery);
    kafkaQuery.setMessages(testQueryMessages);
    kafkaQuery.run();

    // Setup a message listener to receive the query results
    CountDownLatch latch = new CountDownLatch(100);
    KafkaTestConsumer queryResultsListener = new KafkaTestConsumer(kafkaQueryResultTopic);
    queryResultsListener.setLatch(latch);
    new Thread(queryResultsListener).start();

    // Wait to receive messages
    latch.await(15, TimeUnit.SECONDS);
    lc.shutdown();

    // Evaluate results
    String lastMessage;
    LOG.info("Sent " + kafkaQuery.getSendCount() + " messages to " + kafkaQueryTopic);
    LOG.info("Received " + queryResultsListener.holdingBuffer.size() + " messages from Kafka on "
            + kafkaQueryResultTopic + " topic");
    Assert.assertTrue("Minimum messages received from Kafka " + queryResultsListener.holdingBuffer,
            queryResultsListener.holdingBuffer.size() >= 1);

    while (!queryResultsListener.holdingBuffer.isEmpty()) {
        lastMessage = queryResultsListener.getMessage(queryResultsListener.holdingBuffer.poll());
        Assert.assertNotNull("Did not receive message from Kafka", lastMessage);
        LOG.info("received:\n{}", lastMessage);
    }
}

From source file:com.datatorrent.demos.dimensions.generic.GenericAppTest.java

@Test
public void testApplication() throws Exception {
    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.addResource("META-INF/properties.xml");
    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "1");
    conf.set("dt.operator.QueryResult.prop.configProperties(metadata.broker.list)", "localhost:9092");
    conf.set("dt.operator.DimensionsStore.fileStore.basePath", "target/HDSApplicationTestStore");
    conf.set("dt.operator.Query.brokerSet", "localhost:9092");
    conf.set("dt.operator.Query.topic", kafkaQueryTopic);
    conf.set("dt.operator.QueryResult.topic", kafkaQueryResultTopic);
    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "2");
    conf.set("dt.operator.InputGenerator.numPublishers", "2");
    conf.set("dt.loggers.level", "server.*:INFO");

    GenericDimensionsApplication app = new GenericDimensionsApplication();
    lma.prepareDAG(app, conf);/* w w w .  j a  v a 2  s  .c  o m*/
    LocalMode.Controller lc = lma.getController();
    lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();

    //Write messages to kafkaQueryTopic
    KafkaTestProducer kafkaQuery = new KafkaTestProducer(kafkaQueryTopic);

    // Query should be able to support keys of String or Number type
    String testQuery = "{\n" + " \"id\": \"query1\",\n" + " \"keys\": {\"publisherId\": \"1\"},\n"
            + " \"kafka\": {\"queryTopic\":\"GenericDimensionsQuery\",\"resultTopic\":\"GenericDimensionsQueryResult\"}"
            + "}";

    List<String> testQueryMessages = new ArrayList<String>();
    testQueryMessages.add(testQuery);
    kafkaQuery.setMessages(testQueryMessages);
    kafkaQuery.run();

    // Setup a message listener to receive the query results
    CountDownLatch latch = new CountDownLatch(100);
    KafkaTestConsumer queryResultsListener = new KafkaTestConsumer(kafkaQueryResultTopic);
    queryResultsListener.setLatch(latch);
    new Thread(queryResultsListener).start();

    // Wait to receive messages
    latch.await(15, TimeUnit.SECONDS);
    lc.shutdown();

    // Evaluate results
    String lastMessage;
    LOG.info("Sent " + kafkaQuery.getSendCount() + " messages to " + kafkaQueryTopic);
    LOG.info("Received " + queryResultsListener.holdingBuffer.size() + " messages from Kafka on "
            + kafkaQueryResultTopic + " topic");
    Assert.assertTrue("Minimum messages received from Kafka " + queryResultsListener.holdingBuffer,
            queryResultsListener.holdingBuffer.size() >= 1);

    while (!queryResultsListener.holdingBuffer.isEmpty()) {
        lastMessage = queryResultsListener.getMessage(queryResultsListener.holdingBuffer.poll());
        Assert.assertNotNull("Did not receive message from Kafka", lastMessage);
        LOG.info("received:\n{}", lastMessage);
    }
}

From source file:io.syndesis.runtime.EventsITCase.java

@Test
public void sseEventsWithToken() throws Exception {
    ResponseEntity<EventMessage> r1 = post("/api/v1/event/reservations", null, EventMessage.class);
    assertThat(r1.getBody().getEvent().get()).as("event").isEqualTo("uuid");
    String uuid = (String) r1.getBody().getData().get();
    assertThat(uuid).as("data").isNotNull();

    URI uri = resolveURI(EventBusToServerSentEvents.DEFAULT_PATH + "/" + uuid);

    // lets setup an event handler that we can inspect events on..
    EventHandler handler = recorder(mock(EventHandler.class), EventHandler.class);
    List<Recordings.Invocation> invocations = recordedInvocations(handler);
    CountDownLatch countDownLatch = resetRecorderLatch(handler, 2);

    try (EventSource eventSource = new EventSource.Builder(handler, uri).build()) {
        eventSource.start();/*from  w w w .  jav a  2 s .c o m*/

        assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();

        // workaround issues in EventSource
        reorderEventSourceInvocations(invocations);

        assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onOpen");

        // We auto get a message letting us know we connected.
        assertThat(invocations.get(1).getMethod().getName()).isEqualTo("onMessage");
        assertThat(invocations.get(1).getArgs()[0]).isEqualTo("message");
        assertThat(((MessageEvent) invocations.get(1).getArgs()[1]).getData()).isEqualTo("connected");

        /////////////////////////////////////////////////////
        // Test that we get notified of created entities
        /////////////////////////////////////////////////////
        invocations.clear();
        countDownLatch = resetRecorderLatch(handler, 1);

        Integration integration = new Integration.Builder().id("1001").name("test")
                .desiredStatus(Integration.Status.Draft).currentStatus(Integration.Status.Draft).build();
        post("/api/v1/integrations", integration, Integration.class);

        assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
        assertThat(invocations.get(0).getArgs()[0]).isEqualTo("change-event");
        assertThat(((MessageEvent) invocations.get(0).getArgs()[1]).getData())
                .isEqualTo(ChangeEvent.of("created", "integration", "1001").toJson());
    }
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpWebSocketTest.java

private void createClearChannel() throws Exception {
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build();
    config.getUserProperties().put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
    clearChannel = ContainerProvider.getWebSocketContainer().connectToServer(endpoint, config,
            new URI(createClearUriString()));

    assertTrue(clearChannel.isOpen());//from w  w  w  .  j a v a  2 s . c  o  m

    CountDownLatch cdl = new CountDownLatch(1);
    endpoint.setResponseLatch(cdl);

    cdl.await(1, TimeUnit.SECONDS);

    assertNotNull(endpoint.getSystemId());
    assertEquals(clearChannel, endpoint.getSession());
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testSetCallbackIsAppliedProperly() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    tempWatcher.setCallback(file -> latch.countDown());
    TempWatcher lastChild = getChildRecursively(tempWatcher);
    Consumer<File> callback = lastChild.getCallback();

    callback.accept(null);//from  ww w. j  a va  2  s  . com

    if (!latch.await(500, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException("Latch was not tripped.");
    }
}

From source file:io.syndesis.runtime.EventsITCase.java

@Test
public void wsEventsWithToken() throws Exception {
    OkHttpClient client = new OkHttpClient();

    ResponseEntity<EventMessage> r1 = post("/api/v1/event/reservations", null, EventMessage.class);
    assertThat(r1.getBody().getEvent().get()).as("event").isEqualTo("uuid");
    String uuid = (String) r1.getBody().getData().get();
    assertThat(uuid).as("data").isNotNull();

    String uriTemplate = EventBusToWebSocket.DEFAULT_PATH + "/" + uuid;
    String url = resolveURI(uriTemplate).toString().replaceFirst("^http", "ws");

    Request request = new Request.Builder().url(url)
            .addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + tokenRule.validToken()).build();

    // lets setup an event handler that we can inspect events on..
    WebSocketListener listener = recorder(mock(WebSocketListener.class), WebSocketListener.class);
    List<Recordings.Invocation> invocations = recordedInvocations(listener);
    CountDownLatch countDownLatch = resetRecorderLatch(listener, 2);

    WebSocket ws = client.newWebSocket(request, listener);

    // We auto get a message letting us know we connected.
    assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
    assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onOpen");
    assertThat(invocations.get(1).getMethod().getName()).isEqualTo("onMessage");
    assertThat(invocations.get(1).getArgs()[1]).isEqualTo(EventMessage.of("message", "connected").toJson());

    /////////////////////////////////////////////////////
    // Test that we get notified of created entities
    /////////////////////////////////////////////////////
    invocations.clear();//from  w  ww  . j  a  va  2  s. c om
    countDownLatch = resetRecorderLatch(listener, 1);

    Integration integration = new Integration.Builder().id("1002").name("test")
            .desiredStatus(Integration.Status.Draft).currentStatus(Integration.Status.Draft).build();
    post("/api/v1/integrations", integration, Integration.class);

    assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
    assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onMessage");
    assertThat(invocations.get(0).getArgs()[1]).isEqualTo(EventMessage
            .of("change-event", ChangeEvent.of("created", "integration", "1002").toJson()).toJson());

    ws.close(1000, "closing");
}

From source file:com.ericsson.gerrit.plugins.highavailability.cache.CacheEvictionIT.java

@Test
@UseLocalDisk/*from  w  w  w  . ja  va 2  s. c o m*/
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void flushAndSendPost() throws Exception {
    final String flushRequest = "/plugins/high-availability/cache/" + Constants.PROJECTS;
    final CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(flushRequest)) {
            expectedRequestLatch.countDown();
        }
    });

    adminSshSession.exec("gerrit flush-caches --cache " + Constants.PROJECTS);
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(flushRequest)));
}

From source file:com.ericsson.gerrit.plugins.highavailability.cache.ProjectListIT.java

@Test
@UseLocalDisk//from w w  w. ja va  2 s .c om
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void addToProjectListAreForwarded() throws Exception {
    String createdProjectEncoded = Url.encode("org-a/some-project");
    String expectedRequest = "/plugins/high-availability/cache/" + Constants.PROJECT_LIST + "/"
            + createdProjectEncoded;
    CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(expectedRequest)) {
            expectedRequestLatch.countDown();
        }
    });

    adminRestSession.put("/projects/" + createdProjectEncoded).assertCreated();
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(expectedRequest)));
}

From source file:com.frostwire.search.VuzeMagnetDownloader.java

public byte[] download(String magnet, int timeout) {

    CountDownLatch signal = new CountDownLatch(1);

    String saveDir = SharingSettings.TORRENTS_DIR_SETTING.getValue().getAbsolutePath();

    TorrentDownloaderListener listener = new TorrentDownloaderListener(signal);

    TorrentDownloader td = TorrentDownloaderFactory.create(listener, magnet, null, saveDir);

    td.start();//from ww w  .j a  va  2s. c o m

    try {
        signal.await(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // ignore
    }

    if (listener.getData() == null) {
        td.cancel();
    }

    return listener.getData();
}