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

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

Introduction

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

Prototype

public abstract void start();

Source Link

Usage

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, String callUrlPattern,
        boolean fireAndForgot) throws DeviceManagementException {

    if (deviceServerPort == 0) {
        deviceServerPort = 80;//  w  ww  . j  av a  2s .c o  m
    }

    String responseMsg = "";
    String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern;

    if (log.isDebugEnabled()) {
        log.debug(urlString);
    }

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