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:com.vmware.photon.controller.deployer.dcp.DeployerXenonServiceHostTest.java

private void waitForServicesStartup(DeployerXenonServiceHost host)
        throws TimeoutException, InterruptedException, NoSuchFieldException, IllegalAccessException {

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            DeployerXenonServiceHost.FACTORY_SERVICE_FIELD_NAME_SELF_LINK,
            DeployerXenonServiceHost.FACTORY_SERVICES);
    serviceSelfLinks.add(DeployerXenonServiceHost.UPLOAD_VIB_SCHEDULER_SERVICE);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override/*w w  w  . j a v  a 2 s.co  m*/
        public void handle(Operation completedOp, Throwable failure) {
            latch.countDown();
        }
    };

    String[] links = new String[serviceSelfLinks.size()];
    host.registerForServiceAvailability(handler, serviceSelfLinks.toArray(links));
    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new TimeoutException();
    }
}

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

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from   www .j av a2 s . co  m*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            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.ClusterRestApiTest.java

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//  ww  w. jav a2  s  .  co  m
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            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:org.wisdom.framework.vertx.FileUploadTest.java

@Test
public void testFileUploadOfSmallFilesOnDisk() throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("request.body.max.size", 100 * 1024)).thenReturn(100 * 1024);
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);
    // Reduce it to force disk storage
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE))
            .thenReturn(1024l);/*from  w w  w. j a  v a 2 s.  c  o m*/
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(-1l);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() throws IOException {
            FileItem item = context().file("upload");
            if (item.isInMemory()) {
                return badRequest("on disk expected");
            }
            if (!item.name().equals("my-file.dat")) {
                return badRequest("broken name");
            }
            if (item.size() != 2048) {
                return badRequest("broken file");
            }

            if (!context().form().get("comment").get(0).equals("my description")) {
                return badRequest("broken form");
            }

            final File file = item.toFile();
            if (!file.exists() && file.length() != 2048) {
                return badRequest("broken file to file handling");
            }

            return ok(item.stream()).as(MimeTypes.BINARY);
        }
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.vertx = vertx;
    server.configuration = configuration;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    // Now start bunch of clients
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(NUMBER_OF_CLIENTS);

    int port = server.httpPort();

    for (int i = 1; i < NUMBER_OF_CLIENTS + 1; ++i) {
        clients.submit(new Client(startSignal, doneSignal, port, i, 2048));
    }

    startSignal.countDown(); // let all threads proceed
    if (!doneSignal.await(120, TimeUnit.SECONDS)) { // wait for all to finish
        Assert.fail("testFileUploadOfSmallFilesOnDisk - Did not server all requests in time");
    }

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(NUMBER_OF_CLIENTS);
}

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

@Test
public void testGetClusterAsync() throws IOException, InterruptedException {
    final Cluster cluster = new Cluster();
    cluster.setName("clusterName");
    cluster.setState(ClusterState.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(cluster);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getClusterAsync("foo", new FutureCallback<Cluster>() {
        @Override//from w w  w.  ja  v  a 2  s.  c om
        public void onSuccess(Cluster result) {
            assertEquals(result, cluster);
            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.ClusterRestApiTest.java

@Test
public void testGetClusterAsync() throws IOException, InterruptedException {
    final Cluster cluster = new Cluster();
    cluster.setName("clusterName");
    cluster.setState(ClusterState.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(cluster);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getClusterAsync("foo", new FutureCallback<Cluster>() {
        @Override//from   www .  ja v  a  2s . c om
        public void onSuccess(Cluster result) {
            assertEquals(result, cluster);
            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:de.taimos.httputils.Tester1.java

/**
 * /*  w  w w .  ja  va  2s. c  o m*/
 */
@Test
public void testGetAsync() throws InterruptedException {
    final CountDownLatch cdl = new CountDownLatch(1);
    WS.url("http://www.heise.de").getAsync(new HTTPResponseCallback() {

        @Override
        public void response(HttpResponse response) {
            Assert.assertEquals(WS.getStatus(response), 200);
            Assert.assertTrue(WS.isStatusOK(response));
            final String body = WS.getResponseAsString(response);
            Assert.assertNotNull(body);
            Assert.assertFalse(body.isEmpty());
            cdl.countDown();
        }

        @Override
        public void fail(Exception e) {
            System.out.println(e);
        }
    });
    Assert.assertTrue(cdl.await(10, TimeUnit.SECONDS));
}

From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceInstance.java

private static boolean waitForListeningNotification(OSProcessHandler processHandler, Project project) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final Ref<Boolean> result = new Ref<>(false);
    ProcessAdapter listener = new ProcessAdapter() {
        public void onTextAvailable(ProcessEvent event, Key outputType) {
            if (!StringUtil.isEmpty(event.getText())) {
                if (outputType == ProcessOutputTypes.STDOUT || outputType == ProcessOutputTypes.SYSTEM) {
                    if (log.isDebugEnabled()) {
                        log.debug("Language Service response: " + event.getText());
                    }// w  w w .  jav  a 2 s  .  co  m
                    final String text = event.getText().trim();
                    if (text.startsWith("JS GraphQL listening on")) {
                        result.set(true);
                        countDownLatch.countDown();
                    }
                } else if (outputType == ProcessOutputTypes.STDERR) {
                    result.set(false);
                    countDownLatch.countDown();
                    JSGraphQLLanguageUIProjectService.showConsole(project);
                }
            }
        }

        public void processTerminated(ProcessEvent event) {
            countDownLatch.countDown();
        }
    };
    processHandler.addProcessListener(listener);
    processHandler.startNotify();
    try {
        log.debug("Start waiting for ready start");
        countDownLatch.await(30L, TimeUnit.SECONDS);
        log.debug("End waiting for process starting. Result " + result.get());
    } catch (InterruptedException e) {
        log.debug("Process interrupted while waiting ready state", e);
    }

    processHandler.removeProcessListener(listener);
    return result.get();
}

From source file:org.wisdom.framework.vertx.FileUploadTest.java

@Test
public void testFileUploadOfSmallFilesWithAsyncDownload() throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("request.body.max.size", 100 * 1024)).thenReturn(100 * 1024);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE))
            .thenReturn(DiskFileUpload.MINSIZE);
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(-1l);
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            final FileItem item = context().file("upload");
            if (!item.isInMemory()) {
                return badRequest("In memory expected");
            }/*from  www .j a  va 2s . c o  m*/
            if (!item.name().equals("my-file.dat")) {
                return badRequest("broken name");
            }
            if (item.size() != 2048) {
                return badRequest("broken file");
            }

            if (!context().form().get("comment").get(0).equals("my description")) {
                return badRequest("broken form");
            }

            return async(new Callable<Result>() {
                @Override
                public Result call() throws Exception {
                    return ok(item.stream()).as(MimeTypes.BINARY);
                }
            });
        }
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    // Now start bunch of clients
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(NUMBER_OF_CLIENTS);

    int port = server.httpPort();

    for (int i = 1; i < NUMBER_OF_CLIENTS + 1; ++i) // create and start threads
        clients.submit(new Client(startSignal, doneSignal, port, i, 2048));

    startSignal.countDown(); // let all threads proceed
    if (!doneSignal.await(60, TimeUnit.SECONDS)) { // wait for all to finish
        Assert.fail("testFileUploadOfSmallFilesWithAsyncDownload - Client not served in time");
    }
    assertThat(failure).isEmpty();
    assertThat(success).hasSize(NUMBER_OF_CLIENTS);
}

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

@Test
public void testResizeAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.resizeAsync("dummy-cluster-id", 100, new FutureCallback<Task>() {
        @Override/*from  ww w.j  av a2  s. c o  m*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}