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:interactivespaces.util.web.HttpClientHttpContentCopierTest.java

/**
 * Test a file upload from an input stream.
 *///from  ww w.j  a v  a  2  s  .  c om
@Test
public void testFileUploadInputStream() throws Exception {
    final File destination = getTempFile();

    InputStream source = new ByteArrayInputStream(TEST_CONTENT.getBytes());

    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, "foo.txt", 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:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

@Test
public void shouldWatchSingleFileWithNoiseAndTimeout() throws InterruptedException {
    int eventsCount = 100;
    // add a directory watch.
    WatchService service = serviceRule.getService();

    CountDownLatch latch = new CountDownLatch(eventsCount);
    EtcdEventHandler<NodeData> handler = (event) -> {
        latch.countDown();
    };/*w  w w.ja va 2 s . c  o  m*/

    EtcdDirectoryDao<NodeData> dirDao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir", mapper, NODE_DATA_TYPE);

    service.registerDirectoryWatch("/dir", NODE_DATA_TYPE, handler);

    Thread noiseThread = startNoiseThread(externalNoiseDao, 4000);
    Thread waitThread = startWaitThread(1, TimeUnit.SECONDS);

    noiseThread.join();
    waitThread.join();

    startNodeDataThread(dirDao, eventsCount).join();

    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new IllegalStateException("could not catch up with state.");
    }
}

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

/**
 * Test a file upload from a file./*from  www  . j av a2  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: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   w w  w  .  jav a 2 s .com
        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 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 ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.resizeAsync("dummy-cluster-id", 100, new FutureCallback<Task>() {
        @Override/*w ww. j a v a 2 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));
}

From source file:ch.cyberduck.cli.Terminal.java

protected Exit edit(final SessionPool session, final Path remote) throws BackgroundException {
    final EditorFactory factory = EditorFactory.instance();
    final Application application;
    final ApplicationFinder finder = ApplicationFinderFactory.get();
    if (StringUtils.isNotBlank(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()))) {
        application = finder/* w w w .j  a v a 2s . c  o m*/
                .getDescription(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()));
        if (!finder.isInstalled(application)) {
            throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
                    String.format("Application %s not found",
                            input.getOptionValue(TerminalOptionsBuilder.Params.application.name())));
        }
    } else {
        application = factory.getEditor(remote.getName());
    }
    if (!finder.isInstalled(application)) {
        throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
                String.format("No application found to edit %s", remote.getName()));
    }
    final Editor editor = factory.create(controller, session, application, remote);
    final CountDownLatch lock = new CountDownLatch(1);
    final Worker<Transfer> worker = editor.open(new ApplicationQuitCallback() {
        @Override
        public void callback() {
            lock.countDown();
        }
    }, new DisabledTransferErrorCallback(), new DefaultEditorListener(controller, session, editor));
    final SessionBackgroundAction<Transfer> action = new TerminalBackgroundAction<Transfer>(controller, session,
            worker);
    if (!this.execute(action)) {
        return Exit.failure;
    }
    try {
        lock.await();
    } catch (InterruptedException e) {
        return Exit.failure;
    }
    return Exit.success;
}

From source file:com.micro.rent.common.comm.aio.AsyncClientHttpExchangeFutureCallback.java

public void httpAsync() throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();//from  w  w  w . j  av a 2  s.c  o m
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[list.size()];
        for (int i = 0; i < list.size(); i++) {
            BigDecimal lat = list.get(i).getLatitude();
            BigDecimal lon = list.get(i).getLongitude();
            RequestParam reqParam = new RequestParam();
            reqParam.setDestination(lat.toString().concat(",").concat(lon.toString()));
            reqParam.setOrigin(String.valueOf(wpLat).concat(",").concat(String.valueOf(wpLon)));
            reqParam.setMode(queryVo.getTrafficType());
            switch (ETranfficType.getSelfByCode(queryVo.getTrafficType())) {
            case DRIVING:
                reqParam.setOrigin_region(queryVo.getCityName());
                reqParam.setDestination_region(queryVo.getCityName());
                break;
            case TRANSIT:
            case WALKING:
                reqParam.setRegion(queryVo.getCityName());
                break;
            default:
                break;
            }
            requests[i] = new HttpGet(timeUrl(reqParam));
        }
        long start = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (int j = 0; j < requests.length; j++) {
            final HttpGet request = requests[j];
            final int k = j;
            httpclient.execute(request, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    try {
                        InputStream a = response.getEntity().getContent();
                        String responseString = readInputStream(a);
                        String duration = duration(responseString);
                        list.get(k).setDuration(duration);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                public void failed(final Exception ex) {
                    latch.countDown();
                }

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

            });
        }
        latch.await();
        log.info(System.currentTimeMillis() - start + "-----------------ms----");
    } finally {
        httpclient.close();
    }
}

From source file:org.bpmscript.integration.spring.SpringIntegrationTest.java

public void testSpringIntegration() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    MessageBus messageBus = new MessageBus();
    QueueChannel oneChannel = new QueueChannel(10);
    QueueChannel twoChannel = new QueueChannel(10);
    messageBus.registerChannel("onechannel", oneChannel);
    messageBus.registerChannel("twochannel", twoChannel);
    messageBus.registerHandler("onehandler", new MessageHandler() {

        public Message<?> handle(Message<?> message) {
            log.info(message.getPayload());
            latch.countDown();
            return new StringMessage("Hi...");
        }/*from  w  w  w.  j a v  a 2 s  .c  o m*/

    }, new Subscription(oneChannel));
    messageBus.registerHandler("twohandler", new MessageHandler() {

        public Message<?> handle(Message<?> message) {
            log.info(message.getPayload());
            latch.countDown();
            return null;
        }

    }, new Subscription(twoChannel));
    messageBus.start();
    StringMessage stringMessage = new StringMessage("Hello World!");
    stringMessage.getHeader().setReturnAddress("twochannel");
    oneChannel.send(stringMessage);
    assertTrue(latch.await(2, TimeUnit.SECONDS));
    messageBus.stop();
}

From source file:com.netflix.config.ConcurrentMapConfigurationTest.java

@Test
public void testConcurrency() {
    final ConcurrentMapConfiguration conf = new ConcurrentMapConfiguration();
    ExecutorService exectuor = Executors.newFixedThreadPool(20);
    final CountDownLatch doneSignal = new CountDownLatch(1000);
    for (int i = 0; i < 1000; i++) {
        final Integer index = i;
        exectuor.submit(new Runnable() {
            public void run() {
                conf.addProperty("key", index);
                conf.addProperty("key", "stringValue");
                doneSignal.countDown();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }// w  ww .  ja  v a2  s .c  o  m
            }
        });
    }
    try {
        doneSignal.await();
    } catch (InterruptedException e) {

    }
    List prop = (List) conf.getProperty("key");
    assertEquals(2000, prop.size());
}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testUpdate() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//from www.j  a v  a  2  s.  com
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test")
                .client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);
        cache.start();

        instance = ServiceInstance.<String>builder().payload("changed").name("test").port(10064)
                .id(instance.getId()).build();
        discovery.updateService(instance);

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

        Assert.assertEquals(cache.getInstances().size(), 1);
        Assert.assertEquals(cache.getInstances().get(0).getPayload(), instance.getPayload());
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}