Example usage for java.util.concurrent CountDownLatch getCount

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

Introduction

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

Prototype

public long getCount() 

Source Link

Document

Returns the current count.

Usage

From source file:org.apache.awf.web.SystemTest.java

@Test
public void AsynchronousHttpClientConnectionFailedTest() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    final String url = "http://localhost:" + (PORT + 1) + "/";
    final AsynchronousHttpClient http = new AsynchronousHttpClient();
    final AsyncResult<org.apache.awf.web.http.client.Response> cb = new AsyncResult<org.apache.awf.web.http.client.Response>() {

        public void onSuccess(org.apache.awf.web.http.client.Response response) {
        }/*ww w  .  j a v a2s .  c o  m*/

        public void onFailure(Throwable e) {
            if (e instanceof ConnectException) {
                latch.countDown();
            }
        }
    };
    // make sure that the http.fetch(..) is invoked from the ioloop thread
    IOLoop.INSTANCE.addCallback(new AsyncCallback() {
        public void onCallback() {
            http.get(url, cb);
        }
    });
    latch.await(5, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void connectToUnconnectableAddressUsingAsynchronousHttpClient() throws InterruptedException {

    final String unconnectableAddress = "http://localhost:8039/start";
    final CountDownLatch latch = new CountDownLatch(1);
    final AsynchronousHttpClient client = new AsynchronousHttpClient();
    final AsyncCallback runByIOLoop = new AsyncCallback() {

        public void onCallback() {
            client.get(unconnectableAddress, new AsyncResult<org.apache.awf.web.http.client.Response>() {

                public void onSuccess(org.apache.awf.web.http.client.Response result) {
                    client.close();/*  www . j a  va  2 s. co m*/
                }

                public void onFailure(Throwable caught) {
                    if (caught instanceof ConnectException) {
                        latch.countDown();
                    }
                    client.close();
                }
            });
        }
    };
    IOLoop.INSTANCE.addCallback(runByIOLoop);

    latch.await(30, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

From source file:io.coala.enterprise.role.AbstractActorRole.java

@Schedulable(ADD_PROCESS_MANAGER_AGENT)
protected Observable<AgentStatusUpdate> bootAgent(final AgentID agentID, final Class<? extends Agent> agentType,
        // final BasicAgentStatus blockSimUntilState,
        final Job<?> next) throws Exception {
    if (next == null) // no need to sleep sim, nothing to schedule next
        return getBooter().createAgent(agentID, agentType);

    final CountDownLatch latch = new CountDownLatch(1);
    final Subject<AgentStatusUpdate, AgentStatusUpdate> status = ReplaySubject.create();
    status.subscribe(new Observer<AgentStatusUpdate>() {
        /** */// w  w  w  .j a v a  2  s. c o m
        private boolean success = false;

        @Override
        public void onNext(final AgentStatusUpdate update) {
            LOG().trace("Got child agent update: " + update);
            if (update.getStatus().isFailedStatus()) {
                LOG().warn("Child agent failed: " + update.getAgentID());
                latch.countDown();
            } else if (update.getStatus().isInitializedStatus()// .equals(blockSimUntilState)
            ) {
                LOG().info("Child agent " + agentID + " reached unblock status: " + update.getStatus());
                success = true;
                latch.countDown(); // yield
            }
        }

        @Override
        public void onCompleted() {
            if (success)
                return;
            LOG().warn("Child agent died but never reached blockable status" + ", scheduling next job now");
            latch.countDown();
        }

        @Override
        public void onError(final Throwable e) {
            e.printStackTrace();
        }
    });
    getBooter().createAgent(agentID, agentType).subscribe(status);
    //while (latch.getCount() > 0) {
    latch.await(1000L, java.util.concurrent.TimeUnit.MILLISECONDS);
    //   Thread.yield();
    //}
    if (latch.getCount() > 0) {
        LOG.error("FIXME: Failed to wait for agent boot signal for " + agentID + ", continue unsafe.",
                new IllegalStateException("No initialize or fail status for agent reached during boot."));
        getScheduler().schedule(
                ProcedureCall.create(this, this, ADD_PROCESS_MANAGER_AGENT, agentID, agentType, next),
                Trigger.createAbsolute(getTime()));
    } else
        getSimulator().schedule(next, Trigger.createAbsolute(getTime()));

    return status.asObservable();
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void connectToUnresolvableAddressUsingAsynchronousHttpClient() throws InterruptedException {

    final String unresolvableAddress = "http://ttasfdqwertyuiop.se./start";
    final CountDownLatch latch = new CountDownLatch(1);
    final AsynchronousHttpClient client = new AsynchronousHttpClient();
    final AsyncCallback runByIOLoop = new AsyncCallback() {

        public void onCallback() {
            client.get(unresolvableAddress, new AsyncResult<org.apache.awf.web.http.client.Response>() {

                public void onSuccess(org.apache.awf.web.http.client.Response result) {
                    client.close();/*  w w  w.  java2s .c  om*/
                }

                public void onFailure(Throwable caught) {
                    if (caught instanceof UnresolvedAddressException) {
                        latch.countDown();
                    }
                    client.close();
                }
            });
        }
    };
    IOLoop.INSTANCE.addCallback(runByIOLoop);

    latch.await(30, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void AsynchronousHttpClientRedirectTest() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    // final String url = "http://localhost:" + (PORT) + "/moved_perm";
    final String url = "http://localhost:" + PORT + "/moved_perm";
    final AsynchronousHttpClient http = new AsynchronousHttpClient();
    final AsyncResult<org.apache.awf.web.http.client.Response> cb = new AsyncResult<org.apache.awf.web.http.client.Response>() {

        public void onSuccess(org.apache.awf.web.http.client.Response response) {
            if (response.getBody().equals(expectedPayload)) {
                latch.countDown();//from  w w w .  j  av  a 2s .  c  om
            }
        }

        public void onFailure(Throwable e) {
        }

    };
    // make sure that the http.fetch(..) is invoked from the ioloop thread
    IOLoop.INSTANCE.addCallback(new AsyncCallback() {
        public void onCallback() {
            http.get(url, cb);
        }
    });
    latch.await(10, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

From source file:byps.test.TestRemoteStreams.java

/**
 * Check receiving streams asynchronously.
 * @throws IOException //ww  w .  ja  v a 2 s  . c  o m
 * 
 */
@Test
public void testRemoteStreamsAsyncCallback() throws IOException {
    log.info("testRemoteStreamsAsyncCallback(");

    final String text = "abcdef";
    final CountDownLatch waitForFinished = new CountDownLatch(4);

    remote.setImage(new ByteArrayInputStream(text.getBytes()));

    log.info("start download");
    InputStream istrmR = remote.getImage();
    BContentStream.assignAsyncCallback(istrmR, new BContentStreamAsyncCallback() {

        @Override
        public boolean onReceivedData(byte[] buf, int len) {
            TestUtils.assertEquals(log, "stream content", text, new String(buf, 0, len));
            waitForFinished.countDown();
            return true;
        }

        @Override
        public void onReceivedContentLength(long contentLength) {
            TestUtils.assertEquals(log, "stream length", text.length(), (int) contentLength);
            waitForFinished.countDown();
        }

        @Override
        public void onReceivedContentType(String contentType) {
            TestUtils.assertEquals(log, "stream content type", "application/octet-stream", contentType);
            waitForFinished.countDown();
        }

        @Override
        public void onReceivedException(Throwable ex) {
            TestUtils.fail(log, "Exception " + ex);
        }

        @Override
        public void onFinished() {
            waitForFinished.countDown();
        }

    });

    try {
        waitForFinished.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }

    TestUtils.assertTrue(log, "Timeout", waitForFinished.getCount() == 0);

    log.info(")testRemoteStreamsAsyncCallback");
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void asynchronousHttpClientTransferEncodingChunkedTest() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    final String url = "http://localhost:" + PORT + "/chunked";
    final AsynchronousHttpClient http = new AsynchronousHttpClient();
    final AsyncResult<org.apache.awf.web.http.client.Response> cb = new AsyncResult<org.apache.awf.web.http.client.Response>() {

        public void onSuccess(org.apache.awf.web.http.client.Response response) {
            if (response.getBody().equals("arogerab")
                    && response.getHeader("Transfer-Encoding").equals("chunked")) {
                latch.countDown();//from ww  w .j  a v  a2s .  c  o  m
            }
        }

        public void onFailure(Throwable e) {
        }

    };
    // make sure that the http.fetch(..) is invoked from the ioloop thread
    IOLoop.INSTANCE.addCallback(new AsyncCallback() {
        public void onCallback() {
            http.get(url, cb);
        }
    });
    latch.await(10, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void smallHttpPostBodyTest() throws ClientProtocolException, IOException, InterruptedException {

    final String body = "Roger Schildmeijer";
    final CountDownLatch latch = new CountDownLatch(1);
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    asyncHttpClient.preparePost("http://localhost:" + PORT + "/echo").setBody(body)
            .execute(new AsyncCompletionHandler<Response>() {

                @Override/*from   ww  w.j a v a  2  s  .  c  o m*/
                public Response onCompleted(Response response) throws Exception {
                    assertNotNull(response);
                    assertEquals(HttpStatus.SUCCESS_OK.code(), response.getStatusCode());
                    assertEquals("OK", response.getStatusText());
                    assertEquals(5, response.getHeaders().size());
                    String payLoad = response.getResponseBody();
                    assertEquals(body, payLoad);
                    latch.countDown();
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                }
            });

    latch.await();
    assertTrue(latch.getCount() == 0);
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void largeHttpPostBodyTest() throws ClientProtocolException, IOException, InterruptedException {

    String body = "Roger Schildmeijer: 0\n";
    for (int i = 1; i <= 1000; i++) {
        body += "Roger Schildmeijer: " + i + "\n";
    }//from  ww  w .j  a  v a  2s.  c  o m
    final String expectedBody = body;
    final CountDownLatch latch = new CountDownLatch(1);
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    asyncHttpClient.preparePost("http://localhost:" + PORT + "/echo").setBody(body)
            .execute(new AsyncCompletionHandler<Response>() {

                @Override
                public Response onCompleted(Response response) throws Exception {
                    assertNotNull(response);
                    assertEquals(HttpStatus.SUCCESS_OK.code(), response.getStatusCode());
                    assertEquals("OK", response.getStatusText());
                    assertEquals(5, response.getHeaders().size());
                    String payLoad = response.getResponseBody();
                    assertEquals(expectedBody, payLoad);
                    latch.countDown();
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                }
            });

    latch.await();
    assertTrue(latch.getCount() == 0);
}

From source file:org.apache.bookkeeper.replication.TestLedgerUnderreplicationManager.java

/**
 * Test enabling the ledger re-replication. After enableLedegerReplication,
 * should continue getLedgerToRereplicate() task
 *///from   w w  w  . jav  a2 s .  com
@Test(timeout = 20000)
public void testEnableLedgerReplication() throws Exception {
    isLedgerReplicationDisabled = true;
    final LedgerUnderreplicationManager replicaMgr = lmf1.newLedgerUnderreplicationManager();

    // simulate few urLedgers before disabling
    final Long ledgerA = 0xfeadeefdacL;
    final String missingReplica = "localhost:3181";
    try {
        replicaMgr.markLedgerUnderreplicated(ledgerA, missingReplica);
    } catch (UnavailableException e) {
        LOG.debug("Unexpected exception while marking urLedger", e);
        fail("Unexpected exception while marking urLedger" + e.getMessage());
    }

    // disabling replication
    replicaMgr.disableLedgerReplication();
    LOG.debug("Disabled Ledeger Replication");

    String znodeA = getUrLedgerZnode(ledgerA);
    final CountDownLatch znodeLatch = new CountDownLatch(2);
    String urledgerA = StringUtils.substringAfterLast(znodeA, "/");
    String urLockLedgerA = basePath + "/locks/" + urledgerA;
    zkc1.exists(urLockLedgerA, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.NodeCreated) {
                znodeLatch.countDown();
                LOG.debug("Recieved node creation event for the zNodePath:" + event.getPath());
            }

        }
    });
    // getLedgerToRereplicate is waiting until enable rereplication
    Thread thread1 = new Thread() {
        @Override
        public void run() {
            try {
                Long lA = replicaMgr.getLedgerToRereplicate();
                assertEquals("Should be the ledger I just marked", lA, ledgerA);
                isLedgerReplicationDisabled = false;
                znodeLatch.countDown();
            } catch (UnavailableException e) {
                LOG.debug("Unexpected exception while marking urLedger", e);
                isLedgerReplicationDisabled = false;
            }
        }
    };
    thread1.start();

    try {
        assertFalse("shouldn't complete", znodeLatch.await(1, TimeUnit.SECONDS));
        assertTrue("Ledger replication is not disabled!", isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 2, znodeLatch.getCount());

        replicaMgr.enableLedgerReplication();
        znodeLatch.await(5, TimeUnit.SECONDS);
        LOG.debug("Enabled Ledeger Replication");
        assertTrue("Ledger replication is not disabled!", !isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 0, znodeLatch.getCount());
    } finally {
        thread1.interrupt();
    }
}