Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

In this page you can find the example usage for java.util.concurrent Future get.

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.boonya.http.async.examples.nio.client.AsyncClientExecuteProxy.java

public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {/* w w w .ja  v  a 2  s .co m*/
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        request.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();/*w  ww .  j av a2  s.co  m*/
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}

From source file:Test.java

public static void main(String[] args) throws Exception {

    AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
    InetSocketAddress address = new InetSocketAddress("localhost", 5000);

    Future<Void> future = client.connect(address);
    System.out.println("Client: Waiting for the connection to complete");
    future.get();

    String message = "";
    while (!message.equals("quit")) {
        System.out.print("Enter a message: ");
        Scanner scanner = new Scanner(System.in);
        message = scanner.nextLine();/*from w  w  w . j a va  2  s .  com*/
        System.out.println("Client: Sending ...");
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        System.out.println("Client: Message sent: " + new String(buffer.array()));
        client.write(buffer);
    }
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientProxyAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("someproxy", 8080),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();// w ww  .  j a  va 2s. com
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("https://issues.apache.org/");
        httpget.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}

From source file:com.boonya.http.async.examples.nio.client.ZeroCopyHttpExchange.java

public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {// w  ww  .java 2  s .c  om
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload,
                ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:com.example.AsyncClientHttpExchange.java

public static void main(String[] args) throws Exception {
    HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
    httpclient.start();/*from   www  .j  a  v  a2 s . c  o  m*/
    try {

        ArrayList<Future<HttpResponse>> response = new ArrayList<Future<HttpResponse>>();

        ArrayList<String> sites = new ArrayList<String>();

        sites.add("MLA");
        sites.add("MLB");
        sites.add("MLU");
        sites.add("MLV");

        for (String site : sites) {
            HttpGet request = new HttpGet("https://api.mercadolibre.com/sites/" + site);
            Future<HttpResponse> r = httpclient.execute(request, null);
            response.add(r);
        }

        System.out.println("lalala........");
        System.out.println("lalala........");
        System.out.println("lalala........");

        for (Future<HttpResponse> future : response) {
            HttpResponse r = future.get();
            System.out.println("Response: " + r.getStatusLine());
            System.out.println("Body : " + convertStreamToString(r.getEntity().getContent()));
        }

    } finally {
        httpclient.shutdown();
    }
    System.out.println("Done");
}

From source file:httpasync.ZeroCopyHttpExchange.java

public static void main(final String[] args) throws Exception {

    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//  w  w w . j  av a  2  s  . com
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload,
                ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:com.ok2c.lightmtp.examples.MailUserAgentExample.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";

    List<DeliveryRequest> requests = new ArrayList<DeliveryRequest>();
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII"))));

    MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT);
    mua.start();/*w w  w .  j a  va2  s. c o  m*/

    try {

        InetSocketAddress address = new InetSocketAddress("localhost", 2525);

        Queue<Future<DeliveryResult>> queue = new LinkedList<Future<DeliveryResult>>();
        for (DeliveryRequest request : requests) {
            queue.add(mua.deliver(new SessionEndpoint(address), 0, request, null));
        }

        while (!queue.isEmpty()) {
            Future<DeliveryResult> future = queue.remove();
            DeliveryResult result = future.get();
            System.out.println("Delivery result: " + result);
        }

    } finally {
        mua.shutdown();
    }
}

From source file:com.amazonaws.services.dynamodbv2.streamsadapter.StreamsMultiLangDaemon.java

/**
 * @param args Accepts a single argument, that argument is a properties file which provides KCL configuration as
 *             well as the name of an executable.
 *//*from w  w w  .j av  a 2  s .  co  m*/
public static void main(String[] args) {

    if (args.length == 0) {
        MultiLangDaemon.printUsage(System.err, "You must provide a properties file");
        System.exit(1);
    }
    MultiLangDaemonConfig config = null;
    try {
        config = new MultiLangDaemonConfig(args[0]);
    } catch (IOException | IllegalArgumentException e) {
        MultiLangDaemon.printUsage(System.err, "You must provide a valid properties file");
        System.exit(1);
    }

    final ExecutorService executorService = config.getExecutorService();
    final Worker worker = StreamsWorkerFactory.createDynamoDbStreamsWorker(config.getRecordProcessorFactory(),
            config.getKinesisClientLibConfiguration(), executorService);

    // Daemon
    final MultiLangDaemon daemon = new MultiLangDaemon(worker);

    final Future<Integer> future = executorService.submit(daemon);
    try {
        System.exit(future.get());
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Encountered an error while running daemon", e);
    }
    System.exit(1);
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("my.keystore"));
    try {/*from   w w w .  ja  v  a2 s  .  c  o  m*/
        trustStore.load(instream, "nopassword".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" },
            null, SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}