Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java

@Test
public void testWithNamespaceAndLostSession() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
            .retryPolicy(new ExponentialBackoffRetry(100, 3)).namespace("aisa").build();
    try {/*from  ww  w .j  a  va2s.c  om*/
        client.start();

        client.create().forPath("/test-me");

        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        server.stop();

        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            client.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
            // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));

        timing.sleepABit();

        server = new TestingServer(server.getPort(), server.getTempDirectory());
        Assert.assertTrue(timing.awaitLatch(latch));

        timing.sleepABit();

        Assert.assertNull(client.checkExists().forPath("/test-me"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.kurento.kmf.media.HttpGetEndpointAsyncTest.java

/**
 * Test for {@link MediaSessionStartedEvent}
 * //from   ww  w. j a  v a 2 s  . c om
 * @throws InterruptedException
 */
@Test
public void testEventMediaSessionStarted() throws InterruptedException {

    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    player.connect(httpEp);

    final CountDownLatch eosLatch = new CountDownLatch(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });

    final BlockingQueue<ListenerRegistration> events = new ArrayBlockingQueue<ListenerRegistration>(1);
    httpEp.addMediaSessionStartedListener(new MediaEventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    }, new Continuation<ListenerRegistration>() {

        @Override
        public void onSuccess(ListenerRegistration result) {
            events.add(result);
        }

        @Override
        public void onError(Throwable cause) {
            throw new KurentoMediaFrameworkException(cause);
        }
    });

    ListenerRegistration reg = events.poll(500, MILLISECONDS);
    Assert.assertNotNull(reg);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        // This should trigger MediaSessionStartedEvent
        httpclient.execute(new HttpGet(httpEp.getUrl()));
    } catch (ClientProtocolException e) {
        throw new KurentoMediaFrameworkException(e);
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException(e);
    }

    try {
        eosLatch.await(500, MILLISECONDS);
    } catch (InterruptedException e) {
        player.release();
        throw new KurentoMediaFrameworkException(e);
    }

}

From source file:com.ottogroup.bi.streaming.runtime.StreamingAppRuntimeTest.java

/**
 * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being
 * provided null as input//from   w w  w . j a  v  a2  s  .co m
 */
@Test
public void testParseCommandLine_withNullInput() throws Exception {
    final CommandLine cl = new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(null);
    Assert.assertNotNull(cl);
    Assert.assertFalse(cl.hasOption(StreamingAppRuntime.CLI_CONFIG_FILE));
}

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

/**
 * https://github.com/couchbase/couchbase-lite-android/issues/197
 * Gzipped attachment support with Replicator does not seem to be working
 * <p/>/*from   w  ww.j  a  v  a 2 s.  c  o  m*/
 * https://github.com/couchbase/couchbase-lite-android/blob/master/src/androidTest/java/com/couchbase/lite/replicator/ReplicationTest.java#L2071
 */
public void testGzippedAttachment() throws Exception {
    if (!syncgatewayTestsEnabled()) {
        return;
    }

    Database pushDB = manager.getDatabase("pushdb");
    Database pullDB = manager.getDatabase("pulldb");

    String attachmentName = "attachment.png";

    // 1. store attachment with doc
    // 1.a load attachment data from asset
    InputStream attachmentStream = getAsset(attachmentName);
    java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
    IOUtils.copy(attachmentStream, baos);
    baos.close();
    attachmentStream.close();
    byte[] bytes = baos.toByteArray();

    // 1.b apply GZIP + Base64
    String attachmentBase64 = Base64.encodeBytes(bytes, Base64.GZIP);

    // 1.c attachment Map object
    Map<String, Object> attachmentMap = new HashMap<String, Object>();
    attachmentMap.put("content_type", "image/png");
    attachmentMap.put("data", attachmentBase64);
    attachmentMap.put("encoding", "gzip");
    attachmentMap.put("length", bytes.length);

    // 1.d attachments Map object
    Map<String, Object> attachmentsMap = new HashMap<String, Object>();
    attachmentsMap.put(attachmentName, attachmentMap);

    // 1.e document property Map object
    Map<String, Object> propsMap = new HashMap<String, Object>();
    propsMap.put("_attachments", attachmentsMap);

    // 1.f store document into database
    Document putDoc = pushDB.createDocument();
    putDoc.putProperties(propsMap);
    String docId = putDoc.getId();

    URL remote = getReplicationURL();

    // 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(30, 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(30, TimeUnit.SECONDS));

    Log.e(TAG, "Fetching doc1 via id: " + docId);
    Document pullDoc = pullDB.getDocument(docId);
    assertNotNull(pullDoc);
    assertTrue(pullDoc.getCurrentRevisionId().startsWith("1-"));
    Attachment attachment = pullDoc.getCurrentRevision().getAttachment(attachmentName);

    assertEquals(bytes.length, attachment.getLength());
    assertEquals("image/png", attachment.getContentType());
    assertEquals("gzip", attachment.getMetadata().get("encoding"));

    InputStream is = attachment.getContent();
    byte[] receivedBytes = getBytesFromInputStream(is);
    assertEquals(bytes.length, receivedBytes.length);
    is.close();

    assertTrue(Arrays.equals(bytes, receivedBytes));

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

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

From source file:com.bt.aloha.batchtest.scenarios.TwoCallsSharingCallLegScenario.java

@Override
protected void startScenario(String scenarioId) throws Exception {
    updateScenario(scenarioId, SCENARIO_STARTED);

    String firstDialogId = outboundCallLegBean.createCallLeg(getFromAddressUri(), getTestEndpointUri());
    String secondDialogId = outboundCallLegBean.createCallLeg(getFromAddressUri(), getTestEndpointUri());

    latchMap.put(scenarioId, new CountDownLatch(1));
    String callId = callBean.joinCallLegs(firstDialogId, secondDialogId, AutoTerminateAction.True);
    callScenarioMap.put(callId, new ScenarioData(scenarioId, callId));
    latchMap.get(scenarioId).countDown();
    updateScenario(scenarioId, "1st call initiated: " + callId);
}

From source file:com.couchbase.client.ViewNodeTest.java

private HttpOperation createHttpOperation() {
    View view = new View("a", "b", "c", true, true);
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<ViewResponse> crv = new HttpFuture<ViewResponse>(couchLatch, 60000);
    final HttpRequest request = new BasicHttpRequest("GET", "/pools", HttpVersion.HTTP_1_1);
    return new NoDocsOperationImpl(request, view, new ViewOperation.ViewCallback() {
        private ViewResponse vr = null;

        @Override/*from  w  w  w  . ja  va 2s  . c o  m*/
        public void receivedStatus(OperationStatus status) {
            crv.set(vr, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void gotData(ViewResponse response) {
            vr = response;
        }
    });
}

From source file:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadUsingNonAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from   ww  w  .  j  av  a  2 s . com
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getOutputStream().write(new byte[] { 0x42 });
            response.getOutputStream().close();
        }
    });
    server.start();

    Properties custom = new Properties();
    custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true");
    String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort());
    DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom);

    try {
        final CountDownLatch latch = new CountDownLatch(1);
        DownloadFuture df = dm.download("mvn:x.y/z/1.0");
        df.addListener(new FutureListener<DownloadFuture>() {
            @Override
            public void operationComplete(DownloadFuture future) {
                latch.countDown();
            }
        });

        latch.await(30, TimeUnit.SECONDS);
        assertNotNull(df.getUrl());
        assertNotNull(df.getFile());
        assertEquals("z-1.0.jar", df.getFile().getName());
        LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
    } finally {
        server.stop();
    }
}

From source file:siia.booking.integration.FlightNotificationsSpelTest.java

@Test
public void notificationShouldArriveAtSmsAdapter() throws Exception {
    TripNotification notification = mock(TripNotification.class);
    Message tripNotificationMessage = MessageBuilder.withPayload(notification).build();
    CountDownLatch notifierInvoked = new CountDownLatch(1);
    doAnswer(countsDownLatch(notifierInvoked)).when(smsNotifier).notify(notification);
    tripNotifications.send(tripNotificationMessage);
    notifierInvoked.await(100, MILLISECONDS);
    verify(smsNotifier).notify(notification);
}

From source file:com.microsoft.office.core.FolderAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeFolder();//from   w w w  . jav a2s.  c om
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IFolder result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

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

/**
 * Asynchronous query execution using callbacks.
 *///from w  w w. j av  a2 s.co m
@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)));
}