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.palantir.docker.compose.logging.FileLogCollectorShould.java

@Test
public void collect_logs_in_parallel_for_two_containers() throws IOException, InterruptedException {
    when(compose.ps()).thenReturn(TestContainerNames.of("db", "db2"));
    CountDownLatch dbLatch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("log", outputStream);
        dbLatch.countDown();//from  www  .j  av a2  s .c o  m
        return true;
    });
    CountDownLatch db2Latch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db2"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("other", outputStream);
        db2Latch.countDown();
        return true;
    });

    logCollector.startCollecting(compose);
    assertThat(dbLatch.await(1, TimeUnit.SECONDS), is(true));
    assertThat(db2Latch.await(1, TimeUnit.SECONDS), is(true));

    assertThat(logDirectory.listFiles(),
            arrayContainingInAnyOrder(fileWithName("db.log"), fileWithName("db2.log")));
    assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log")));
    assertThat(new File(logDirectory, "db2.log"), is(fileContainingString("other")));

    logCollector.stopCollecting();
}

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

@Test
public void testListAllAsync() throws Exception {
    Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    Flavor flavor2 = new Flavor();
    flavor2.setId("flavor2");
    flavor2.setKind("vm");

    final ResourceList<Flavor> flavorResourceList = new ResourceList<>(Arrays.asList(flavor1, flavor2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavorResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.listAllAsync(new FutureCallback<ResourceList<Flavor>>() {
        @Override//from   www. j av a 2s . c o  m
        public void onSuccess(@Nullable ResourceList<Flavor> result) {
            assertEquals(result.getItems(), flavorResourceList.getItems());
            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.FlavorRestApiTest.java

@Test
public void testListAllAsync() throws Exception {
    Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    Flavor flavor2 = new Flavor();
    flavor2.setId("flavor2");
    flavor2.setKind("vm");

    final ResourceList<Flavor> flavorResourceList = new ResourceList<>(Arrays.asList(flavor1, flavor2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavorResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.listAllAsync(new FutureCallback<ResourceList<Flavor>>() {
        @Override/*from w  w  w .  j ava 2s  .com*/
        public void onSuccess(@Nullable ResourceList<Flavor> result) {
            assertEquals(result.getItems(), flavorResourceList.getItems());
            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.eclipse.hono.example.ExampleSender.java

/**
 * Reads user input from the console and sends it to the Hono server.
 *//*w  w  w.  j a v a2  s.com*/
@EventListener(classes = { ApplicationReadyEvent.class })
public void readMessagesFromStdin() {

    Runnable reader = new Runnable() {

        public void run() {
            try {
                // give Spring Boot some time to log its startup messages
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
            LOG.info("sender for tenant [{}] created successfully", tenantId);
            LOG.info("Enter some message(s) (hit return to send, ctrl-c to quit)");
            String input;
            Scanner scanner = new Scanner(System.in);
            do {
                input = scanner.nextLine();
                final String msg = input;
                if (!msg.isEmpty()) {

                    final Map<String, Object> properties = new HashMap<>();
                    properties.put("my_prop_string", "I'm a string");
                    properties.put("my_prop_int", 10);
                    final CountDownLatch latch = new CountDownLatch(1);
                    Future<Boolean> sendTracker = Future.future();
                    sendTracker.setHandler(s -> {
                        if (s.failed()) {
                            LOG.info(s.cause().getMessage());
                        }
                    });

                    getRegistrationAssertion().compose(token -> {
                        return send(msg, properties, token);
                    }).compose(sent -> {
                        latch.countDown();
                        sendTracker.complete();
                    }, sendTracker);

                    try {
                        if (!latch.await(2, TimeUnit.SECONDS)) {
                            sendTracker.fail("cannot connect to server");
                        }
                    } catch (InterruptedException e) {
                        // nothing to do
                    }
                }
            } while (!input.isEmpty());
            scanner.close();
        };
    };
    new Thread(reader).start();
}

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // ping publish
    // wait for notification
    // response/*from  w w  w.j  a  v  a 2s.c  o m*/
    // error if timeout

    if (req.getPathInfo().equals("/feed")) {
        // serve ATOM feed
        resp.getWriter().write(atom(getFragment(req)));
    } else {
        // publish

        UUID id = UUID.randomUUID();
        String publicationUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/feed#" + id;

        String hubUrl = System.getProperty("hub.url");
        if (hubUrl == null) {
            throw new RuntimeException("System properti hub.url missing");
        }

        try {
            CountDownLatch latch = new CountDownLatch(1);
            publications.put(id, latch);

            HttpPost publication = new HttpPost(hubUrl);
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("hub.mode", "publish"));
            parameters.add(new BasicNameValuePair("hub.url", publicationUrl));

            publication.setEntity(new UrlEncodedFormEntity(parameters));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse publicationResponse = httpClient.execute(publication);

            if (publicationResponse.getStatusLine().getStatusCode() == 204) {
                try {
                    if (latch.await(20000, TimeUnit.MILLISECONDS)) {
                        // all happy, return
                        return;
                    } else {
                        // timeout
                        resp.sendError(591);
                    }
                } catch (InterruptedException e) {
                    // interrupted
                    resp.sendError(592);
                }
            } else {
                // publication failed
                resp.sendError(publicationResponse.getStatusLine().getStatusCode(),
                        publicationResponse.getStatusLine().getReasonPhrase());
            }
        } finally {
            // try to prevent memory leaks
            publications.remove(id);
        }
    }
}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final MessageConverter<TBase<?, ?>> messageConverter = new BypassMessageConverter<TBase<?, ?>>();
    final MessageSerializer<ByteMessage> thriftMessageSerializer = new ThriftUdpMessageSerializer(
            messageConverter, ThriftUdpMessageSerializer.UDP_MAX_PACKET_LENGTH) {
        @Override// ww  w. j  a  v a  2s  .  c  o m
        protected boolean isLimit(int interBufferSize) {
            final boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };

    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100,
            thriftMessageSerializer);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:org.fcrepo.sequencer.mods2dc.MODSExtractionSequencerIT2.java

public void titleSetTest() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    final String parentPath = "/" + UUID.randomUUID().toString();
    final SequencingListener listener = addSequenceListener(latch, parentPath);
    // addSequencingListeners(session);

    final Node rootNode = session.getRootNode();
    final Node parentNode = rootNode.addNode(UUID.randomUUID().toString());

    session.save();//  w  w w  .  j  av  a2  s  .  c  om
    // final FedoraResource parent = new FedoraResourceImpl(parentNode);

    final FedoraResource parent = nodeService.findOrCreateObject(session, parentPath);

    session.save();

    final Datastream ds = dsService.createDatastream(session, parentPath + "/mods", "text/xml", "mods.xml",
            this.getClass().getResourceAsStream("/mods.xml"));

    session.save();

    latch.await(5, TimeUnit.SECONDS);
    // this.getOutputNode(null);

    System.out.println("reached the end " + ds);

}

From source file:interactivespaces.util.web.HttpClientHttpContentCopierTest.java

/**
 * Test a file upload from a file.//from   w w  w  .  ja  va2  s  .  co m
 */
@Test
public void testFileUploadFile() throws Exception {
    File source = getTempFile();
    final File destination = getTempFile();

    Files.writeFile(source, TEST_CONTENT);

    final AtomicReference<Map<String, String>> receivedParameters = new AtomicReference<Map<String, String>>();
    final CountDownLatch latch = new CountDownLatch(1);

    webServer.setHttpFileUploadListener(new HttpFileUploadListener() {
        @Override
        public void handleHttpFileUpload(HttpFileUpload fileUpload) {
            fileUpload.moveTo(destination);
            receivedParameters.set(fileUpload.getParameters());
            latch.countDown();
        }
    });

    String sourceParameterName = "myfile";
    Map<String, String> expectedParameters = Maps.newHashMap();
    expectedParameters.put("foo", "bar");
    expectedParameters.put("bletch", "spam");

    copier.copyTo(getUrlPrefix(), source, sourceParameterName, expectedParameters);

    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

    Assert.assertEquals(TEST_CONTENT, Files.readFile(destination).trim());
    Assert.assertEquals(expectedParameters, receivedParameters.get());
}

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

@Test
public void testSession() throws InterruptedException, IOException {
    Router router = prepareServer();//from ww w.ja  v  a2s  . co m

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            context().session().put("id", context().parameter("id"));
            return ok("Alright");
        }

        @SuppressWarnings("unused")
        public Result logged() {
            String id = context().session().get("id");
            if (id == null) {
                return badRequest("no session");
            } else {
                return ok(id);
            }
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    final Route route2 = new RouteBuilder().route(HttpMethod.GET).on("/logged").to(controller, "logged");
    configureRouter(router, route1, route2);

    server.start();
    waitForStart(server);

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

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {
        executor.submit(new LoggedClient(startSignal, doneSignal, port, i, true));
    }

    startSignal.countDown(); // let all threads proceed
    doneSignal.await(60, TimeUnit.SECONDS); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);

}

From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testGetFabricNodeState() throws IOException, InterruptedException {
    final FabricNodeState mockResponse = new FabricNodeState();
    mockResponse.setState(com.vmware.photon.controller.nsxclient.datatypes.FabricNodeState.SUCCESS);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getFabricNodeState("nodeId",
            new com.google.common.util.concurrent.FutureCallback<FabricNodeState>() {
                @Override/*w w w  .j  a v a2s.  co m*/
                public void onSuccess(FabricNodeState 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));
}