List of usage examples for java.util.concurrent CountDownLatch await
public void await() throws InterruptedException
From source file:io.pivotal.ListApplicationsApplication.java
public static void main(String[] args) throws InterruptedException { ConfigurableApplicationContext applicationContext = SpringApplication.run(ListApplicationsApplication.class, args);/*from w w w .j av a 2 s . com*/ CloudFoundryClient cloudFoundryClient = applicationContext.getBean(CloudFoundryClient.class); CloudFoundryOperations cloudFoundryOperations = applicationContext.getBean(CloudFoundryOperations.class); CountDownLatch latch = new CountDownLatch(1); cloudFoundryOperations.applications().list().flatMap( application -> Mono.just(application).and(getServiceInstances(cloudFoundryClient, application))) .map(function(FormattingUtils::formatApplication)).subscribe(System.out::println, t -> { t.printStackTrace(); latch.countDown(); }, latch::countDown); latch.await(); }
From source file:example.topic.Subscriber.java
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim();//from w w w. jav a 2 s .c o m } System.out .println("\nWaiting to receive messages... Either waiting for END message or press Ctrl+C to exit"); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url); Connection connection = null; final CountDownLatch latch = new CountDownLatch(1); try { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createTopic("test-topic"); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(new Subscriber(latch)); latch.await(); consumer.close(); session.close(); } catch (Exception e) { System.out.println("Caught exception!"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { System.out.println("Could not close an open connection..."); } } } }
From source file:example.topic.durable.Subscriber.java
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim();// w w w .j a v a2s. c om } System.out .println("\nWaiting to receive messages... Either waiting for END message or press Ctrl+C to exit"); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url); Connection connection = null; final CountDownLatch latch = new CountDownLatch(1); try { connection = connectionFactory.createConnection(); String clientId = System.getProperty("clientId"); connection.setClientID(clientId); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); Topic destination = session.createTopic("test-topic"); MessageConsumer consumer = session.createDurableSubscriber(destination, clientId); consumer.setMessageListener(new Subscriber(latch)); latch.await(); consumer.close(); session.close(); } catch (Exception e) { System.out.println("Caught exception!"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { System.out.println("Could not close an open connection..."); } } } }
From source file:gobblin.test.TestWorker.java
@SuppressWarnings("all") public static void main(String[] args) throws Exception { // Build command-line options Option configOption = OptionBuilder.withArgName("framework config file") .withDescription("Configuration properties file for the framework").hasArgs().withLongOpt("config") .create('c'); Option jobConfigsOption = OptionBuilder.withArgName("job config files") .withDescription("Comma-separated list of job configuration files").hasArgs() .withLongOpt("jobconfigs").create('j'); Option modeOption = OptionBuilder.withArgName("run mode") .withDescription("Test mode (schedule|run); 'schedule' means scheduling the jobs, " + "whereas 'run' means running the jobs immediately") .hasArg().withLongOpt("mode").create('m'); Option helpOption = OptionBuilder.withArgName("help").withDescription("Display usage information") .withLongOpt("help").create('h'); Options options = new Options(); options.addOption(configOption);/*from www . j a v a2 s . c om*/ options.addOption(jobConfigsOption); options.addOption(modeOption); options.addOption(helpOption); // Parse command-line options CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { printUsage(options); System.exit(0); } // Start the test worker with the given configuration properties Configuration config = new PropertiesConfiguration(cmd.getOptionValue('c')); Properties properties = ConfigurationConverter.getProperties(config); TestWorker testWorker = new TestWorker(properties); testWorker.start(); // Job running mode Mode mode = Mode.valueOf(cmd.getOptionValue('m').toUpperCase()); // Get the list of job configuration files List<String> jobConfigFiles = Lists .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(cmd.getOptionValue('j'))); CountDownLatch latch = new CountDownLatch(jobConfigFiles.size()); for (String jobConfigFile : jobConfigFiles) { // For each job, load the job configuration, then run or schedule the job. Properties jobProps = new Properties(); jobProps.load(new FileReader(jobConfigFile)); jobProps.putAll(properties); testWorker.runJob(jobProps, mode, new TestJobListener(latch)); } // Wait for all jobs to finish latch.await(); testWorker.stop(); }
From source file:com.ok2c.lightmtp.examples.LocalMailClientTransportExample.java
public static void main(final String[] args) throws Exception { String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n" + "This is a short test message 1\r\n"; String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n" + "This is a short test message 2\r\n"; String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n" + "\r\n" + "This is a short test message 3\r\n"; DeliveryRequest request1 = new BasicDeliveryRequest("root", Arrays.asList("testuser1"), new ByteArraySource(text1.getBytes("US-ASCII"))); DeliveryRequest request2 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"), new ByteArraySource(text2.getBytes("US-ASCII"))); DeliveryRequest request3 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2", "testuser3"), new ByteArraySource(text3.getBytes("US-ASCII"))); Queue<DeliveryRequest> queue = new ConcurrentLinkedQueue<DeliveryRequest>(); queue.add(request1);//www. j a v a2 s .c o m queue.add(request2); queue.add(request3); CountDownLatch messageCount = new CountDownLatch(queue.size()); IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); MailClientTransport mua = new LocalMailClientTransport(config); mua.start(new MyDeliveryRequestHandler(messageCount)); SessionEndpoint endpoint = new SessionEndpoint(new InetSocketAddress("localhost", 2525)); SessionRequest sessionRequest = mua.connect(endpoint, queue, null); sessionRequest.waitFor(); IOSession iosession = sessionRequest.getSession(); if (iosession != null) { messageCount.await(); } else { IOException ex = sessionRequest.getException(); if (ex != null) { System.out.println("Connection failed: " + ex.getMessage()); } } System.out.println("Shutting down I/O reactor"); try { mua.shutdown(); } catch (IOException ex) { mua.forceShutdown(); } System.out.println("Done"); }
From source file:com.example.AsyncClientHttpExchangeFutureCallback.java
public static void main(String[] args) throws Exception { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); httpclient.start();/* w w w. ja va 2 s . c o m*/ try { HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.shutdown(); } System.out.println("Done"); }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientHttpExchangeFutureCallback.java
public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .build();//from w w w . j ava 2 s. co m try { httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:rg.apache.http.examples.async.AsyncClientHttpExchangeFutureCallback.java
public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .setThreadFactory(new NamedThreadFactory("dddddddd")).build(); try {//from w w w .ja v a 2s . c o m httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://httpbin.org/ip"), new HttpGet("https://httpbin.org/ip"), new HttpGet("http://httpbin.org/headers") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:httpasync.QuickStart.java
public static void main(String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try {//from w w w .j a va2 s.c o m // Start the client httpclient.start(); // Execute request final HttpGet request1 = new HttpGet("http://www.apache.org/"); Future<HttpResponse> future = httpclient.execute(request1, null); // and wait until response is received HttpResponse response1 = future.get(); System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine()); // One most likely would want to use a callback for operation result final CountDownLatch latch1 = new CountDownLatch(1); final HttpGet request2 = new HttpGet("http://www.apache.org/"); httpclient.execute(request2, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response2) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine()); } @Override public void failed(final Exception ex) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch1.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch1.await(); // In real world one most likely would want also want to stream // request and response body content final CountDownLatch latch2 = new CountDownLatch(1); final HttpGet request3 = new HttpGet("http://www.apache.org/"); HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3); AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override protected void onResponseReceived(final HttpResponse response) { this.response = response; } @Override protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { // Do something useful } @Override protected void releaseResources() { } @Override protected HttpResponse buildResult(final HttpContext context) { return this.response; } }; httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response3) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine()); } @Override public void failed(final Exception ex) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch2.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch2.await(); } finally { httpclient.close(); } }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientEvictExpiredConnections.java
public static void main(String[] args) throws Exception { ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); cm.setMaxTotal(100);//from w ww. ja v a 2 s . com CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(cm).build(); try { httpclient.start(); // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", }; IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); connEvictor.start(); final CountDownLatch latch = new CountDownLatch(urisToGet.length); for (final String uri : urisToGet) { final HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(httpget.getRequestLine() + " cancelled"); } }); } latch.await(); // Sleep 10 sec and let the connection evictor do its job Thread.sleep(20000); // Shut down the evictor thread connEvictor.shutdown(); connEvictor.join(); } finally { httpclient.close(); } }