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:net.niyonkuru.koodroid.webview.BlockingWebView.java

public void load(final String url) throws IOException {
    loadOnUiThread(url);/*ww  w  . ja va2 s.co  m*/

    try {
        mCountDownLatch = new CountDownLatch(1);
        mCountDownLatch.await();
        throwPendingException();
    } catch (InterruptedException e) {
        super.stopLoading();
    }
}

From source file:example.springdata.cassandra.people.ReactiveCassandraTemplateIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining. It prints
 * the two counts ({@code 4} and {@code 6}) to the console.
 *//*from   w w  w .j av  a  2 s  .com*/
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    template.count(Person.class) //
            .doOnNext(System.out::println) //
            .thenMany(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))
            .flatMap(template::insert) //
            .last() //
            .flatMap(v -> template.count(Person.class)) //
            .doOnNext(System.out::println) //
            .doOnTerminate(countDownLatch::countDown) //
            .subscribe();

    countDownLatch.await();
}

From source file:test.config.WebAppInitializer.java

private void setupForwardScenario(ServletContext servletContext) {

    CountDownLatch latch = new CountDownLatch(1);

    Dynamic servlet;//from w  ww  . j  a  v a2s  .  co m
    servlet = servletContext.addServlet("ForwardA",
            new ForwardingServlet("A", "/forwardScenarioB/b?b=B", latch));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/forwardScenarioA/*");

    servlet = servletContext.addServlet("ForwardB",
            new ForwardingServlet("B", "/forwardScenarioC/c?c=C", null));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/forwardScenarioB/*");

    servlet = servletContext.addServlet("ForwardC",
            new ForwardingAsyncServlet("C", "/forwardScenarioD/d?d=D", latch));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/forwardScenarioC/*");

    servlet = servletContext.addServlet("ForwardD", new ForwardingServlet("D", "/WEB-INF/page.jsp", null));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/forwardScenarioD/*");
}

From source file:org.kurento.repository.OneRecordingServer.java

private void prepareToDownloadVideo(RepositoryItem repositoryItem) throws InterruptedException {
    RepositoryHttpPlayer player = repositoryItem.createRepositoryHttpPlayer("video-download");
    log.info("The video can be downloaded with GET from the URL: " + player.getURL());

    player.setAutoTerminationTimeout(30 * 60 * 1000);
    log.info("The player will be auto-terminated 30 min after the last downloading of content (http GET)");

    final CountDownLatch terminatedLatch = new CountDownLatch(1);

    player.addSessionStartedListener(new RepositoryHttpEventListener<HttpSessionStartedEvent>() {
        @Override/*from  w  w w  .ja v  a2 s .  c  om*/
        public void onEvent(HttpSessionStartedEvent event) {
            log.info("Downloading started");
        }
    });

    player.addSessionTerminatedListener(new RepositoryHttpEventListener<HttpSessionTerminatedEvent>() {
        @Override
        public void onEvent(HttpSessionTerminatedEvent event) {
            log.info("Downloading terminated");
            terminatedLatch.countDown();
        }
    });

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

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

@Test(timeout = 60000)
public void updateTest() throws Exception {
    counter = new CountDownLatch(1);
    // create contact first
    prepareContact();/*from   ww w  . jav a  2  s  . c om*/
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                updateAndCheck();
                // clean up
                removeContact();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        };
    });
    counter.await();
}

From source file:com.datatorrent.demos.adsdimension.KafkaApplicationTest.java

@Test
public void testApplication() throws Exception {
    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.set("dt.operator.Kafka.prop.configProperties(metadata.broker.list)", "localhost:9092");
    conf.set("dt.operator.Kafka.prop.topic", kafkaTopic);
    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "1");

    lma.prepareDAG(new KafkaApplication(), conf);
    LocalMode.Controller lc = lma.getController();
    lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();/*from  w  w w. j  av  a2 s  .co m*/

    CountDownLatch latch = new CountDownLatch(100);
    // Setup a message listener to receive the message
    KafkaTestConsumer listener = new KafkaTestConsumer(kafkaTopic);

    listener.setLatch(latch);
    new Thread(listener).start();

    latch.await(30, TimeUnit.SECONDS);
    lc.shutdown();

    String lastMessage;
    Assert.assertTrue("Minimum messages received from Kafka " + listener.holdingBuffer,
            listener.holdingBuffer.size() >= 100);
    while (!listener.holdingBuffer.isEmpty()) {
        lastMessage = listener.getMessage(listener.holdingBuffer.poll());
        Assert.assertNotNull("Did not receive message from Kafka", lastMessage);
        LOG.debug("received:\n{}", lastMessage);
    }

}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * postThread posts a top comment to Elastic-Search.
 * Tested and verified.//from w  ww  .ja  va 2  s.c om
 * @param ElasticSearchOperations
 * @throws InterruptedException 
 */
public static void postThread(final Comment commentThread) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    if (GSON == null)
        constructGson();

    Thread thread = new Thread() {

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(postAddress + commentThread.getUuid() + "/");

            try {
                request.setEntity(new StringEntity(GSON.toJson(commentThread)));

                HttpResponse response = client.execute(request);
                Log.w(serverName, response.getStatusLine().toString());

                response.getStatusLine().toString();
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String output = reader.readLine();
                while (output != null) {
                    Log.w(serverName, output);
                    output = reader.readLine();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    thread.start();
    latch.await();
}

From source file:io.syndesis.connector.sql.stored.SqlStoredStartConnectorComponentTest.java

@Test
public void camelConnectorTest() throws Exception {

    BasicDataSource ds = new BasicDataSource();
    ds.setUsername(properties.getProperty("sql-stored-start-connector.user"));
    ds.setPassword(properties.getProperty("sql-stored-start-connector.password"));
    ds.setUrl(properties.getProperty("sql-stored-start-connector.url"));

    SimpleRegistry registry = new SimpleRegistry();
    registry.put("dataSource", ds);
    CamelContext context = new DefaultCamelContext(registry);

    CountDownLatch latch = new CountDownLatch(1);

    final Result result = new Result();

    try {/*ww w.  j  a  v a  2 s  . c o  m*/
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("sql-stored-start-connector:DEMO_OUT( OUT INTEGER c)").process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        String jsonBean = (String) exchange.getIn().getBody();
                        result.setResult(jsonBean);
                        latch.countDown();
                    }
                }).to("stream:out");
            }
        });
        context.start();
        latch.await(5l, TimeUnit.SECONDS);
        Assert.assertEquals("{\"c\":60}", result.getJsonBean());
    } finally {
        context.stop();
    }
}

From source file:com.alibaba.simpleimage.PressureTester.java

public PressureTester(int threadsNum, long total, String rootDir) {
    this.threadsNum = threadsNum;
    this.total = new AtomicLong(total);
    this.countDownLatch = new CountDownLatch(threadsNum);
    if (StringUtils.isNotBlank(rootDir)) {
        sourceDir = new File(rootDir + "/src/test/resources/conf.test/simpleimage");
    } else {/* w  w  w.  j  av a  2s .co m*/
        throw new IllegalArgumentException("root dir must not be null");
    }
}

From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java

public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
        boolean fireAndForgot) throws DeviceManagementException {

    String responseMsg = "";
    String urlString = ConnectedCupConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;

    if (log.isDebugEnabled()) {
        log.debug(urlString);//from   www .j a  va2s  . c o m
    }

    if (!fireAndForgot) {
        HttpURLConnection httpConnection = getHttpConnection(urlString);

        try {
            httpConnection.setRequestMethod(HttpMethod.GET);
        } catch (ProtocolException e) {
            String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:"
                    + urlString;
            log.error(errorMsg);
            throw new DeviceManagementException(errorMsg, e);
        }

        responseMsg = readResponseFromGetRequest(httpConnection);

    } else {
        CloseableHttpAsyncClient httpclient = null;
        try {

            httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
            HttpGet request = new HttpGet(urlString);
            final CountDownLatch latch = new CountDownLatch(1);
            Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    latch.countDown();
                }

                @Override
                public void failed(Exception e) {
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (InterruptedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Sync Interrupted");
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();

                }
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed on close");
                }
            }
        }
    }

    return responseMsg;
}