List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.vmware.photon.controller.api.client.resource.ImagesRestApiTest.java
@Test public void testGetAllImagesAsyncForPagination() throws IOException, InterruptedException { Image image1 = new Image(); image1.setId("image1"); Image image2 = new Image(); image2.setId("image2"); Image image3 = new Image(); image3.setId("image3"); String nextPageLink = "nextPageLink"; final ResourceList<Image> imageResourceList = new ResourceList<>(Arrays.asList(image1, image2), nextPageLink, null);//from www . j a v a 2 s . c o m final ResourceList<Image> imageResourceListNextPage = new ResourceList<>(Arrays.asList(image3)); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(imageResourceList); String serializedTaskNextPage = mapper.writeValueAsString(imageResourceListNextPage); setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK); ImagesApi imagesApi = new ImagesRestApi(this.restClient); final CountDownLatch latch = new CountDownLatch(1); imagesApi.getImagesAsync(new FutureCallback<ResourceList<Image>>() { @Override public void onSuccess(@Nullable ResourceList<Image> result) { assertEquals(result.getItems().size(), imageResourceList.getItems().size() + imageResourceListNextPage.getItems().size()); assertTrue(result.getItems().containsAll(imageResourceList.getItems())); assertTrue(result.getItems().containsAll(imageResourceListNextPage.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.wisdom.framework.vertx.CookiesTest.java
@Test public void testThatCookiesCanBeReplaced() throws InterruptedException, IOException { Router router = prepareServer();/* w w w. jav a2s . c om*/ // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { if (context().parameter("id") == null) { return badRequest("'id' parameter required"); } return ok("Alright").with(Cookie.builder("my-cookie", context().parameter("id")).setMaxAge(3600) .setSecure(false).build()); } @SuppressWarnings("unused") public Result logged() { String id = context().cookieValue("my-cookie"); if (id == null) { return badRequest("no cookie"); } else { return ok(id).with(Cookie.cookie("my-cookie", id + "_").build()); } } }; 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 = NUMBER_OF_CLIENTS; CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(num); int port = server.httpPort(); createAndSubmitClients(num, startSignal, doneSignal, port); startSignal.countDown(); // let all threads proceed assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish assertThat(failure).isEmpty(); assertThat(success).hasSize(num); }
From source file:org.wisdom.framework.vertx.CookiesTest.java
@Test public void testThatCookiesCanBeWithdrawnAndReplaced() throws InterruptedException, IOException { Router router = prepareServer();//from w w w .j av a 2 s. c o m // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { if (context().parameter("id") == null) { return badRequest("'id' parameter required"); } return ok("Alright").with(Cookie.builder("my-cookie", context().parameter("id")).setMaxAge(3600) .setSecure(false).build()); } @SuppressWarnings("unused") public Result logged() { String id = context().cookieValue("my-cookie"); if (id == null) { return badRequest("no cookie"); } else { return ok(id).without("my-cookie").with(Cookie.cookie("my-cookie", id + "_").build()); } } }; 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 = NUMBER_OF_CLIENTS; CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(num); int port = server.httpPort(); createAndSubmitClients(num, startSignal, doneSignal, port); startSignal.countDown(); // let all threads proceed assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish assertThat(failure).isEmpty(); assertThat(success).hasSize(num); }
From source file:org.cometd.client.JacksonCustomSerializationTest.java
@Test public void testJacksonCustomSerialization() throws Exception { Map<String, String> serverOptions = new HashMap<>(); serverOptions.put(AbstractServerTransport.JSON_CONTEXT_OPTION, jacksonContextServerClassName); serverOptions.put(AbstractHttpTransport.JSON_DEBUG_OPTION, "true"); Map<String, Object> clientOptions = new HashMap<>(); clientOptions.put(ClientTransport.JSON_CONTEXT_OPTION, jacksonContextClientClassName); startServer(serverOptions);/*from w ww . j a v a 2 s .co m*/ String channelName = "/data"; final String dataContent = "random"; final long extraContent = 13; final CountDownLatch latch = new CountDownLatch(1); LocalSession service = bayeux.newLocalSession("custom_serialization"); service.handshake(); service.getChannel(channelName).subscribe(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { Data data = (Data) message.getData(); Assert.assertEquals(dataContent, data.content); Map<String, Object> ext = message.getExt(); Assert.assertNotNull(ext); Extra extra = (Extra) ext.get("extra"); Assert.assertEquals(extraContent, extra.content); latch.countDown(); } }); BayeuxClient client = new BayeuxClient(cometdURL, new LongPollingTransport(clientOptions, httpClient)); client.addExtension(new ExtraExtension(extraContent)); client.handshake(); Assert.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED)); // Wait for the connect to establish Thread.sleep(1000); client.getChannel(channelName).publish(new Data(dataContent)); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); disconnectBayeuxClient(client); }
From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java
/** * Pulls the userProfile from the server, uses their uniqueID as a key source of extracting * Information.// w w w.j a va2s . c om * @param uniqueID * @return * @throws InterruptedException */ public static ArrayList<UserProfileModel> pullUserProfile(final String uniqueID) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final ArrayList<UserProfileModel> userProfileList = new ArrayList<UserProfileModel>(); if (GSON == null) constructGson(); Thread thread = new Thread() { @Override public void run() { HttpClient client = new DefaultHttpClient(); try { HttpPost searchRequest = new HttpPost(profileAddress + "_search?pretty=1"); String query = "{\"query\" : {\"query_string\" : {\"default_field\" : \"uniqueID\",\"query\" : \"" + uniqueID + "\"}}}"; StringEntity stringentity = new StringEntity(query); searchRequest.setEntity(stringentity); HttpResponse response = client.execute(searchRequest); String json = getEntityContent(response); Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<UserProfileModel>>() { }.getType(); ElasticSearchSearchResponse<UserProfileModel> esResponse = GSON.fromJson(json, elasticSearchSearchResponseType); for (ElasticSearchResponse<UserProfileModel> r : esResponse.getHits()) { UserProfileModel userProfileModel = r.getSource(); userProfileList.add(userProfileModel); } latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); latch.await(); return userProfileList; }
From source file:com.vmware.photon.controller.api.client.resource.DisksApiTest.java
@Test public void testGetTasksForDisksAsyncForPagination() throws IOException, InterruptedException { Task task1 = new Task(); task1.setId("task1"); Task task2 = new Task(); task2.setId("task2"); Task task3 = new Task(); task3.setId("task3"); Task task4 = new Task(); task4.setId("task4"); String nextPageLink = "nextPageLink"; final ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2), nextPageLink, null);/*from w w w .j a v a 2 s. c om*/ final ResourceList<Task> taskResourceListNextPage = new ResourceList<>(Arrays.asList(task3, task4)); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(taskResourceList); String serializedTaskNextPage = mapper.writeValueAsString(taskResourceListNextPage); setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK); DisksApi disksApi = new DisksApi(restClient); final CountDownLatch latch = new CountDownLatch(1); disksApi.getTasksForDiskAsync("persistentDisk", new FutureCallback<ResourceList<Task>>() { @Override public void onSuccess(@Nullable ResourceList<Task> result) { assertEquals(result.getItems().size(), taskResourceList.getItems().size() + taskResourceListNextPage.getItems().size()); assertTrue(result.getItems().containsAll(taskResourceList.getItems())); assertTrue(result.getItems().containsAll(taskResourceListNextPage.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.DisksRestApiTest.java
@Test public void testGetTasksForDisksAsyncForPagination() throws IOException, InterruptedException { Task task1 = new Task(); task1.setId("task1"); Task task2 = new Task(); task2.setId("task2"); Task task3 = new Task(); task3.setId("task3"); Task task4 = new Task(); task4.setId("task4"); String nextPageLink = "nextPageLink"; final ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2), nextPageLink, null);// w w w. j a v a 2 s. co m final ResourceList<Task> taskResourceListNextPage = new ResourceList<>(Arrays.asList(task3, task4)); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(taskResourceList); String serializedTaskNextPage = mapper.writeValueAsString(taskResourceListNextPage); setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK); DisksApi disksApi = new DisksRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); disksApi.getTasksForDiskAsync("persistentDisk", new FutureCallback<ResourceList<Task>>() { @Override public void onSuccess(@Nullable ResourceList<Task> result) { assertEquals(result.getItems().size(), taskResourceList.getItems().size() + taskResourceListNextPage.getItems().size()); assertTrue(result.getItems().containsAll(taskResourceList.getItems())); assertTrue(result.getItems().containsAll(taskResourceListNextPage.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.github.sdbg.debug.core.internal.webkit.protocol.WebkitDom.java
public WebkitNode getDocumentSync() throws IOException { @SuppressWarnings("unchecked") final WebkitResult<WebkitNode>[] result = new WebkitResult[1]; final CountDownLatch latch = new CountDownLatch(1); getDocument(new WebkitCallback<WebkitNode>() { @Override/*from w ww .j a v a 2 s . c o m*/ public void handleResult(WebkitResult<WebkitNode> r) { result[0] = r; latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { } if (result[0].isError()) { throw new IOException(result[0].getErrorMessage()); } else { return result[0].getResult(); } }
From source file:it.pronetics.madstore.repository.index.impl.IndexManagerMultiThreadTest.java
public void testIndexManagerSharedByMultipleThreads() throws Exception { final CountDownLatch firstStepLatch = new CountDownLatch(1); final CountDownLatch secondStepLatch = new CountDownLatch(1); final CountDownLatch thirdStepLatch = new CountDownLatch(1); final CountDownLatch stopLatch = new CountDownLatch(4); final List<String> terms = new ArrayList<String>(); final Element entry1 = Utils.getDoc("luceneentry1.xml").getDocumentElement(); final Element entry2 = Utils.getDoc("luceneentry2.xml").getDocumentElement(); terms.add("bla"); Thread t1 = threadFactory.newThread(new Runnable() { public void run() { try { indexManager.index(COLLECTION_KEY, "entry1", entry1); firstStepLatch.countDown(); } finally { stopLatch.countDown();//from w w w . jav a 2 s .c om } } }); t1.start(); Thread t2 = threadFactory.newThread(new Runnable() { public void run() { try { firstStepLatch.await(5, TimeUnit.SECONDS); List<SearchResult> entryKeyPair = indexManager.searchCollectionByFullText(COLLECTION_KEY, terms, 0, 0); assertEquals(1, entryKeyPair.size()); secondStepLatch.countDown(); } catch (InterruptedException ex) { fail(ex.getMessage()); } finally { stopLatch.countDown(); } } }); t2.start(); Thread t3 = threadFactory.newThread(new Runnable() { public void run() { try { secondStepLatch.await(5, TimeUnit.SECONDS); indexManager.index(COLLECTION_KEY, "entry2", entry2); thirdStepLatch.countDown(); } catch (InterruptedException ex) { fail(ex.getMessage()); } finally { stopLatch.countDown(); } } }); t3.start(); Thread t4 = threadFactory.newThread(new Runnable() { public void run() { try { thirdStepLatch.await(5, TimeUnit.SECONDS); List<SearchResult> entryKeyPair = indexManager.searchCollectionByFullText(COLLECTION_KEY, terms, 0, 0); assertEquals(2, entryKeyPair.size()); } catch (InterruptedException ex) { fail(ex.getMessage()); } finally { stopLatch.countDown(); } } }); t4.start(); stopLatch.await(); threadFactory.verifyThreads(); threadFactory.resetThreads(); }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java
@Test protected void test_lock() { ExecutorService exeucotr = Executors.newCachedThreadPool(); final int count = 50; final CountDownLatch latch = new CountDownLatch(count); final DistributedReentrantLock lock = new DistributedReentrantLock(dir); for (int i = 0; i < count; i++) { exeucotr.submit(new Runnable() { public void run() { try { Thread.sleep(1000); lock.lock();/*from w w w . j a va 2 s. co m*/ Thread.sleep(100 + RandomUtils.nextInt(100)); System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner()); } catch (InterruptedException e) { want.fail(); } catch (KeeperException e) { want.fail(); } finally { latch.countDown(); try { lock.unlock(); } catch (KeeperException e) { want.fail(); } } } }); } try { latch.await(); } catch (InterruptedException e) { want.fail(); } exeucotr.shutdown(); }