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:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

/**
 * <p>/*from w w  w  . j a va2s .c  om*/
 * Initiate a transaction for sending data.
 * </p>
 *
 * <p>
 * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest.
 * Then client has to resend the same request with its credential added.
 * This mechanism is problematic for sending data from NiFi.
 * </p>
 *
 * <p>
 * In order to resend a POST request with auth param,
 * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere.
 * If we store that in memory, it would causes OOM, or storing it on disk slows down performance.
 * Rolling back processing session would be overkill.
 * Reading flow-file contents only when it's ready to send in a streaming way is ideal.
 * </p>
 *
 * <p>
 * Additionally, the way proxy authentication is done is vary among Proxy server software.
 * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and
 * the proxy server, then consecutive requests skip auth steps.
 * The problem is, that how should we behave is only told after sending a request to the proxy.
 * </p>
 *
 * In order to handle above concerns correctly and efficiently, this method do the followings:
 *
 * <ol>
 * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests.
 *      This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li>
 * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works.
 * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data.
 * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li>
 * <li>Then this method stores whether the final POST request should wait for the auth step.
 * So that {@link #openConnectionForSend} can determine when to produce contents.</li>
 * </ol>
 *
 * <p>
 * The above special sequence is only executed when a proxy instance is set, and its username is set.
 * </p>
 *
 * @param post a POST request to establish transaction
 * @return POST request response
 * @throws IOException thrown if the post request failed
 */
private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException {
    if (shouldCheckProxyAuth()) {
        final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient();
        final HttpGet get = createGetControllerRequest();
        final Future<HttpResponse> getResult = asyncClient.execute(get, null);
        try {
            final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS);
            logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine());
        } catch (final ExecutionException e) {
            logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}",
                    e.getMessage());
            throw toIOException(e);
        } catch (TimeoutException | InterruptedException e) {
            throw new IOException(e);
        }
    }

    final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() {
        private boolean requestHasBeenReset = false;

        @Override
        public HttpHost getTarget() {
            return URIUtils.extractHost(post.getURI());
        }

        @Override
        public HttpRequest generateRequest() throws IOException, HttpException {
            final BasicHttpEntity entity = new BasicHttpEntity();
            post.setEntity(entity);
            return post;
        }

        @Override
        public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException {
            encoder.complete();
            if (shouldCheckProxyAuth() && requestHasBeenReset) {
                logger.debug("Produced content again, assuming the proxy server requires authentication.");
                proxyAuthRequiresResend.set(true);
            }
        }

        @Override
        public void requestCompleted(HttpContext context) {
            debugProxyAuthState(context);
        }

        @Override
        public void failed(Exception ex) {
            final String msg = String.format("Failed to create transaction for %s", post.getURI());
            logger.error(msg, ex);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
        }

        @Override
        public boolean isRepeatable() {
            return true;
        }

        @Override
        public void resetRequest() throws IOException {
            requestHasBeenReset = true;
        }

        @Override
        public void close() throws IOException {
        }
    };

    final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer,
            new BasicAsyncResponseConsumer(), null);
    final HttpResponse response;
    try {
        response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS);

    } catch (final ExecutionException e) {
        logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage());
        throw toIOException(e);
    } catch (TimeoutException | InterruptedException e) {
        throw new IOException(e);
    }
    return response;
}

From source file:com.micro.rent.common.comm.aio.AsyncClientHttpExchangeFutureCallback.java

public void httpAsync() throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();/*from  w w w . j  a  v  a 2  s  . com*/
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[list.size()];
        for (int i = 0; i < list.size(); i++) {
            BigDecimal lat = list.get(i).getLatitude();
            BigDecimal lon = list.get(i).getLongitude();
            RequestParam reqParam = new RequestParam();
            reqParam.setDestination(lat.toString().concat(",").concat(lon.toString()));
            reqParam.setOrigin(String.valueOf(wpLat).concat(",").concat(String.valueOf(wpLon)));
            reqParam.setMode(queryVo.getTrafficType());
            switch (ETranfficType.getSelfByCode(queryVo.getTrafficType())) {
            case DRIVING:
                reqParam.setOrigin_region(queryVo.getCityName());
                reqParam.setDestination_region(queryVo.getCityName());
                break;
            case TRANSIT:
            case WALKING:
                reqParam.setRegion(queryVo.getCityName());
                break;
            default:
                break;
            }
            requests[i] = new HttpGet(timeUrl(reqParam));
        }
        long start = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (int j = 0; j < requests.length; j++) {
            final HttpGet request = requests[j];
            final int k = j;
            httpclient.execute(request, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    try {
                        InputStream a = response.getEntity().getContent();
                        String responseString = readInputStream(a);
                        String duration = duration(responseString);
                        list.get(k).setDuration(duration);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                public void failed(final Exception ex) {
                    latch.countDown();
                }

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

            });
        }
        latch.await();
        log.info(System.currentTimeMillis() - start + "-----------------ms----");
    } finally {
        httpclient.close();
    }
}

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

private Future<byte[]> execute(CloseableHttpAsyncClient client, HttpRequestBase req, Callback<byte[]> callback,
        boolean fullResponse) {

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
            .setConnectionRequestTimeout(10000).build();
    req.setConfig(requestConfig);/*ww  w  .  jav  a  2  s.c o  m*/

    Promise<byte[]> promise = Promises.create();

    FutureCallback<HttpResponse> cb = callback(callback, promise, fullResponse);
    client.execute(req, cb);

    return promise;
}

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;//from  w w w  . j  a va  2  s .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;
}