List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:org.zodiark.subscriber.SubscriberTest.java
@Test(enabled = false) public void createSessionTest() throws IOException, InterruptedException { final AtomicReference<SubscriberResults> answer = new AtomicReference<>(); final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch latch = new CountDownLatch(1); publisherClient.handler(new OnEnvelopHandler() { @Override//w w w .j a va 2 s . c om public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class)); latch.countDown(); return true; } }).open(); Envelope createSessionMessage = Envelope .newClientToServerRequest(new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE), mapper.writeValueAsString(new UserPassword("foo", "bar")))); createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER)); publisherClient.send(createSessionMessage); latch.await(); assertEquals("OK", answer.get().getResults()); }
From source file:com.microsoft.office.core.ContactsAsyncTestCase.java
private void deleteAndCheck() throws Exception { removeContact();/*from ww w.j ava2s.c om*/ final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } @Override public void onSuccess(IContact result) { try { assertNull(result); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); cdl.await(); }
From source file:com.nebhale.cyclinglibrary.util.GoogleMapsPointAugmenterTest.java
@Test @SuppressWarnings("rawtypes") public void augmentPoints() throws InterruptedException, URISyntaxException { Double[][] points = new Double[0][0]; List<String> encodedPolylines = Arrays.asList("encoded-polyline-0"); when(this.polylineEncoder.encode(1900, points)).thenReturn(encodedPolylines); Task task = new Task(Long.valueOf(0), Status.IN_PROGRESS, "test-message"); when(this.taskRepository.create("Augmenting %d segments", 1)).thenReturn(task); Map<String, Object> response = new HashMap<>(); response.put("status", "OK"); List<Map<String, Object>> results = new ArrayList<>(); Map<String, Object> result = new HashMap<>(); Map<String, Object> location = new HashMap<>(); location.put("lat", 1.0); location.put("lng", 2.0); result.put("location", location); result.put("elevation", 3.0); results.add(result);//w w w . j av a 2 s . c o m response.put("results", results); when(this.restTemplate.getForEntity(new URI( "https://maps.googleapis.com/maps/api/elevation/json?sensor=false&locations=encoded-polyline-0"), Map.class)).thenReturn(new ResponseEntity<Map>(response, HttpStatus.OK)); CountDownLatch countDownLatch = new CountDownLatch(1); StubPointAugmenterCallback callback = new StubPointAugmenterCallback(countDownLatch); this.pointAugmenter.augmentPoints(points, callback); countDownLatch.await(250, TimeUnit.MILLISECONDS); assertEquals(1, callback.points.size()); Point point = callback.points.get(0); assertEquals(Double.valueOf(1.0), point.getLatitude()); assertEquals(Double.valueOf(2.0), point.getLongitude()); assertEquals(Double.valueOf(3.0), point.getElevation()); verify(this.taskRepository).update(Long.valueOf(0), Status.IN_PROGRESS, "Augmenting %d%% complete", 100); verify(this.taskRepository).update(Long.valueOf(0), Status.SUCCESS, "Augmentation complete"); }
From source file:com.vmware.photon.controller.api.client.resource.TenantsApiTest.java
@Test public void testCreateAsync() 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); TenantsApi tenantsApi = new TenantsApi(restClient); final CountDownLatch latch = new CountDownLatch(1); tenantsApi.createAsync("foo", new FutureCallback<Task>() { @Override// w w w . ja v a 2 s .c om public void onSuccess(@Nullable 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:interactivespaces.service.comm.network.NettyUdpSocketTest.java
/** * Test a round trip from a UDP client to a UDP server and back. * * @throws Exception// w w w .j ava 2s.c o m * something bad */ @Test public void testUdpPacketSend() throws Exception { final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 }; byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 }; int serverPort = 10000; final CountDownLatch serverReceiveLatch = new CountDownLatch(1); final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>(); final CountDownLatch clientReceiveLatch = new CountDownLatch(1); final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>(); UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log); UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log); try { serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() { @Override public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) { serverRequestActualData.set(request); request.writeResponse(serverResponseExpectedData); serverReceiveLatch.countDown(); } }); serverEndpoint.startup(); clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() { @Override public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response, InetSocketAddress remoteAddress) { serverResponseActualData.set(response); clientReceiveLatch.countDown(); } }); clientEndpoint.startup(); WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length); packet.writeBytes(serverRequestExpectedData); packet.write(new InetSocketAddress("127.0.0.1", serverPort)); Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS)); } finally { clientEndpoint.shutdown(); serverEndpoint.shutdown(); } Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest()); Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get()); }
From source file:com.signicat.hystrix.servlet.AsyncWrapperServletTest.java
@Test public void require_That_Servlet_Timeout_Kicks_In_And_Hystrix_Timeout_Also_Kicks_In() throws Exception { CountDownLatch servletTimeout = new CountDownLatch(1); CountDownLatch hystrixError = new CountDownLatch(1); final AsyncTestServlet servlet = new AsyncTestServlet(new CountDownLatch(1), servletTimeout, new CountDownLatch(1), new CountDownLatch(1), hystrixError, new CountDownLatch(1), null, new TimeoutServlet(servletTimeout, hystrixError), 1000L); try (TestServer server = new TestServer(0, servlet)) { server.start();//from w ww . j a v a2s. c om try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet("http://localhost:" + server.getPort() + "/bananarama"); try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) { StatusLine statusLine = httpResponse.getStatusLine(); assertThat(statusLine.getStatusCode(), equalTo(504)); assertThat(statusLine.getReasonPhrase(), equalTo("Timeout from async listener")); EntityUtils.consume(httpResponse.getEntity()); assertThat(servlet.servletTimeout.await(60, TimeUnit.SECONDS), is(true)); assertThat(servlet.servletComplete.await(60, TimeUnit.SECONDS), is(true)); assertThat(servlet.servletError.getCount(), equalTo(1L)); assertThat(servlet.hystrixError.await(60, TimeUnit.SECONDS), is(true)); assertThat(servlet.hystrixCompleted.getCount(), equalTo(1L)); assertThat(servlet.hystrixNext.getCount(), equalTo(1L)); } } } }
From source file:info.archinnov.achilles.it.TestAsyncCRUDSimpleEntity.java
@Test public void should_insert_async() throws Exception { //Given/*from ww w. ja v a2 s . c o m*/ final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final Date date = new Date(); final SimpleEntity entity = new SimpleEntity(id, date, "value"); final CountDownLatch latch = new CountDownLatch(1); final CassandraLogAsserter logAsserter = new CassandraLogAsserter(); logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n"); //When manager.crud().insert(entity).withResultSetAsyncListener(rs -> { LOGGER.info(CALLED); latch.countDown(); return rs; }).executeAsync(); //Then latch.await(); logAsserter.assertContains("Called - [achilles-default-executor"); final List<Row> rows = session.execute("SELECT * FROM simple WHERE id = " + id).all(); assertThat(rows).hasSize(1); final Row row = rows.get(0); assertThat(row.getLong("id")).isEqualTo(id); assertThat(row.getTimestamp("date")).isEqualTo(date); assertThat(row.getString("value")).isEqualTo("value"); }
From source file:com.googlecode.ehcache.annotations.integration.SelfPopulatingTest.java
/** * Verify that setting selfPopulating=true will guarantee only 1 invocation * of the cached method.//from w w w. j a v a 2 s . co m * * @throws Exception */ @Test(timeout = 1000) public void testSelfPopulatingTrue() throws Exception { final CountDownLatch threadRunningLatch = new CountDownLatch(5); final CountDownLatch proccedLatch = new CountDownLatch(1); this.selfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch); this.selfPopulatingTestInterface.setProccedLatch(proccedLatch); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingAInvocationCount()); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingBInvocationCount()); final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingFalse-", true); // set up threads threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingA("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingA("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingB("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingB("test2"); } }); threadGroup.start(); // wait for all threads to get going threadRunningLatch.await(); Thread.sleep(100); // Let both threads complete proccedLatch.countDown(); threadGroup.join(); // verify only 1 call between method A and method B Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingAInvocationCount() + this.selfPopulatingTestInterface.getBlockingBInvocationCount()); }
From source file:com.vmware.photon.controller.api.client.resource.TenantsRestApiTest.java
@Test public void testCreateAsync() 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); TenantsApi tenantsApi = new TenantsRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); tenantsApi.createAsync("foo", new FutureCallback<Task>() { @Override/*from w w w. j av a 2 s .c o m*/ public void onSuccess(@Nullable 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:io.undertow.server.handlers.GracefulShutdownTestCase.java
@Test public void simpleGracefulShutdownTestCase() throws IOException, InterruptedException { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); TestHttpClient client = new TestHttpClient(); try {//from w w w .j av a 2 s . co m HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); shutdown.shutdown(); result = client.execute(get); Assert.assertEquals(StatusCodes.SERVICE_UNAVAILABLE, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); shutdown.start(); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); CountDownLatch latch = new CountDownLatch(1); latch2.set(latch); latch1.set(new CountDownLatch(1)); Thread t = new Thread(new RequestTask()); t.start(); latch1.get().await(); shutdown.shutdown(); Assert.assertFalse(shutdown.awaitShutdown(10)); latch.countDown(); Assert.assertTrue(shutdown.awaitShutdown(10000)); } finally { client.getConnectionManager().shutdown(); } }