Example usage for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute

List of usage examples for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute.

Prototype

@Override
    public Future<HttpResponse> execute(final HttpUriRequest request, final FutureCallback<HttpResponse> callback) 

Source Link

Usage

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);// w w w. j a  v a2 s  . c  om
    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();
    }
}

From source file:com.controller.CPMOrderMANIAC.java

public static List<SingleOrder> updateOrders()
        throws ExecutionException, InterruptedException, IOException, JSONException {
    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;//from www. j  a v a 2 s.  c o m

    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/pm/orders/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    List<SingleOrder> arrayOrders = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentOrder = new JSONObject();
        try {
            currentOrder = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());
        arrayOrders.add(currentSingleOrder);
    }
    arrayOrdersMaster = arrayOrders;

    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!arrayOrdersMaster.isEmpty()) {
        return arrayOrdersMaster;
    } else {
        System.out.println("ASYNC ORDERS IS EMPTY.");
        return null;
    }
}

From source file:org.wisdom.test.http.HttpClientHelper.java

/**
 * Emits an asynchronous request.//from   www . j a v  a2s . c o  m
 *
 * @param request       the request
 * @param responseClass the response class
 * @param callback      the completion callback
 * @param <T>           the type of the expected result
 * @return the future to retrieve the result
 */
public static <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request);

    CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        /**
         * Cancels the request.
         *
         * @param mayInterruptIfRunning whether or not we need to interrupt the request.
         * @return {@literal true} if the task is successfully canceled.
         */
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        /**
         * @return whether the future is cancelled.
         */
        public boolean isCancelled() {
            return future.isCancelled();
        }

        /**
         * @return whether the result is available.
         */
        public boolean isDone() {
            return future.isDone();
        }

        /**
         * Gets the result.
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         */
        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<>(httpResponse, responseClass);
        }

        /**
         * Gets the result.
         * @param timeout timeout configuration
         * @param unit unit timeout
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         * @throws TimeoutException if the set time out is reached before the completion of the request.
         */
        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout * TimeUtils.TIME_FACTOR, unit);
            return new HttpResponse<>(httpResponse, responseClass);
        }
    };
}

From source file:com.controller.CTraderOrderMANIAC.java

public static List<Block> updateBlockOrderHistory()
        throws InterruptedException, ExecutionException, IOException, JSONException {
    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/*from ww w .  ja  v a2  s .co m*/

    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/blocks/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    ArrayList<Block> arrayBlock = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentBlock = new JSONObject();
        try {
            currentBlock = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        Block currBlock = JsonParsing.parseJsonToBlockObject(currentBlock.toString());
        arrayBlock.add(currBlock);
    }
    blockHistory = arrayBlock;

    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!blockHistory.isEmpty()) {
        return blockHistory;
    } else {
        System.out.println("ASYNC BLOCK HISTORY IS EMPTY.");
        return null;
    }
}

From source file:com.controller.CTraderOrderMANIAC.java

public static List<SingleOrder> updateOrders()
        throws InterruptedException, IOException, JSONException, ExecutionException {

    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/*from   ww  w  .j  a v a  2s .com*/
    System.out.println("Username in update orders is: " + currUsername);
    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/orders/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    System.out.println("ASYNC JSON STRING IS : " + json_string);
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    List<SingleOrder> arrayOrders = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentOrder = new JSONObject();
        try {
            currentOrder = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());

        arrayOrders.add(currentSingleOrder);
    }
    arrayOrdersMaster = arrayOrders;
    System.out.println("-----------------> THIS ARRAY IS: " + arrayOrdersMaster.size());
    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!arrayOrdersMaster.isEmpty()) {
        return arrayOrdersMaster;
    } else {
        System.out.println("ASYNC ORDERS IS EMPTY.");
        return null;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java

public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
        boolean fireAndForgot) throws DeviceManagementException {

    String responseMsg = "";
    String urlString = ArduinoConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;

    if (log.isDebugEnabled()) {
        log.debug(urlString);//from   w w  w .  j a v  a2  s . c om
    }

    if (!fireAndForgot) {
        HttpURLConnection httpConnection = getHttpConnection(urlString);

        try {
            httpConnection.setRequestMethod(HttpMethod.GET);
        } catch (ProtocolException e) {
            String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:"
                    + urlString;
            log.error(errorMsg);
            throw new DeviceManagementException(errorMsg, e);
        }

        responseMsg = readResponseFromGetRequest(httpConnection);

    } else {
        CloseableHttpAsyncClient httpclient = null;
        try {

            httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
            HttpGet request = new HttpGet(urlString);
            final CountDownLatch latch = new CountDownLatch(1);
            Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    latch.countDown();
                }

                @Override
                public void failed(Exception e) {
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (InterruptedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Sync Interrupted");
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();

                }
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed on close");
                }
            }
        }
    }

    return responseMsg;
}

From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java

public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
        boolean fireAndForgot) throws DeviceManagementException {

    String responseMsg = "";
    String urlString = ConnectedCupConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;

    if (log.isDebugEnabled()) {
        log.debug(urlString);// w  w w  .  j  a  va2s. c o m
    }

    if (!fireAndForgot) {
        HttpURLConnection httpConnection = getHttpConnection(urlString);

        try {
            httpConnection.setRequestMethod(HttpMethod.GET);
        } catch (ProtocolException e) {
            String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:"
                    + urlString;
            log.error(errorMsg);
            throw new DeviceManagementException(errorMsg, e);
        }

        responseMsg = readResponseFromGetRequest(httpConnection);

    } else {
        CloseableHttpAsyncClient httpclient = null;
        try {

            httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
            HttpGet request = new HttpGet(urlString);
            final CountDownLatch latch = new CountDownLatch(1);
            Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    latch.countDown();
                }

                @Override
                public void failed(Exception e) {
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (InterruptedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Sync Interrupted");
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();

                }
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed on close");
                }
            }
        }
    }

    return responseMsg;
}

From source file:com.controller.CPMEndOfDay.java

public static void getEODData() throws InterruptedException, IOException, JSONException {
    System.out.println("EOD DATA THREAD RUNNING.");
    try {/*w  ww  . j a  v a  2s. c  o  m*/
        String currUsername = CMAIN.reportUser().getUsername();
        HttpResponse<JsonNode> resp;

        ArrayList<SingleOrder> boughtOrders = new ArrayList<>();
        ArrayList<SingleOrder> soldOrders = new ArrayList<>();

        String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
        String timeToCompare = "16:30";
        int x = currentTime.compareTo(timeToCompare);

        //INIT CLIENT
        CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
        client.start();

        //REQUEST
        HttpGet request;

        if (x >= 0) {
            request = new HttpGet("http://139.59.17.119:8080/api/pm/eod/" + currUsername + "/0");
        } else {
            request = new HttpGet("http://139.59.17.119:8080/api/pm/eod/" + currUsername + "/1");
        }

        //GET AND PARSE RESPONSE
        Future<org.apache.http.HttpResponse> future = client.execute(request, null);
        org.apache.http.HttpResponse response = future.get();
        String json_string = EntityUtils.toString(response.getEntity());
        JSONArray arrJson = new JSONArray(json_string);

        //GET ORDERS FROM ARRAY
        ArrayList<SingleOrder> arrayOrders = new ArrayList<>();

        for (int i = 0; i < arrJson.length(); i++) {
            JSONObject currentOrder = arrJson.getJSONObject(i);
            SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());

            //DO THE DATE PART
            if (currentSingleOrder.getStatus().equals("Executed")) {
                // System.out.println("# executed by :" + currUsername);
                arrayOrders.add(currentSingleOrder);
            }
        }

        for (SingleOrder o : arrayOrders) {
            if (o.getAction().equals("Sell")) {
                soldOrders.add(o);
            } else if (o.getAction().equals("Buy")) {
                boughtOrders.add(o);
            }
        }

        setBought(boughtOrders);
        setSold(soldOrders);

        //DONT FORGET TO KILL CLIENT
        try {
            client.close();
        } catch (IOException ex) {
            Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (ExecutionException ex) {
        Logger.getLogger(CPMEndOfDay.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.rapidoid.http.HttpClientUtil.java

static Future<HttpResp> request(HttpReq config, CloseableHttpAsyncClient client, Callback<HttpResp> callback,
        boolean close) {

    HttpRequestBase req = createRequest(config);
    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    Promise<HttpResp> promise = Promises.create();
    FutureCallback<HttpResponse> cb = callback(client, callback, promise, close);
    client.execute(req, cb);

    return promise;
}