List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:org.bpmscript.integration.internal.memory.BpmScriptTestSupport.java
/** * @see org.bpmscript.test.ITestSupport#execute(org.bpmscript.test.ITestCallback) *///from w w w . ja va 2 s .c o m public void execute(final ITestCallback<ApplicationContext> callback) throws Exception { final CountDownLatch latch = new CountDownLatch(total); final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(spring); try { final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine"); final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context .getBean("versionedDefinitionManager"); processManager.createDefinition("id", new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE.getResourceAsString(script))); engine.setInstanceListener(new LoggingInstanceListener() { @Override public void instanceCompleted(String pid, ICompletedResult result) { super.instanceCompleted(pid, result); latch.countDown(); } }); IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() { public void execute(int count) throws Exception { callback.execute(context); } }, new IWaitForCallback() { public void call() throws Exception { latch.await(); } }, false)); } finally { context.destroy(); } }
From source file:com.microsoft.office.integration.test.MessagesAsyncTestCase.java
public void testReply() { // first send message to self final String subject = "reply test" + (int) (Math.random() * 1000000); message = (IMessage) Messages.newMessage().setToRecipients(new ArrayList<Recipient>() { {//from w ww . j a v a 2s . c om add(new Recipient().setAddress(TestRunner.getUsername())); } }).setSubject(subject); counter = new CountDownLatch(1); Futures.addCallback(message.sendAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); counter.countDown(); } public void onSuccess(Void result) { try { // find message in inbox after a little delay, otherwise service sometimes lags with message processing IMessage inboxMessage = null; for (int i = 0; i < 20; ++i) { try { Thread.sleep(100); } catch (InterruptedException e) { } if (Me.getInboxAsync().get().getMessagesAsync().get().createQuery() .setFilter("Subject eq '" + subject + "'").getResult().size() > 0) { inboxMessage = Me.getInbox().getMessages().createQuery() .setFilter("Subject eq '" + subject + "'").getSingleResult(); break; } } if (inboxMessage == null) { fail("message did not send"); } final String reply = "reply on test message"; final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(inboxMessage.replyAsync(reply), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(Void result) { try { // find reply after a little delay IMessageCollection replies = null; for (int i = 0; i < 20; ++i) { try { Thread.sleep(100); } catch (InterruptedException e) { } try { if (Me.getInbox().getMessages().createQuery() .setFilter("Subject eq 'RE: " + subject + "'").getResult() .size() > 0) { replies = Me.getInboxAsync().get().getMessagesAsync().get() .createQuery().setFilter("Subject eq 'RE: " + subject + "'") .getResult(); break; } } catch (Throwable t) { reportError(t); } } if (replies == null) { fail("reply did not send"); } assertEquals(1, replies.size()); } catch (Throwable t) { reportError(t); } finally { cdl.countDown(); } } }); cdl.await(); } catch (Throwable e) { reportError(e); } finally { Iterator<IMessage> messages = Me.getSentItems().getMessages().createQuery() .setFilter("contains(Subject, '" + subject + "')").getResult().iterator(); while (messages.hasNext()) { Me.getMessages().delete(messages.next().getId()); } messages = Me.getInbox().getMessages().createQuery() .setFilter("contains(Subject, '" + subject + "')").getResult().iterator(); while (messages.hasNext()) { Me.getMessages().delete(messages.next().getId()); } Me.flush(); counter.countDown(); } } }); try { if (!counter.await(60000, TimeUnit.MILLISECONDS)) { fail("testSize() timed out"); } } catch (InterruptedException e) { fail("testSize() has been interrupted"); } }
From source file:com.couchbase.client.TestingClient.java
public HttpFuture<String> asyncHttpPut(String uri, String document) throws UnsupportedEncodingException { final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout); HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1); request.setHeader(new BasicHeader("Content-Type", "application/json")); StringEntity entity = new StringEntity(document); ((BasicHttpEntityEnclosingRequest) request).setEntity(entity); HttpOperationImpl op = new TestOperationPutImpl(request, new TestCallback() { private String json; @Override//from www . j a v a 2s. c om public void receivedStatus(OperationStatus status) { crv.set(json, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void getData(String response) { json = response; } }); crv.setOperation(op); addOp(op); return crv; }
From source file:com.netflix.curator.framework.imps.TestFramework.java
@Test public void testCustomCallback() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();// w ww . j a v a 2 s. c om try { final CountDownLatch latch = new CountDownLatch(1); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.CREATE) { if (event.getPath().equals("/head")) { latch.countDown(); } } } }; client.create().inBackground(callback).forPath("/head"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { client.close(); } }
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java
private void internalTestMode(CuratorFramework client, boolean cacheData) throws Exception { PathChildrenCache cache = new PathChildrenCache(client, "/test", cacheData); final CountDownLatch latch = new CountDownLatch(2); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override//w w w . j av a 2 s . co m public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { latch.countDown(); } } }); cache.start(); client.create().forPath("/test/one", "one".getBytes()); client.create().forPath("/test/two", "two".getBytes()); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); for (ChildData data : cache.getCurrentData()) { if (cacheData) { Assert.assertNotNull(data.getData()); Assert.assertNotNull(data.getStat()); } else { Assert.assertNull(data.getData()); Assert.assertNotNull(data.getStat()); } } cache.close(); }
From source file:com.qualys.jserf.SerfClientIT.java
@Test(timeout = 10000) public void testHandShake() throws Exception { while (!client.isConnected()) { Thread.sleep(500);//www . j av a2 s. co m } final boolean[] callbackInvoked = { false }; final CountDownLatch latch = new CountDownLatch(1); SerfResponseCallBack<EmptyResponseBody> callBack = new SerfResponseCallBack<EmptyResponseBody>() { @Override public void call(SerfResponse<EmptyResponseBody> response) { log.debug("Received call back with sequence {}", response.getHeader().getSeq()); callbackInvoked[0] = true; assertNotNull(response.getHeader()); assertEquals(StringUtils.EMPTY, response.getHeader().getError()); assertNotNull(response.getBody()); assertEquals(EmptyResponseBody.class, response.getBody().getClass()); //don't count down unless all the asserts pass latch.countDown(); } }; SerfRequest request = SerfRequests.handshake(callBack); client.makeRpc(request); latch.await(); assertTrue(callbackInvoked[0]); }
From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java
/** * pullThreads returns the list of top comments. * Tested and verified.// w w w. j a va 2s. c om * @return list of names of Threads. * @throws InterruptedException */ public static ArrayList<Comment> pullThreads() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final ArrayList<Comment> commentList = new ArrayList<Comment>(); if (GSON == null) constructGson(); Thread thread = new Thread() { @Override public void run() { HttpClient client = new DefaultHttpClient(); try { HttpPost searchRequest = new HttpPost(searchAddress); String query = "{\"query\" : {\"query_string\" : {\"default_field\" : \"topComment\",\"query\" : \"true\"}}}"; StringEntity stringentity = new StringEntity(query); searchRequest.setEntity(stringentity); HttpResponse response = client.execute(searchRequest); String json = getEntityContent(response); Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Comment>>() { }.getType(); ElasticSearchSearchResponse<Comment> esResponse = GSON.fromJson(json, elasticSearchSearchResponseType); for (ElasticSearchResponse<Comment> r : esResponse.getHits()) { Comment topComment = r.getSource(); commentList.add(topComment); } // Sort by latest dated element. Collections.sort(commentList); Collections.reverse(commentList); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); latch.await(); return commentList; }
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 {// ww w .jav a 2s . 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:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java
public List<Object> process(List<ConcurrentRequest> requests) { List<Object> resultList = new ArrayList<Object>(); if (CollectionUtils.isEmpty(requests)) return resultList; List<RequestDepository> requestsDepo = fetchConnectionsAndDepositForLaterUse(requests); final CountDownLatch latch = new CountDownLatch(requestsDepo.size()); List<Future<Object>> futures = new ArrayList<Future<Object>>(); try {//from www . j av a 2 s . c o m for (RequestDepository rdepo : requestsDepo) { ConcurrentRequest request = rdepo.getOriginalRequest(); final SqlMapClientCallback action = request.getAction(); final Connection connection = rdepo.getConnectionToUse(); futures.add(request.getExecutor().submit(new Callable<Object>() { public Object call() throws Exception { try { return executeWith(connection, action); } finally { latch.countDown(); } } })); } try { latch.await(); } catch (InterruptedException e) { throw new ConcurrencyFailureException( "interrupted when processing data access request in concurrency", e); } } finally { for (RequestDepository depo : requestsDepo) { Connection springCon = depo.getConnectionToUse(); DataSource dataSource = depo.getOriginalRequest().getDataSource(); try { if (springCon != null) { if (depo.isTransactionAware()) { springCon.close(); } else { DataSourceUtils.doReleaseConnection(springCon, dataSource); } } } catch (Throwable ex) { logger.info("Could not close JDBC Connection", ex); } } } fillResultListWithFutureResults(futures, resultList); return resultList; }
From source file:com.microsoft.office.core.MessagesAsyncTestCase.java
@Test(timeout = 60000) public void replyTest() throws Exception { // first send message to self final String subject = "reply test" + (int) (Math.random() * 1000000); message = (IMessage) Messages.newMessage().setToRecipients(new ArrayList<Recipient>() { {/*w w w.j a va 2 s . co m*/ add(new Recipient().setAddress(username)); } }).setSubject(subject); counter = new CountDownLatch(1); Futures.addCallback(message.sendAsync(), new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { reportError(t); counter.countDown(); } @Override public void onSuccess(Void result) { try { // find message in inbox after a little delay, otherwise service sometimes lags with message processing IMessage inboxMessage = null; for (int i = 0; i < 20; ++i) { try { Thread.sleep(100); } catch (InterruptedException e) { } if (Me.getInboxAsync().get().getMessagesAsync().get().createQuery() .setFilter("Subject eq '" + subject + "'").getResult().size() > 0) { inboxMessage = Me.getInbox().getMessages().createQuery() .setFilter("Subject eq '" + subject + "'").getSingleResult(); break; } } if (inboxMessage == null) { fail("message did not send"); } final String reply = "reply on test message"; final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(inboxMessage.replyAsync(reply), new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } @Override public void onSuccess(Void result) { try { // find reply after a little delay IMessageCollection replies = null; for (int i = 0; i < 20; ++i) { try { Thread.sleep(100); } catch (InterruptedException e) { } try { if (Me.getInbox().getMessages().createQuery() .setFilter("Subject eq 'RE: " + subject + "'").getResult() .size() > 0) { replies = Me.getInboxAsync().get().getMessagesAsync().get() .createQuery().setFilter("Subject eq 'RE: " + subject + "'") .getResult(); break; } } catch (Throwable t) { reportError(t); } } if (replies == null) { fail("reply did not send"); } assertEquals(1, replies.size()); } catch (Throwable t) { reportError(t); } finally { cdl.countDown(); } } }); cdl.await(); } catch (Throwable e) { reportError(e); } finally { Iterator<IMessage> messages = Me.getSentItems().getMessages().createQuery() .setFilter("contains(Subject, '" + subject + "')").getResult().iterator(); while (messages.hasNext()) { Me.getMessages().delete(messages.next().getId()); } messages = Me.getInbox().getMessages().createQuery() .setFilter("contains(Subject, '" + subject + "')").getResult().iterator(); while (messages.hasNext()) { Me.getMessages().delete(messages.next().getId()); } Me.flush(); counter.countDown(); } } }); counter.await(); }