List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.netflix.curator.framework.imps.TestFramework.java
@Test public void testCreateACLWithReset() throws Exception { Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()) .authorization("digest", "me:pass".getBytes()).retryPolicy(new RetryOneTime(1)).build(); client.start();/* w w w .j a v a 2 s . c o m*/ try { final CountDownLatch lostLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List<ACL> aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); server.stop(); Assert.assertTrue(timing.awaitLatch(lostLatch)); try { client.checkExists().forPath("/"); Assert.fail("Connection should be down"); } catch (KeeperException.ConnectionLossException e) { // expected } server = new TestingServer(server.getPort(), server.getTempDirectory()); try { client.setData().forPath("/test", "test".getBytes()); } catch (KeeperException.NoAuthException e) { Assert.fail("Auth failed"); } } finally { IOUtils.closeQuietly(client); } }
From source file:info.archinnov.achilles.test.integration.tests.AsyncBatchModeIT.java
@Test public void should_batch_several_entities_async() throws Exception { CompleteBean bean = CompleteBeanTestBuilder.builder().randomId().name("name").buid(); Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("tweet1").buid(); Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("tweet2").buid(); final CountDownLatch latch = new CountDownLatch(2); final AtomicReference<Object> successSpy = new AtomicReference<>(); final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>(); FutureCallback<Object> successCallBack = new FutureCallback<Object>() { @Override/* w ww.j a v a 2 s. c o m*/ public void onSuccess(Object result) { successSpy.getAndSet(result); latch.countDown(); } @Override public void onFailure(Throwable t) { latch.countDown(); } }; FutureCallback<Object> errorCallBack = new FutureCallback<Object>() { @Override public void onSuccess(Object result) { latch.countDown(); } @Override public void onFailure(Throwable t) { exceptionSpy.getAndSet(t); latch.countDown(); } }; // Start batch AsyncBatch batch = asyncManager.createBatch(); batch.startBatch(); batch.insert(bean); batch.insert(tweet1); batch.insert(tweet2); batch.insert(user); CompleteBean foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately(); Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately(); Tweet foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately(); User foundUser = asyncManager.find(User.class, user.getId()).getImmediately(); assertThat(foundBean).isNull(); assertThat(foundTweet1).isNull(); assertThat(foundTweet2).isNull(); assertThat(foundUser).isNull(); // Flush batch.asyncEndBatch(successCallBack, errorCallBack); latch.await(); final ResultSet resultSet = asyncManager.getNativeSession().execute( "SELECT id,favoriteTweets,followers,friends,age_in_years,name,welcomeTweet,label,preferences FROM CompleteBean WHERE id=:id", bean.getId()); assertThat(resultSet.all()).hasSize(1); foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately(); foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately(); foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately(); foundUser = asyncManager.find(User.class, user.getId()).getImmediately(); assertThat(foundBean.getName()).isEqualTo("name"); assertThat(foundTweet1.getContent()).isEqualTo("tweet1"); assertThat(foundTweet2.getContent()).isEqualTo("tweet2"); assertThat(foundUser.getFirstname()).isEqualTo("fn"); assertThat(foundUser.getLastname()).isEqualTo("ln"); assertThatBatchContextHasBeenReset(batch); assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE); assertThat(exceptionSpy.get()).isNull(); }
From source file:io.nats.client.ITClusterTest.java
@Test public void testProperReconnectDelay() throws Exception { try (NatsServer s1 = runServerOnPort(1222)) { Options opts = new Options.Builder(defaultOptions()).dontRandomize().build(); opts.servers = Nats.processUrlArray(testServers); final CountDownLatch latch = new CountDownLatch(1); opts.disconnectedCb = new DisconnectedCallback() { public void onDisconnect(ConnectionEvent event) { event.getConnection().setDisconnectedCallback(null); latch.countDown(); }/*w ww . java2 s . c o m*/ }; final AtomicBoolean ccbCalled = new AtomicBoolean(false); opts.closedCb = new ClosedCallback() { public void onClose(ConnectionEvent event) { ccbCalled.set(true); } }; try (Connection c = opts.connect()) { assertFalse(c.isClosed()); s1.shutdown(); // wait for disconnect assertTrue("Did not receive a disconnect callback message", await(latch, 2, TimeUnit.SECONDS)); // Wait, want to make sure we don't spin on reconnect to non-existent servers. sleep(1, TimeUnit.SECONDS); assertFalse("Closed CB was triggered, should not have been.", ccbCalled.get()); assertEquals("Wrong state: " + c.getState(), c.getState(), RECONNECTING); } } }
From source file:io.nats.client.ITClusterTest.java
@Test public void testTimeoutOnNoServers() throws Exception { int maxRecon = 10; int reconWait = 100; String[] servers = testServers; final String hostOs = System.getProperty("os.name").toLowerCase(); boolean windows = (hostOs.contains("win")); windows = true;/*from w w w .j av a 2 s.com*/ if (windows) { servers = Arrays.copyOf(testServers, 2); maxRecon = 2; } Options opts = new Options.Builder(defaultOptions()).dontRandomize() // 1 second total time wait .maxReconnect(maxRecon).reconnectWait(reconWait).build(); opts.servers = Nats.processUrlArray(servers); final CountDownLatch dcLatch = new CountDownLatch(1); opts.disconnectedCb = new DisconnectedCallback() { public void onDisconnect(ConnectionEvent ev) { ev.getConnection().setDisconnectedCallback(null); dcLatch.countDown(); } }; final CountDownLatch ccLatch = new CountDownLatch(1); opts.closedCb = new ClosedCallback() { public void onClose(ConnectionEvent ev) { ccLatch.countDown(); } }; try (NatsServer s1 = runServerOnPort(1222)) { try (Connection c = opts.connect()) { s1.shutdown(); // wait for disconnect assertTrue("Did not receive a disconnect callback message", dcLatch.await(5, TimeUnit.SECONDS)); long t0 = System.nanoTime(); // Wait for ClosedCB assertTrue("Did not receive a closed callback signal", ccLatch.await(5, TimeUnit.SECONDS)); if (windows) { long elapsedMsec = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0); // Use 500ms as variable time delta long variable = 500; long expected = opts.getMaxReconnect() * opts.getReconnectWait(); assertFalse("Waited too long for Closed state: " + elapsedMsec, elapsedMsec > (expected + variable)); } } } }
From source file:com.microsoft.office.core.MessagesAsyncTestCase.java
@Test(timeout = 60000) public void createInDefaultFolderTest() throws Exception { try {/*from w w w . j a va2 s . c om*/ message = Messages.newMessage(); sourceMessage = getEntityFromResource("simpleMessage.json"); String subject = sourceMessage.getProperty("Subject").getPrimitiveValue().toString(); message.setSubject(subject); 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 { assertTrue(StringUtils.isNotEmpty(MessagesAsyncTestCase.this.message.getId())); final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(Me.getDraftsAsync(), new FutureCallback<IFolder>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(IFolder result) { assertEquals(MessagesAsyncTestCase.this.message.getParentFolderId(), result.getId()); cdl.countDown(); }; }); cdl.await(); } catch (Throwable t) { reportError(t); } counter.countDown(); } }); counter.await(); } finally { removeMessage(); } }
From source file:com.balch.mocktrade.finance.FinanceYQLModel.java
@Override public void getQuotes(final List<String> symbols, final RequestListener<Map<String, Quote>> listener) { final CountDownLatch latch = new CountDownLatch(2); final Map<String, Quote> yqlQuotes = new HashMap<String, Quote>(); final Map<String, Quote> googleQuotes = new HashMap<String, Quote>(); final StringBuilder errorMessages = new StringBuilder(); this.getYQLQuotes(symbols, new RequestListener<Map<String, Quote>>() { @Override/*from w w w. ja v a 2 s . co m*/ public void onResponse(Map<String, Quote> response) { try { yqlQuotes.putAll(response); } finally { latch.countDown(); } } @Override public void onErrorResponse(String error) { errorMessages.append(error).append("\n"); latch.countDown(); } }); this.getGoogleRealTimeQuotes(symbols, new RequestListener<Map<String, Quote>>() { @Override public void onResponse(Map<String, Quote> response) { try { googleQuotes.putAll(response); } finally { latch.countDown(); } } @Override public void onErrorResponse(String error) { errorMessages.append(error).append("\n"); latch.countDown(); } }); try { // wait for both requests to finish latch.await(); if (errorMessages.length() == 0) { // add google's realtime quotes on top of yql quotes for (Quote q : googleQuotes.values()) { Quote yqlQuote = yqlQuotes.get(q.getSymbol()); if (yqlQuote != null) { yqlQuote.setPrice(q.getPrice()); yqlQuote.setLastTradeTime(q.getLastTradeTime()); } else { Log.wtf(TAG, "GoogleQuote contains a symbol that is not in the yqlQuote map. GoogleQuote Symbol:" + q.getSymbol() + " Submitted Symbols:" + TextUtils.join(",", symbols)); } } listener.onResponse(yqlQuotes); } else { listener.onErrorResponse(errorMessages.toString()); } } catch (InterruptedException e) { } }
From source file:com.twitter.aurora.scheduler.app.SchedulerIT.java
private HostAndPort awaitSchedulerReady() throws Exception { return executor.submit(new Callable<HostAndPort>() { @Override// w w w . ja v a 2s . c om public HostAndPort call() throws Exception { final AtomicReference<HostAndPort> thriftEndpoint = Atomics.newReference(); ServerSet schedulerService = new ServerSetImpl(zkClient, SERVERSET_PATH); final CountDownLatch schedulerReady = new CountDownLatch(1); schedulerService.watch(new HostChangeMonitor<ServiceInstance>() { @Override public void onChange(ImmutableSet<ServiceInstance> hostSet) { if (!hostSet.isEmpty()) { Endpoint endpoint = Iterables.getOnlyElement(hostSet).getServiceEndpoint(); thriftEndpoint.set(HostAndPort.fromParts(endpoint.getHost(), endpoint.getPort())); schedulerReady.countDown(); } } }); // A timeout is used because certain types of assertion errors (mocks) will not surface // until the main test thread exits this body of code. assertTrue(schedulerReady.await(5L, TimeUnit.MINUTES)); return thriftEndpoint.get(); } }).get(); }
From source file:net.java.html.charts.ChartsTest.java
/** * * @throws InterruptedException/* w w w . j a v a2s. c o m*/ */ @BeforeMethod public void initializePresenter() throws InterruptedException { animationComplete = false; final CountDownLatch initialized = new CountDownLatch(1); final BrowserBuilder builder = BrowserBuilder.newBrowser().loadPage("charts.html").loadFinished(() -> { presenter = Fn.activePresenter(); initialized.countDown(); }); Executors.newSingleThreadExecutor().execute(builder::showAndWait); initialized.await(); assertNotNull(presenter, "We have the presenter"); }
From source file:com.vmware.photon.controller.common.xenon.MultiHostEnvironment.java
private boolean checkFactoryServiceAvailable(H host, Class<? extends Service> c, String selector) throws Throwable { URI availableUri = UriUtils.buildAvailableUri(UriUtils.buildUri(host, c)); if (selector != null) { availableUri = UriUtils.buildBroadcastRequestUri(availableUri, selector); }//from w w w. j a va 2 s .com boolean isReady[] = new boolean[1]; CountDownLatch countDownLatch = new CountDownLatch(1); Operation getOp = Operation.createGet(availableUri) .setReferer(UriUtils.buildUri(host, "/multi-host-environment")).setCompletion((o, e) -> { if (e != null) { logger.info("Checking availability failed: " + e); isReady[0] = false; countDownLatch.countDown(); return; } if (selector == null) { isReady[0] = true; countDownLatch.countDown(); return; } NodeGroupBroadcastResponse rsp = o.getBody(NodeGroupBroadcastResponse.class); logger.info("Received {} failures, {} available nodes", rsp.failures.size(), rsp.availableNodeCount); isReady[0] = (rsp.failures.size() < rsp.availableNodeCount); countDownLatch.countDown(); }); host.sendRequest(getOp); countDownLatch.await(); return isReady[0]; }
From source file:com.vmware.photon.controller.api.client.resource.ImagesApiTest.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 w w w . j a va 2s . 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 ImagesApi(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)); }