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:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadAlreadyDownloadedArtifact() throws Exception {
    DownloadManager dm = createDownloadManager("non-existing-settings.xml", null);
    File dir = new File(systemRepo, "x/y/z/1.0");
    dir.mkdirs();/*from  w  w  w  .j  ava 2  s. c o  m*/
    FileOutputStream artifact = new FileOutputStream(new File(dir, "z-1.0.jar"));
    artifact.write(new byte[] { 0x42 });
    artifact.close();

    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());
}

From source file:com.mastfrog.scamper.SctpServerTest.java

@Test
public void test(Sender sender, CountDownLatch latch, MessageHandlerMapping mapping) throws Throwable {
    assertNotNull(mapping.get(INBOUND));
    assertNotNull(mapping.get(OUTBOUND));

    sender.send(new Address("127.0.0.1", port), INBOUND.newMessage(newThing(1, longString)));
    latch.await(1, TimeUnit.SECONDS);
    errors.maybeThrow();/* ww  w.  jav a  2  s  . co  m*/
    assertNotNull(inInstance);
    inInstance.await();
    errors.maybeThrow();
    assertFalse(inInstance.things.isEmpty());
    assertEquals(longString, inInstance.things.iterator().next().what);
    assertEquals(1, inInstance.things.iterator().next().index);
    for (int i = 0; outInstance == null && i < 100; i++) {
        Thread.sleep(20);
    }
    assertNotNull(outInstance);
    System.out.println("Wiat on ");
    outInstance.await();
    System.out.println("done");
    errors.maybeThrow();
    assertFalse(outInstance.strings.isEmpty());
    assertEquals("Received " + longString, outInstance.strings.iterator().next());
}

From source file:io.fabric8.tooling.archetype.commands.ArchetypeCreateAction.java

/**
 * Fetches archetype from the configured repositories
 * TODO: make this code available to hawt.io/JMX too
 *
 * @param archetype//from  ww w.  j  av  a 2s . co m
 * @return
 */
private InputStream fetchArchetype(Archetype archetype) throws IOException {
    MavenConfigurationImpl config = new MavenConfigurationImpl(
            new PropertiesPropertyResolver(System.getProperties()), "org.ops4j.pax.url.mvn");
    config.setSettings(new MavenSettingsImpl(config.getSettingsFileUrl(), config.useFallbackRepositories()));
    DownloadManager dm = new DownloadManager(config, Executors.newSingleThreadExecutor());

    final CountDownLatch latch = new CountDownLatch(1);
    DownloadFuture df = dm.download(
            String.format("mvn:%s/%s/%s", archetype.groupId, archetype.artifactId, archetype.version));
    df.addListener(new FutureListener<DownloadFuture>() {
        @Override
        public void operationComplete(DownloadFuture future) {
            latch.countDown();
        }
    });

    try {
        latch.await(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("Failed to download " + archetype);
        throw new IOException(e.getMessage(), e);
    }
    System.out.println("Downloaded archetype (" + df.getFile() + ")");

    return new FileInputStream(df.getFile());
}

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);/*from ww  w.ja  v  a  2 s .c  o 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());
}

From source file:com.baidu.oped.apm.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);

    UdpDataSender sender = new UdpDataSender("localhost", 9009, "test", 128, 1000, 1024 * 64 * 100) {
        @Override/*from  ww w . j av a  2s  . c om*/
        protected boolean isLimit(int interBufferSize) {
            boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };
    try {
        sender.send(tbase);
        latch.await(5000, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:io.opentracing.contrib.elasticsearch5.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 InetSocketTransportAddress(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);//from   w  w w  .j av a 2 s . c o  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());
}

From source file:com.vmware.photon.controller.api.client.resource.SystemStatusApiTest.java

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final SystemStatus systemStatus = new SystemStatus();
    systemStatus.setStatus(StatusType.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(systemStatus);

    setupMocks(serialized, HttpStatus.SC_OK);

    SystemStatusApi systemStatusApi = new SystemStatusApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    systemStatusApi.getSystemStatusAsync(new FutureCallback<SystemStatus>() {
        @Override//from  w  ww.  ja  va  2s . c om
        public void onSuccess(@Nullable SystemStatus result) {
            assertEquals(result, systemStatus);
            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.api.client.resource.SystemStatusRestApiTest.java

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final SystemStatus systemStatus = new SystemStatus();
    systemStatus.setStatus(StatusType.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(systemStatus);

    setupMocks(serialized, HttpStatus.SC_OK);

    SystemStatusApi systemStatusApi = new SystemStatusRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    systemStatusApi.getSystemStatusAsync(new FutureCallback<SystemStatus>() {
        @Override//from  ww w  .java  2 s  .  co  m
        public void onSuccess(@Nullable SystemStatus result) {
            assertEquals(result, systemStatus);
            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.googlecode.android_scripting.facade.CameraFacade.java

private void autoFocus(final BooleanResult result, final Camera camera) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    {/*  w ww. j  a  v  a 2  s . c  o m*/
        camera.autoFocus(new AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                result.mmResult = success;
                latch.countDown();
            }
        });
        latch.await(10, TimeUnit.SECONDS);
    }
}

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

@Test
public void sseEventsWithoutToken() throws Exception {

    // TODO: define an entity model for the response message:
    // {"timestamp":1490099424012,"status":401,"error":"Unauthorized","message":"Unauthorized","path":"/api/v1/event/reservations"}

    ResponseEntity<JsonNode> response = restTemplate().postForEntity("/api/v1/event/reservations", null,
            JsonNode.class);
    assertThat(response.getStatusCode()).as("reservations post status code").isEqualTo(HttpStatus.UNAUTHORIZED);

    // 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, 1);

    // Using a random uuid should not work either.
    String uuid = UUID.randomUUID().toString();
    URI uri = resolveURI(EventBusToServerSentEvents.DEFAULT_PATH + "/" + uuid);
    try (EventSource eventSource = new EventSource.Builder(handler, uri).build()) {
        eventSource.start();/*from   w  ww.j a  va  2  s.c  o  m*/

        assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
        assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onError");
        assertThat(invocations.get(0).getArgs()[0].toString()).isEqualTo(
                "com.launchdarkly.eventsource.UnsuccessfulResponseException: Unsuccessful response code received from stream: 404");
    }
}