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:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testGetDhcpRelayProfile() throws IOException, InterruptedException {
    final DhcpRelayProfile mockResponse = new DhcpRelayProfile();
    mockResponse.setId("id");
    mockResponse.setResourceType(ServiceProfileResourceType.DHCP_RELAY_PROFILE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getDhcpRelayProfile("id", new com.google.common.util.concurrent.FutureCallback<DhcpRelayProfile>() {
        @Override/*w  w  w  .  j av a 2s.  com*/
        public void onSuccess(DhcpRelayProfile result) {
            assertEquals(result, mockResponse);
            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.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testGetDhcpRelayService() throws IOException, InterruptedException {
    final DhcpRelayService mockResponse = new DhcpRelayService();
    mockResponse.setId("id");
    mockResponse.setResourceType(LogicalServiceResourceType.DHCP_RELAY_SERVICE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getDhcpRelayService("id", new com.google.common.util.concurrent.FutureCallback<DhcpRelayService>() {
        @Override/*from w w  w.  ja  va  2  s .c om*/
        public void onSuccess(DhcpRelayService result) {
            assertEquals(result, mockResponse);
            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.microsoft.office.core.EventsAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeEvent();//ww  w. ja v a 2  s  . com
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getEvents().getAsync(event.getId()), new FutureCallback<IEvent>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

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

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

From source file:org.kurento.tutorial.helloworld.HelloWorldController.java

@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
private String processRequest(@RequestBody String sdpOffer) {

    final CountDownLatch eventReceived = new CountDownLatch(1);
    // Media Logic
    MediaPipeline pipeline = kurento.createMediaPipeline();
    WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
    webRtcEndpoint.addOnIceGatheringDoneListener(new EventListener<OnIceGatheringDoneEvent>() {
        @Override/*from  w ww  . ja v  a2s  .c o m*/
        public void onEvent(OnIceGatheringDoneEvent event) {
            eventReceived.countDown();
        }
    });

    webRtcEndpoint.connect(webRtcEndpoint);
    webRtcEndpoint.processOffer(sdpOffer);
    webRtcEndpoint.gatherCandidates();

    try {
        eventReceived.await();
    } catch (InterruptedException e) {

    }
    // SDP negotiation (offer and answer)
    String responseSdp = webRtcEndpoint.getLocalSessionDescriptor();
    return responseSdp;
}

From source file:com.googlecode.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final CountDownLatch count = new CountDownLatch(1);
    client.setCredentialsProvider(new BasicCredentialsProvider() {
        @Override/*from w w  w .j a v a  2 s .  c om*/
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:com.metamx.emitter.core.EmitterTest.java

private void waitForEmission(HttpPostEmitter emitter) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    emitter.getExec().execute(new Runnable() {
        @Override/*from   w  ww .  ja v  a 2s .  c  om*/
        public void run() {
            latch.countDown();
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail("latch await() did not complete in 10 seconds");
    }
}

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

private void checkDeleted(final IAttachment attachment) throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(message.getAttachmentsAsync(), new FutureCallback<IAttachments>() {
        @Override/*from  w w w. ja  va2s .c o m*/
        public void onFailure(Throwable err) {
            reportError(err);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IAttachments attachments) {
            Futures.addCallback(attachments.getAsync(attachment.getId()), new FutureCallback<IAttachment>() {
                @Override
                public void onFailure(Throwable err) {
                    reportError(err);
                    cdl.countDown();
                }

                @Override
                public void onSuccess(IAttachment a) {
                    try {
                        assertNull(a);
                    } catch (Throwable t) {
                        reportError(t);
                    }
                    cdl.countDown();
                }
            });
        }
    });

    cdl.await();
}

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

private void createAndCheck() throws Exception {
    prepareFolder();//from  www  . j a  va2 s  .c o  m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(folder.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

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

From source file:gov.va.isaac.workflow.engine.RemoteSynchronizer.java

/**
 * Request a remote synchronization. This call blocks until the operation is complete,
 * or the thread is interrupted./*w w  w.j  a  v a  2 s.  c om*/
 * 
 * @throws InterruptedException
 */
public SynchronizeResult blockingSynchronize() throws InterruptedException {
    log.info("Queuing a blocking sync request");
    final MutableObject<SynchronizeResult> result = new MutableObject<SynchronizeResult>();
    final CountDownLatch cdl = new CountDownLatch(1);
    Consumer<SynchronizeResult> callback = new Consumer<SynchronizeResult>() {
        @Override
        public void accept(SynchronizeResult t) {
            result.setValue(t);
            cdl.countDown();
        }
    };

    synchronize(callback);
    cdl.await();
    return result.getValue();
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testPeriodicHandshake() throws Exception {
    final int numHosts = 3;
    final int numStreamsPerHost = 3;
    final int initialPort = 5000;

    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    Map<SocketAddress, ServerInfo> serverInfoMap = new HashMap<SocketAddress, ServerInfo>();
    Map<SocketAddress, MockServerInfoService> mockServiceMap = new HashMap<SocketAddress, MockServerInfoService>();
    final Map<SocketAddress, CountDownLatch> hostDoneLatches = new HashMap<SocketAddress, CountDownLatch>();
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_stream_" + j, address.toString());
        }/*from  w ww.  j  a v a  2s  . c  o  m*/
        Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address,
                serverInfo);
        builder.provideProxyClient(address, mockProxyClient.getLeft());
        serverInfoMap.put(address, serverInfo);
        mockServiceMap.put(address, mockProxyClient.getRight());
        hostDoneLatches.put(address, new CountDownLatch(2));
    }

    final Map<SocketAddress, ServerInfo> results = new HashMap<SocketAddress, ServerInfo>();
    final CountDownLatch doneLatch = new CountDownLatch(numHosts);
    ProxyListener listener = new ProxyListener() {
        @Override
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            synchronized (results) {
                results.put(address, serverInfo);
                CountDownLatch latch = hostDoneLatches.get(address);
                if (null != latch) {
                    latch.countDown();
                }
            }
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    TestHostProvider rs = new TestHostProvider();
    ProxyClientManager clientManager = createProxyClientManager(builder, rs, 50L);
    clientManager.setPeriodicHandshakeEnabled(false);
    clientManager.registerProxyListener(listener);

    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        rs.addHost(address);
        clientManager.createClient(address);
    }

    // make sure the first 3 handshakes going through
    doneLatch.await();

    assertEquals("Handshake should return server info", numHosts, results.size());
    assertTrue("Handshake should get all server infos", Maps.difference(serverInfoMap, results).areEqual());

    // update server info
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_new_stream_" + j, address.toString());
        }
        MockServerInfoService service = mockServiceMap.get(address);
        serverInfoMap.put(address, serverInfo);
        service.updateServerInfo(serverInfo);
    }

    clientManager.setPeriodicHandshakeEnabled(true);
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        CountDownLatch latch = hostDoneLatches.get(address);
        latch.await();
    }

    assertTrue("Periodic handshake should update all server infos",
            Maps.difference(serverInfoMap, results).areEqual());
}