List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:io.syndesis.connector.sql.stored.SqlStoredConnectorComponentTest.java
@Test public void camelConnectorTest() throws Exception { BasicDataSource ds = new BasicDataSource(); ds.setUsername(properties.getProperty("sql-stored-connector.user")); ds.setPassword(properties.getProperty("sql-stored-connector.password")); ds.setUrl(properties.getProperty("sql-stored-connector.url")); SimpleRegistry registry = new SimpleRegistry(); registry.put("dataSource", ds); CamelContext context = new DefaultCamelContext(registry); String jsonBody = "{\"a\":20,\"b\":30}"; CountDownLatch latch = new CountDownLatch(1); final Result result = new Result(); try {/*from www . ja va 2 s . c o m*/ context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("timer://myTimer?period=2000").setBody().constant(jsonBody).to( "sql-stored-connector:DEMO_ADD( INTEGER ${body[a]}, INTEGER ${body[b]}, 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(); } }); } }); context.start(); latch.await(5l, TimeUnit.SECONDS); Assert.assertEquals("{\"c\":50}", result.getJsonBean()); } finally { context.stop(); } }
From source file:io.servicecomb.foundation.vertx.VertxUtils.java
public static <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls, DeploymentOptions options) throws InterruptedException { Holder<Boolean> result = new Holder<>(); CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(cls.getName(), options, ar -> { result.value = ar.succeeded();//from www. j av a 2s . c om if (ar.failed()) { LOGGER.error("deploy vertx failed, cause ", ar.cause()); } latch.countDown(); }); latch.await(); return result.value; }
From source file:com.liferay.mobile.android.async.FileUploadAsyncTest.java
@Test public void uploadPhoto() throws Exception { Session session = new SessionImpl(this.session); DLAppService service = new DLAppService(session); long repositoryId = props.getGroupId(); long folderId = DLAppServiceTest.PARENT_FOLDER_ID; InputStream is = getClass().getResourceAsStream("/" + FileUploadTest.FILE_NAME); final int[] size = { 0 }; FileProgressCallback callback = new FileProgressCallback() { @Override/* w w w.j a v a 2 s .c o m*/ public void onProgress(int totalBytes) { size[0] = totalBytes; } }; UploadData data = new UploadData(is, FileUploadTest.MIME_TYPE, FileUploadTest.FILE_NAME, callback); final CountDownLatch lock = new CountDownLatch(1); session.setCallback(new JSONObjectCallback() { @Override public void onSuccess(JSONObject file) { _file = file; lock.countDown(); } @Override public void onFailure(Exception exception) { fail(exception.getMessage()); lock.countDown(); } }); service.addFileEntry(repositoryId, folderId, FileUploadTest.FILE_NAME, FileUploadTest.MIME_TYPE, FileUploadTest.FILE_NAME, "", "", data, null); lock.await(500, TimeUnit.MILLISECONDS); assertEquals(FileUploadTest.FILE_NAME, _file.get(DLAppServiceTest.TITLE)); assertEquals(372434, size[0]); }
From source file:com.microsoft.office.core.FolderAsyncTestCase.java
@Test(timeout = 60000) public void updateTest() throws Exception { prepareFolder();/*from w ww . j a va 2s. c o m*/ counter = new CountDownLatch(1); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { reportError(t); counter.countDown(); } @Override public void onSuccess(Void result) { try { updateAndCheck(); removeFolder(); } catch (Throwable t) { reportError(t); } counter.countDown(); } }); counter.await(); }
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();/*from ww w .j a va 2 s .co m*/ // 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:example.springdata.cassandra.people.RxJava2PersonRepositoryIntegrationTest.java
/** * This sample performs a count, inserts data and performs a count again using reactive operator chaining. *//*from www . j a v a2s. com*/ @Test public void shouldInsertAndCountData() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); repository.count() // .doOnSuccess(System.out::println) // .toFlowable() // .switchMap(count -> repository.saveAll(Flowable.just(new Person("Hank", "Schrader", 43), // new Person("Mike", "Ehrmantraut", 62)))) // .lastElement() // .toSingle() // .flatMap(v -> repository.count()) // .doOnSuccess(System.out::println) // .doAfterTerminate(countDownLatch::countDown) // .subscribe(); countDownLatch.await(); }
From source file:com.test.database.jedis.TestJedisEvalLua.java
public static void testTryGetHongBao() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(threadCount); System.err.println("start:" + System.currentTimeMillis() / 1000); watch.start();// w w w.j a v a2 s. co m for (int i = 0; i < threadCount; ++i) { final int temp = i; Thread thread = new Thread() { public void run() { String sha = null; Jedis jedis = new Jedis(host, port); sha = jedis.scriptLoad(tryGetHongBaoScript); if (temp == 0) { System.err.println("SCRIPT SHA: " + sha); } int j = honBaoCount / threadCount * temp; while (true) { // Object object = jedis.eval(tryGetHongBaoScript, 4, // hongBaoList, hongBaoConsumedList, // hongBaoConsumedMap, "" + j); Object object = jedis.evalsha(sha, 4, hongBaoList, hongBaoConsumedList, hongBaoConsumedMap, "" + j); j++; if (object != null) { System.out.println("Get hongBao:" + object); } else if (jedis.llen(hongBaoList) == 0) { break; } } latch.countDown(); jedis.close(); } }; thread.start(); } latch.await(); watch.stop(); System.err.println("time:" + watch.getTime() + " ms"); System.err.println("speed:" + honBaoCount / watch.getTime()); System.err.println("end:" + System.currentTimeMillis() / 1000); }
From source file:ch.cyberduck.core.local.FileWatcher.java
public CountDownLatch register(final Local file, final FileWatcherListener listener) throws IOException { // Make sure to canonicalize the watched folder final Path folder = new File(file.getParent().getAbsolute()).getCanonicalFile().toPath(); if (log.isDebugEnabled()) { log.debug(String.format("Register folder %s watching for file %s", folder, file)); }/*from ww w .j a v a 2 s . c o m*/ final WatchKey key = monitor.register(folder, new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }); if (!key.isValid()) { throw new IOException(String.format("Failure registering for events in %s", file)); } final CountDownLatch lock = new CountDownLatch(1); pool.execute(new Callable<Boolean>() { @Override public Boolean call() throws IOException { while (true) { // wait for key to be signaled final WatchKey key; try { lock.countDown(); if (log.isDebugEnabled()) { log.debug(String.format("Wait for key from watch service %s", monitor)); } key = monitor.take(); } catch (ClosedWatchServiceException e) { // If this watch service is closed return true; } catch (InterruptedException e) { return false; } if (log.isDebugEnabled()) { log.debug(String.format("Retrieved key %s from watch service %s", key, monitor)); } for (WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (log.isInfoEnabled()) { log.info(String.format("Detected file system event %s", kind.name())); } if (kind == OVERFLOW) { log.error(String.format("Overflow event for %s", folder)); break; } // The filename is the context of the event. May be absolute or relative path name. if (matches(normalize(LocalFactory.get(folder.toString()), event.context().toString()), LocalFactory.get(folder.toString(), file.getName()))) { callback(LocalFactory.get(folder.toString()), event, listener); } else { log.warn(String.format("Ignored file system event for unknown file %s", event.context())); } } // Reset the key -- this step is critical to receive further watch events. boolean valid = key.reset(); if (!valid) { // The key is no longer valid and the loop can exit. return true; } } } }); return lock; }
From source file:interactivespaces.util.web.WebSocketTest.java
@Test public void testWebSocketCommunication() throws Exception { final String dataKey = "message"; final CountDownLatch clientOpenning = new CountDownLatch(1); final CountDownLatch clientClosing = new CountDownLatch(1); final AtomicBoolean onConnectCalledServer = new AtomicBoolean(false); final AtomicBoolean onCloseCalledServer = new AtomicBoolean(false); final AtomicReference<WebServerWebSocketHandler> serverHandler = new AtomicReference<WebServerWebSocketHandler>(); int port = 8082; String webSocketUriPrefix = "websockettest"; URI uri = new URI(String.format("ws://127.0.0.1:%d/%s", port, webSocketUriPrefix)); final List<Integer> serverReceivedList = Lists.newArrayList(); final List<Integer> clientReceivedList = Lists.newArrayList(); List<Integer> serverSentList = Lists.newArrayList(); List<Integer> clientSentList = Lists.newArrayList(); Random random = new Random(System.currentTimeMillis()); for (int i = 0; i < 100; i++) { clientSentList.add(random.nextInt()); serverSentList.add(random.nextInt()); }// ww w . ja v a 2 s.c o m NettyWebServer server = new NettyWebServer(threadPool, log); server.setServerName("test-server"); server.setPort(port); server.setWebSocketHandlerFactory(webSocketUriPrefix, new WebServerWebSocketHandlerFactory() { @Override public WebServerWebSocketHandler newWebSocketHandler(WebSocketConnection connection) { WebServerWebSocketHandler handler = new WebServerWebSocketHandlerSupport(connection) { @Override public void onReceive(Object data) { @SuppressWarnings("unchecked") Map<String, Object> d = (Map<String, Object>) data; serverReceivedList.add((Integer) d.get(dataKey)); } @Override public void onConnect() { onConnectCalledServer.set(true); } @Override public void onClose() { onCloseCalledServer.set(true); } }; serverHandler.set(handler); return handler; } }); server.startup(); Thread.sleep(2000); WebSocketHandler clientHandler = new WebSocketHandler() { @Override public void onConnect() { clientOpenning.countDown(); } @Override public void onClose() { clientClosing.countDown(); } @Override public void onReceive(Object data) { @SuppressWarnings("unchecked") Map<String, Object> d = (Map<String, Object>) data; clientReceivedList.add((Integer) d.get(dataKey)); } }; NettyWebSocketClient client = new NettyWebSocketClient(uri, clientHandler, threadPool, log); client.startup(); Assert.assertTrue(clientOpenning.await(10, TimeUnit.SECONDS)); Assert.assertTrue(client.isOpen()); Map<String, Object> data = Maps.newHashMap(); for (Integer i : clientSentList) { data.put("message", i); client.writeDataAsJson(data); } for (Integer i : serverSentList) { data.put("message", i); serverHandler.get().sendJson(data); } client.ping(); client.shutdown(); Assert.assertTrue(clientClosing.await(10, TimeUnit.SECONDS)); server.shutdown(); Assert.assertEquals(clientSentList, serverReceivedList); Assert.assertEquals(serverSentList, clientReceivedList); Assert.assertTrue(onConnectCalledServer.get()); Assert.assertTrue(onCloseCalledServer.get()); }
From source file:com.google.api.ads.adwords.awreporting.server.kratu.KratuProcessor.java
public void processKratus(Long topAccountId, Set<Long> accountIdsSet, Date dateStart, Date dateEnd) throws InterruptedException { System.out.println("Processing Kratus for " + topAccountId); // We use a Latch so the main thread knows when all the worker threads are complete. final CountDownLatch latch = new CountDownLatch(1); Stopwatch stopwatch = Stopwatch.createStarted(); RunnableKratu runnableKratu = createRunnableKratu(topAccountId, accountIdsSet, storageHelper, dateStart, dateEnd);/*from w w w . j a va 2 s . c o m*/ ExecutorService executorService = Executors.newFixedThreadPool(1); runnableKratu.setLatch(latch); executorService.execute(runnableKratu); latch.await(); stopwatch.stop(); }