Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:de.taimos.httputils.Tester1.java

/**
 * /*from  ww w. j  av  a2 s.  c  o  m*/
 */
@Test
public void testGetAsyncStringCB() throws InterruptedException {
    final CountDownLatch cdl = new CountDownLatch(1);
    WS.url("http://www.heise.de").getAsync(new HTTPStringCallback() {

        @Override
        public void fail(Exception e) {
            System.out.println(e);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void invalidStatus(int status, HttpResponse response) {
            System.out.println("Invalid status: " + status);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void stringResponse(String body, HttpResponse response) {
            Assert.assertNotNull(body);
            Assert.assertFalse(body.isEmpty());
            cdl.countDown();
        }

    });
    Assert.assertTrue(cdl.await(10, TimeUnit.SECONDS));
}

From source file:interactivespaces.master.server.services.internal.ros.MasterRosContext.java

public void startup() {
    log.error("Starting up master ROS context");

    final NodeConfiguration nodeConfiguration = rosEnvironment.getPublicNodeConfigurationWithNodeName();
    nodeConfiguration.setNodeName("interactivespaces/master");

    final CountDownLatch registrationLatch = new CountDownLatch(1);

    NodeListener listener = new NodeListener() {

        @Override//from w ww  .  ja  v  a2  s  . co m
        public void onStart(ConnectedNode connectedNode) {
            setConnectedNode(connectedNode);
            registrationLatch.countDown();
        }

        @Override
        public void onShutdownComplete(Node node) {
            log.error(String.format("Got ROS node complete shutdown for Interactive Spaces master node %s",
                    node.getName()));
        }

        @Override
        public void onShutdown(Node node) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(Node node, Throwable throwable) {
            log.error(String.format("Got ROS node error for Interactive Spaces master node %s", node.getName()),
                    throwable);
        }
    };
    rosEnvironment.newNode(nodeConfiguration, Lists.newArrayList(listener));
}

From source file:kidozen.client.crash.HttpSender.java

@Override
public void send(CrashReportData report) throws ReportSenderException {
    try {//w ww  . j av a  2 s. c  om
        final CountDownLatch cdl = new CountDownLatch(1);
        IdentityManager.getInstance().GetRawToken(mApplicationKey, new ServiceEventListener() {
            @Override
            public void onFinish(ServiceEvent e) {
                mEvent = e;
                cdl.countDown();
            }
        });
        cdl.await(DEFAULT_TIMEOUT, TimeUnit.MINUTES);
        if (mEvent.Exception != null || mEvent.StatusCode >= HttpStatus.SC_BAD_REQUEST)
            throw new ReportSenderException(mEvent.Body);
        mToken = ((KidoZenUser) mEvent.Response).Token;

        String authHeaderValue = String.format("WRAP access_token=\"%s\"", mToken);

        Log.d(LOG_TAG, String.format("About to send log to Log V3 service: %s ", mCrashEndpoint));
        JSONObject reportAsJson = report.toJSON();

        String bc = new JSONArray(mBreadCrumbs).toString();
        reportAsJson.put(APPLICATION_BREADCRUMB, bc);

        Hashtable<String, String> headers = new Hashtable<String, String>();
        headers.put(Constants.AUTHORIZATION_HEADER, authHeaderValue);
        headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON);
        headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);

        mSniManager = new SNIConnectionManager(mCrashEndpoint, reportAsJson.toString(), headers, null, true);
        Hashtable<String, String> response = mSniManager.ExecuteHttp(KZHttpMethod.POST);
        String body = response.get("responseBody");
        Integer statusCode = Integer.parseInt(response.get("statusCode"));
        if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
            String exceptionMessage = (body != null ? body : "Unexpected HTTP Status Code: " + statusCode);
            throw new Exception(exceptionMessage);
        }
    } catch (InterruptedException e) {
        throw new ReportSenderException("Timeout trying to send report to KidoZen services.", e);
    } catch (ReportSenderException e) {
        throw e;
    } catch (Exception e) {
        throw new ReportSenderException("Error while sending  report to KidoZen services.", e);
    }
}

From source file:com.github.oscerd.camel.cassandra.embedded.CassandraBaseTest.java

@Override
public void doPostSetup() {
    String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz");
    fs = new Farsandra();
    fs.withVersion("2.0.3");
    fs.withCleanInstanceOnStart(true);/*from  w  ww  .  j  a  v  a  2 s  .c  o  m*/
    fs.withInstanceName("target" + File.separator + id);
    fs.withCreateConfigurationFiles(true);
    fs.withHost("localhost");
    fs.withSeeds(Arrays.asList("localhost"));
    final CountDownLatch started = new CountDownLatch(1);
    fs.getManager().addOutLineHandler(new LineHandler() {
        @Override
        public void handleLine(String line) {
            if (line.contains("Listening for thrift clients...")) {
                started.countDown();
            }
        }
    });
    fs.getManager().addProcessHandler(new ProcessHandler() {
        @Override
        public void handleTermination(int exitValue) {
            started.countDown();
        }
    });
    fs.start();
    try {
        started.await();
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication "
            + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    session.execute("CREATE TABLE IF NOT EXISTS simplex.airport (" + "id int PRIMARY KEY," + "ident text,"
            + "type text," + "name text," + "latitude_deg float," + "longitude_deg float," + "elevation_ft int,"
            + "continent text," + "iso_country text," + "iso_region text," + "municipality text,"
            + "scheduled_service text," + "gps_code text," + "iata_code text," + "local_code text,"
            + "home_link text," + "wikipedia_link text," + "keywords text," + ");");
    session.execute("CREATE INDEX IF NOT EXISTS name_idx ON simplex.airport(name);");
    session.execute("CREATE INDEX IF NOT EXISTS continent_idx ON simplex.airport(continent);");
    session.close();
    cluster.close();
    try {
        Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.github.oscerd.component.cassandra.embedded.CassandraBaseCounterTest.java

@Override
public void doPostSetup() {
    String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz");
    fs = new Farsandra();
    fs.withVersion("2.0.3");
    fs.withCleanInstanceOnStart(true);/*from   w  w w . j a  va2  s .  c om*/
    fs.withInstanceName("target" + File.separator + id);
    fs.withCreateConfigurationFiles(true);
    fs.withHost("localhost");
    fs.withSeeds(Arrays.asList("localhost"));
    final CountDownLatch started = new CountDownLatch(1);
    fs.getManager().addOutLineHandler(new LineHandler() {
        @Override
        public void handleLine(String line) {
            if (line.contains("Listening for thrift clients...")) {
                started.countDown();
            }
        }
    });
    fs.getManager().addProcessHandler(new ProcessHandler() {
        @Override
        public void handleTermination(int exitValue) {
            started.countDown();
        }
    });
    fs.start();
    try {
        started.await();
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication "
            + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    session.execute(
            "CREATE TABLE IF NOT EXISTS simplex.counter (" + "like counter, " + "id int PRIMARY KEY" + ");");
    session.close();
    session = cluster.connect("simplex");
    Where update = QueryBuilder.update("counter").with(QueryBuilder.incr("like", 1))
            .where(QueryBuilder.eq("id", 1));
    session.execute(update);
    session.close();
    cluster.close();
    try {
        Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:example.springdata.cassandra.basic.CassandraOperationsIntegrationTests.java

/**
 * Asynchronous query execution using callbacks.
 *///from w  ww.java  2  s  .c  om
@Test
public void insertAsynchronously() throws InterruptedException {

    User user = new User();
    user.setId(42L);
    user.setUsername("heisenberg");
    user.setFirstname("Walter");
    user.setLastname("White");

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    template.insertAsynchronously(user, new WriteListener<User>() {

        @Override
        public void onWriteComplete(Collection<User> entities) {
            countDownLatch.countDown();
        }

        @Override
        public void onException(Exception x) {
        }
    });

    countDownLatch.await(5, TimeUnit.SECONDS);

    User loaded = template.selectOneById(User.class, user.getId());
    assertThat(loaded, is(equalTo(user)));
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSCxfContinuationsTest.java

private void doTestContinuation(String pathSegment) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);

    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1",
            "CXF in Action1", startSignal, doneSignal));
    startSignal.countDown();//from  w w w  . j a  va  2 s .c om
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}

From source file:org.kurento.test.base.BrowserKurentoClientTest.java

protected void playFileWithPipeline(BrowserType browserType, String recordingFile, int playtime, int x, int y,
        Color... expectedColors) throws InterruptedException {

    // Media Pipeline
    MediaPipeline mp = kurentoClient.createMediaPipeline();
    PlayerEndpoint playerEP = new PlayerEndpoint.Builder(mp, recordingFile).build();
    WebRtcEndpoint webRtcEP = new WebRtcEndpoint.Builder(mp).build();
    playerEP.connect(webRtcEP);/*from   ww  w .  ja va2  s. com*/

    // Browser
    BrowserClient browserClient = new BrowserClient.Builder().browserType(browserType).client(Client.WEBRTC)
            .build();
    String browserkey = "playBrowser";
    addBrowserClient(browserkey, browserClient);

    // Play latch
    final CountDownLatch eosLatch = new CountDownLatch(1);
    playerEP.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });

    // Test execution
    getBrowser(browserkey).subscribeEvents("playing");
    getBrowser(browserkey).initWebRtc(webRtcEP, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
    playerEP.play();

    // Assertions
    makeAssertions(browserkey, "[played file with media pipeline]", browserClient, playtime, x, y, eosLatch,
            expectedColors);

    // Release Media Pipeline
    if (mp != null) {
        mp.release();
    }
}

From source file:com.yahoo.gondola.container.client.ZookeeperShardManagerClientTest.java

@BeforeMethod
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    servers = new HashMap<>();
    shardManagers = new HashMap<>();
    for (String hostId : config.getHostIds()) {
        Gondola gondola = mock(Gondola.class);
        when(gondola.getHostId()).thenReturn(hostId);
        when(gondola.getConfig()).thenReturn(config);
        ShardManager shardManager = mock(ShardManager.class);
        ZookeeperShardManagerServer server = new ZookeeperShardManagerServer("foo",
                zookeeperServer.getConnectString(), gondola, shardManager);
        shardManagers.put(hostId, shardManager);
        servers.put(hostId, server);/*  w  ww  .  j  av a2s .  c o  m*/
    }

    client = new ZookeeperShardManagerClient("foo", "fooClientName", zookeeperServer.getConnectString(),
            config);
    stats = (PathChildrenCache) Whitebox.getInternalState(client, "stats");
    CountDownLatch latch = new CountDownLatch(1);
    this.stats.getListenable().addListener((curatorFramework, pathChildrenCacheEvent) -> {
        if (this.stats.getCurrentData().size() == config.getMembers().size()) {
            latch.countDown();
        }
    });
    latch.await();
}

From source file:io.opentracing.contrib.elasticsearch6.TracingTest.java

@Test
public void transportClient() throws Exception {

    Settings settings = Settings.builder().put("cluster.name", clusterName).build();

    TransportClient client = new TracingPreBuiltTransportClient(mockTracer, settings).addTransportAddress(
            new TransportAddress(InetAddress.getByName("localhost"), Integer.parseInt(HTTP_TRANSPORT_PORT)));

    IndexRequest indexRequest = new IndexRequest("twitter").type("tweet").id("1")
            .source(jsonBuilder().startObject().field("user", "kimchy").field("postDate", new Date())
                    .field("message", "trying out Elasticsearch").endObject());

    IndexResponse indexResponse = client.index(indexRequest).actionGet();
    assertNotNull(indexResponse);/*w  ww.j a  v a 2s .  co  m*/

    final CountDownLatch latch = new CountDownLatch(1);
    client.index(indexRequest, new ActionListener<IndexResponse>() {
        @Override
        public void onResponse(IndexResponse indexResponse) {
            latch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            latch.countDown();
        }
    });

    latch.await(30, TimeUnit.SECONDS);
    client.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "IndexRequest");
    assertNull(mockTracer.activeSpan());
}