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

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

Introduction

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

Prototype

public static Async newInstance() 

Source Link

Usage

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  va2  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);
            }//from  ww 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: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   www  . j  ava  2s .  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:org.obm.servlet.filter.qos.util.AsyncServletRequestUtils.java

public AsyncServletRequestUtils(ExecutorService executorService, int port, String servletName) {
    this.async = Async.newInstance().use(executorService);
    this.serviceUri = "http://localhost:" + port + "/" + servletName;
    this.count = 0;
}

From source file:org.obm.opush.command.PushContinuationTest.java

@Before
public void setup() throws Exception {
    threadpool = Executors.newFixedThreadPool(4);
    async = Async.newInstance().use(threadpool);
    httpClient = HttpClientBuilder.create().build();
    cassandraServer.start();//from  ww  w  .ja  v a  2  s  . c  o m

    user = users.jaures;
    inboxCollectionId = CollectionId.of(1234);
    inboxPath = MailboxPath.of(EmailConfiguration.IMAP_INBOX_NAME);
    inboxFolder = Folder.builder().backendId(inboxPath).collectionId(inboxCollectionId)
            .parentBackendIdOpt(Optional.<BackendId>absent()).displayName("INBOX")
            .folderType(FolderType.DEFAULT_INBOX_FOLDER).build();

    FolderSyncKey syncKey = new FolderSyncKey("4fd6280c-cbaa-46aa-a859-c6aad00f1ef3");
    folderSnapshotDao.create(user.user, user.device, syncKey,
            FolderSnapshot.nextId(2).folders(ImmutableSet.of(inboxFolder)));

    expect(policyConfigurationProvider.get()).andReturn("fakeConfiguration");
}

From source file:org.obm.opush.PingHandlerTest.java

@Before
public void init() throws Exception {
    cassandraServer.start();//from   w w  w . j a  v a2s. c o m

    threadpool = Executors.newFixedThreadPool(4);
    async = Async.newInstance().use(threadpool);
    httpClient = HttpClientBuilder.create().build();

    expect(policyConfigurationProvider.get()).andReturn("fakeConfiguration");
}

From source file:com.movilizer.mds.webservice.services.UploadFileService.java

private CompletableFuture<UploadResponse> upload(HttpEntity entity, Integer connectionTimeoutInMillis) {
    CompletableFuture<UploadResponse> future = new CompletableFuture<>();
    try {/* w  w  w . ja va  2 s . c  o  m*/

        Async.newInstance().execute(
                Request.Post(documentUploadAddress.toURI())
                        .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT)
                        .connectTimeout(connectionTimeoutInMillis).body(entity),
                new ResponseHandlerAdapter<UploadResponse>(future) {
                    @Override
                    public UploadResponse convertHttpResponse(HttpResponse httpResponse) {
                        logger.info(Messages.UPLOAD_COMPLETE);
                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();
                        if (statusCode == POSSIBLE_BAD_CREDENTIALS) {
                            errorMessage = errorMessage + Messages.FAILED_FILE_UPLOAD_CREDENTIALS;
                        }
                        return new UploadResponse(statusCode, errorMessage);
                    }
                });
    } catch (URISyntaxException e) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format(Messages.UPLOAD_ERROR, e.getMessage()));
        }
        future.completeExceptionally(new MovilizerWebServiceException(e));
    }
    return future;
}

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:/*from www  .  jav  a2s  .c o m*/
    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;
}

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  ww 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);
}