List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:com.watchrabbit.executor.spring.AnnotationDiscoverTest.java
@Test public void shouldNotClose() throws Exception { CountDownLatch latch = new CountDownLatch(1); try {// w w w .j av a 2s.co m annotatedService.excludedSystemException(() -> { throw new SystemException(); }); failBecauseExceptionWasNotThrown(SystemException.class); } catch (SystemException ex) { } annotatedService.excludedSystemException(() -> { latch.countDown(); return null; }); assertThat(latch.getCount()).isEqualTo(0); }
From source file:com.couchbase.client.TestingClient.java
public HttpFuture<String> asyncHttpDelete(String uri) throws UnsupportedEncodingException { final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout); HttpRequest request = new BasicHttpRequest("DELETE", uri, HttpVersion.HTTP_1_1); HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() { private String json; @Override//from ww w.j av a 2 s . com 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.networknt.client.oauth.OauthHelper.java
/** * Get an access token from the token service. A Result of TokenResponse will be returned if the invocation is successfully. * Otherwise, a Result of Status will be returned. * * @param tokenRequest token request constructed from the client.yml token section. * @param envTag the environment tag from the server.yml for service lookup. * @return Result of TokenResponse or error Status. *//*from w w w .j a v a 2 s.co m*/ public static Result<TokenResponse> getTokenResult(TokenRequest tokenRequest, String envTag) { final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>(); final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try { if (tokenRequest.getServerUrl() != null) { connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY) .get(); } else if (tokenRequest.getServiceId() != null) { Cluster cluster = SingletonServiceFactory.getBean(Cluster.class); String url = cluster.serviceToUrl("https", tokenRequest.getServiceId(), envTag, null); connection = client .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY) .get(); } else { // both server_url and serviceId are empty in the config. logger.error("Error: both server_url and serviceId are not configured in client.yml for " + tokenRequest.getClass()); throw new ClientException("both server_url and serviceId are not configured in client.yml for " + tokenRequest.getClass()); } } catch (Exception e) { logger.error("cannot establish connection:", e); return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR, tokenRequest.getServerUrl() != null ? tokenRequest.getServerUrl() : tokenRequest.getServiceId())); } try { IClientRequestComposable requestComposer = ClientRequestComposerProvider.getInstance().getComposer( ClientRequestComposerProvider.ClientRequestComposers.CLIENT_CREDENTIAL_REQUEST_COMPOSER); connection.getIoThread() .execute(new TokenRequestAction(tokenRequest, requestComposer, connection, reference, latch)); latch.await(4, TimeUnit.SECONDS); } catch (Exception e) { logger.error("IOException: ", e); return Failure.of(new Status(FAIL_TO_SEND_REQUEST)); } finally { IoUtils.safeClose(connection); } //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout. return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get(); }
From source file:com.microsoft.office.core.AttachmentsAsyncTestCase.java
@Test(timeout = 60000) public void deleteFileAttachmentTest() throws Exception { counter = new CountDownLatch(1); final IFileAttachment attachment = createFileAttachment(); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { @Override/*w ww .ja va 2 s .c om*/ public void onFailure(Throwable err) { reportError(err); counter.countDown(); } @Override public void onSuccess(Void arg0) { try { removeAttachment(attachment); checkDeleted(attachment); } catch (Exception e) { reportError(e); } counter.countDown(); } }); counter.await(); }
From source file:org.apache.servicemix.jbi.cluster.engine.ClusterEndpointLoadTest.java
public void testLoadInOut() throws Exception { createRoute(Transacted.Jms, true, false, false); final int nbThreads = 10; final int nbExchanges = 10; final ReadWriteLock lock = new ReentrantReadWriteLock(); final CountDownLatch latch = new CountDownLatch(nbThreads); lock.writeLock().lock();/* w ww . j a v a2 s.co m*/ for (int i = 0; i < nbThreads; i++) { new Thread() { public void run() { Channel client = null; try { client = nmr1.createChannel(); lock.readLock().lock(); for (int i = 0; i < nbExchanges; i++) { Exchange exchange = client.createExchange(Pattern.InOut); exchange.getIn().setBody(new StringSource("<hello/>")); exchange.setTarget(nmr1.getEndpointRegistry() .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME))); client.sendSync(exchange); assertEquals(Status.Active, exchange.getStatus()); exchange.setStatus(Status.Done); client.send(exchange); } } catch (Exception e) { e.printStackTrace(); } finally { lock.readLock().unlock(); latch.countDown(); if (client != null) { client.close(); } } } }.start(); } cluster2.pause(); lock.writeLock().unlock(); Thread.sleep(0000); cluster2.resume(); latch.await(); receiver.assertExchangesReceived(nbThreads * nbExchanges * 2, TIMEOUT); }
From source file:com.networknt.openapi.JwtVerifyHandlerTest.java
@Test public void testWithRightScopeInIdToken() throws Exception { final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try {/*from w w w . j a va 2 s.co m*/ connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e); } final AtomicReference<ClientResponse> reference = new AtomicReference<>(); try { ClientRequest request = new ClientRequest().setPath("/v1/pets/111").setMethod(Methods.GET); request.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiV0Z1VVZneE83dmxKUm5XUlllMjE1dyIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.ZDlD_JbtHMqfx8EWOlOXI0zFGjB_pJ6yXWpxoE03o2yQnCUq1zypaDTJWSiy-BPIiQAxwDV09L3SN7RsOcgJ3y2LLFhgqIXhcHoePxoz52LPOeeiihG2kcrgBm-_VMq0uUykLrD-ljSmmSm1Hai_dx0WiYGAEJf-TiD1mgzIUTlhogYrjFKlp2NaYHxr7yjzEGefKv4DWdjtlEMmX_cXkqPgxra_omzyxeWE-n0b7f_r7Hr5HkxnmZ23gkZcvFXfVWKEp2t0_dYmNCbSVDavAjNanvmWsNThYNglFRvF0lm8kl7jkfMO1pTa0WLcBLvOO2y_jRWjieFCrc0ksbIrXA"); connection.sendRequest(request, client.createClientCallback(reference, latch)); latch.await(); } catch (Exception e) { logger.error("Exception: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection); } int statusCode = reference.get().getResponseCode(); Assert.assertEquals(200, statusCode); if (statusCode == 200) { Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY)); } }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSConnectionPoolImplTest.java
@Test public void testPoolWithMultipleThreads() { String testAppId = "multithreadTestApp"; /**/*from w w w . j a v a 2 s. com*/ * create 5 threads each sending to 100 devices */ int deviceCount = 100; int threadCount = 5; Map<String, String> payload = new LinkedHashMap<String, String>(100); for (int i = 0; i < deviceCount; i++) { payload.put("device:" + (i + 1), "JSON Payload{}:" + (i + 1)); } objectFactory.clearCounter(); APNSConnectionPoolImpl pool = APNSConnectionPoolImpl.getInstance(); //initialize the pool with connections for all apps // for (int i = 0; i < appIds.length; i++) { // APNSConnection conn = pool.getConnection(appIds[i], true); // pool.returnConnection(conn); // } CountDownLatch countDownLatch = new CountDownLatch(threadCount); Executor executor = Executors.newFixedThreadPool(threadCount, new ThreadFactory() { private AtomicInteger counter = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("TestThread:" + counter.getAndIncrement()); return t; } }); for (int i = 0; i < threadCount; i++) { executor.execute(new SimpleAPNSSenderThread(testAppId, true, payload, countDownLatch)); } //wait for the threads to finish try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); fail(e.getMessage()); } int count = objectFactory.getCreatedCount(new APNSConnectionPoolImpl.APNSConnectionKey(testAppId, true)); assertEquals("Object got created too many times", MAX_OBJECTS_PER_KEY, count); }
From source file:com.tenforce.lodms.extractors.CkanHarvester.java
public void harvest(List<String> datasetIds) throws RDFHandlerException, ExtractException, DatatypeConfigurationException { if (datasetIds.isEmpty()) { throw new ExtractException("no datasets specified"); }//w ww . j a v a 2 s.c om if (enableProvenance) addCatalogProvenance(); MapToRdfConverter converter = new MapToRdfConverter(predicatePrefix, ignoredKeys, handler); ExecutorService executorService = Executors.newFixedThreadPool(5); CountDownLatch barrier = new CountDownLatch(datasetIds.size()); Catalog catalog = new Catalog(baseUri, subjectPrefix); try { for (String datasetId : datasetIds) { executorService.execute(new DataSetHarvester(catalog, converter, handler, apiUri, datasetId, barrier, warnings, httpMethod)); } executorService.shutdown(); barrier.await(); } catch (Exception e) { executorService.shutdownNow(); throw new ExtractException(e.getMessage(), e); } }
From source file:com.blackducksoftware.integration.hub.jenkins.bom.RemoteHubEventPolling.java
/** * Checks the status's in the scan files and polls their URL's, every 10 seconds, * until they have all have status COMPLETE. We keep trying until we hit the maximum wait time. * If we find a scan history object that has status cancelled or an error type then we throw an exception. *///from w ww. jav a 2 s . co m @Override public void assertBomUpToDate(final HubReportGenerationInfo hubReportGenerationInfo, final IntLogger logger) throws InterruptedException, BDRestException, HubIntegrationException, URISyntaxException, IOException { if (StringUtils.isBlank(hubReportGenerationInfo.getScanStatusDirectory())) { throw new HubIntegrationException("The scan status directory must be a non empty value."); } final FilePath statusDirectory = new FilePath(getChannel(), hubReportGenerationInfo.getScanStatusDirectory()); if (!statusDirectory.exists()) { throw new HubIntegrationException("The scan status directory does not exist."); } if (!statusDirectory.isDirectory()) { throw new HubIntegrationException("The scan status directory provided is not a directory."); } final List<FilePath> statusFiles = statusDirectory.list(); if (statusFiles == null || statusFiles.size() == 0) { throw new HubIntegrationException("Can not find the scan status files in the directory provided."); } int expectedNumScans = 0; if (hubReportGenerationInfo.getScanTargets() != null && !hubReportGenerationInfo.getScanTargets().isEmpty()) { expectedNumScans = hubReportGenerationInfo.getScanTargets().size(); } if (statusFiles.size() != expectedNumScans) { throw new HubIntegrationException("There were " + expectedNumScans + " scans configured and we found " + statusFiles.size() + " status files."); } logger.info("Checking the directory : " + statusDirectory.getRemote() + " for the scan status's."); final CountDownLatch lock = new CountDownLatch(expectedNumScans); final List<ScanStatusChecker> scanStatusList = new ArrayList<ScanStatusChecker>(); for (final FilePath currentStatusFile : statusFiles) { final String fileContent = currentStatusFile.readToString(); final Gson gson = new GsonBuilder().create(); final ScanStatusToPoll status = gson.fromJson(fileContent, ScanStatusToPoll.class); if (status.get_meta() == null || status.getStatus() == null) { throw new HubIntegrationException("The scan status file : " + currentStatusFile.getRemote() + " does not contain valid scan status json."); } final ScanStatusChecker checker = new ScanStatusChecker(getService(), status, lock); scanStatusList.add(checker); } logger.debug("Cleaning up the scan status files at : " + statusDirectory.getRemote()); // We delete the files in a second loop to ensure we have all the scan status's in memory before we start // deleting the files. This way, if there is an exception thrown, the User can go look at the files to see what // went wrong. for (final FilePath currentStatusFile : statusFiles) { currentStatusFile.delete(); } statusDirectory.delete(); pollScanStatusChecker(lock, hubReportGenerationInfo, scanStatusList); }
From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestGroup.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public void runTests(List<TestCase> testsToRun, final MobileServiceClient client, final TestExecutionCallback callback) { try {//w w w.java 2 s. co m onPreExecute(client); } catch (Exception e) { mStatus = TestStatus.Failed; if (callback != null) callback.onTestGroupComplete(this, null); return; } final TestRunStatus testRunStatus = new TestRunStatus(); mNewTestRun = true; int oldQueueSize = mTestRunQueue.size(); mTestRunQueue.clear(); mTestRunQueue.addAll(testsToRun); cleanTestsState(); testRunStatus.results.clear(); mStatus = TestStatus.NotRun; if (oldQueueSize == 0) { for (final TestCase test : mTestRunQueue) { final CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread() { public void run() { executeNextTest(test, client, callback, testRunStatus, latch); } }; thread.run(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (test.getStatus() == TestStatus.Failed) { mFailedTestCount++; } } // End Run final CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread() { public void run() { executeNextTest(null, client, callback, testRunStatus, latch); } }; thread.run(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }