Example usage for org.apache.http.client.fluent Async execute

List of usage examples for org.apache.http.client.fluent Async execute

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Async execute.

Prototype

public Future<Content> execute(final Request request, final FutureCallback<Content> callback) 

Source Link

Usage

From source file:com.mycompany.asyncreq.MainApp.java

public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost("comtrade.un.org").setPath("/api/get").setParameter("max", "50000")
            .setParameter("type", "C").setParameter("freq", "M").setParameter("px", "HS")
            .setParameter("ps", "2014").setParameter("r", "804").setParameter("p", "112")
            .setParameter("rg", "All").setParameter("cc", "All").setParameter("fmt", "json");
    URI requestURL = null;/*from   ww  w  .  j  ava2 s .c o  m*/
    try {
        requestURL = builder.build();
    } catch (URISyntaxException use) {
    }

    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);
    final Request request = Request.Get(requestURL);

    try {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {
            @Override
            public void failed(final Exception e) {
                System.out.println(e.getMessage() + ": " + request);
            }

            @Override
            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
                System.out.println("Response:\n" + content.asString());
            }

            @Override
            public void cancelled() {
            }
        });
    } catch (Exception e) {
        System.out.println("Job threw exception: " + e.getCause());
    }

}

From source file:interoperabilite.webservice.fluent.FluentAsync.java

public static void main(String[] args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            @Override/*w  w w  . j a  v a2  s  .  c o m*/
            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }

            @Override
            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            @Override
            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

From source file:io.aos.protocol.http.httpcommon.FluentAsync.java

public static void main(String... args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }// w w w  . ja  v a 2  s  .co m

            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

From source file:MinimalServerTest.java

License:asdf

public void testStartOfSession() throws Exception {
    //Create client
    HttpClient client = new DefaultHttpClient();
    HttpPost mockRequest = new HttpPost("http://localhost:5555/login");
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Add parameters
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("email", "test"));
    urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    //Execute the request
    HttpResponse mockResponse = client.execute(mockRequest, httpContext);

    //Test if normal login is successful
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    rd.close();//from  w  w w  .j a va 2  s. c  o m
    URL newURL = new URL("http://127.0.0.1:5555/start");
    final Request request = Request.Post(newURL.toURI());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Async async = Async.newInstance().use(executor);
    Future<Content> future = async.execute(request, new FutureCallback<Content>() {
        @Override
        public void failed(final Exception e) {
            e.printStackTrace();
        }

        @Override
        public void completed(final Content content) {
            System.out.println("Done");
        }

        @Override
        public void cancelled() {

        }
    });

    server.startSession();
    String asyncResponse = future.get().asString();
    JSONObject jsonTest = new JSONObject();
    //                "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed
    //              "sessionType": "normal", //alternatively Yes/No or winner
    //              "rangeBottom": "0",
    //              "rangeTop": "15",
    //              "description": "image discription here",
    //              "comments": "True",  //True if comments are allowed, False if not
    //              "imgPath": "path/to/image.jpg" //the path where the image resides on the server
    jsonTest.put("status", "1");
    jsonTest.put("sessionType", "normal");
    jsonTest.put("rangeBottom", 0);
    jsonTest.put("rangeTop", 10);
    jsonTest.put("description", "helo");
    jsonTest.put("comments", "true");
    jsonTest.put("imgPath", "temp/1.jpg");
    assertEquals("Testing if login was correctly failed due to incorrect username", jsonTest.toString(),
            asyncResponse);
}

From source file:org.obm.sync.push.client.WBXMLOPClient.java

@Override
public <T> Future<T> postASyncXml(Async async, String namespace, Document doc, String cmd, String policyKey,
        boolean multipart, final ResponseTransformer<T> responseTransformer)
        throws TransformerException, WBXmlException, IOException, HttpRequestException {

    DOMUtils.logDom(doc);/*from   w  w  w.  j a  va2  s . c  om*/

    Request request = buildRequest(namespace, doc, cmd, policyKey, multipart);

    return async.execute(request, new ResponseHandler<T>() {
        @Override
        public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            Document document = new DocumentResponseHandler().handleResponse(response);
            return responseTransformer.parse(document);
        }
    });
}

From source file:net.opentsdb.search.ElasticSearch.java

public Deferred<SearchQuery> executeQuery(final SearchQuery query) {
    final Deferred<SearchQuery> result = new Deferred<SearchQuery>();

    final StringBuilder uri = new StringBuilder("http://");
    uri.append(hosts.get(0).toHostString());
    uri.append("/").append(index).append("/");
    switch (query.getType()) {
    case TSMETA:/*  w  ww .  j  a va 2s. c om*/
    case TSMETA_SUMMARY:
    case TSUIDS:
        uri.append(tsmeta_type);
        break;
    case UIDMETA:
        uri.append(uidmeta_type);
        break;
    case ANNOTATION:
        uri.append(annotation_type);
        break;
    }
    uri.append("/_search");

    // setup the query body
    HashMap<String, Object> body = new HashMap<String, Object>(3);
    body.put("size", query.getLimit());
    body.put("from", query.getStartIndex());

    HashMap<String, Object> qs = new HashMap<String, Object>(1);
    body.put("query", qs);
    HashMap<String, String> query_string = new HashMap<String, String>(1);
    query_string.put("query", query.getQuery());
    qs.put("query_string", query_string);

    final Request request = Request.Post(uri.toString());
    request.bodyByteArray(JSON.serializeToBytes(body));

    final Async async = Async.newInstance().use(threadpool);
    async.execute(request, new SearchCB(query, result));
    return result;
}