Example usage for org.apache.http.impl.client FutureRequestExecutionService execute

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

Introduction

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

Prototype

public <T> HttpRequestFutureTask<T> execute(final HttpUriRequest request, final HttpContext context,
        final ResponseHandler<T> responseHandler) 

Source Link

Document

Schedule a request for execution.

Usage

From source file:com.lxf.spider.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);//from ww  w .  j av  a 2 s .  c  om
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://google.com");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://google.com");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://google.com");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://google.com");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}

From source file:interoperabilite.webservice.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);/*  ww w .ja  v  a  2  s .  co m*/
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            @Override
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://httpbin.org/get");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            @Override
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            @Override
            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://httpbin.org/get");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}

From source file:com.yahoo.yrlhaifa.liveqa.challenge.http_operation.QuestionOperationHttpRequestSender.java

private void sendRequestsWithRequestExecutor(final FutureRequestExecutionService requestExecutor)
        throws QuestionOperationException, InterruptedException {
    final long timeOut = requestGeneralParameters.getTimeForAnswerMilliseconds()
            + requestGeneralParameters.getExtraTimeForRequestResponseMilliseconds()
            + requestGeneralParameters.getSlackTimeForRequestExecutorTimeOutMilliseconds();
    final long maximumAllowedDuration = requestGeneralParameters.getTimeForAnswerMilliseconds()
            + requestGeneralParameters.getExtraTimeForRequestResponseMilliseconds();

    List<HttpRequestFutureTask<Participant>> futures = new ArrayList<HttpRequestFutureTask<Participant>>(
            participants.size());//  w  w w. jav  a  2  s .  co m
    for (Participant participant : participants) {
        HttpRequestFutureTask<Participant> future = requestExecutor.execute(createRequest(participant), null,
                new AnswerResponseHandler(participant));
        futures.add(future);
    }

    systemsSucceeded = new LinkedHashSet<Participant>();
    final long loopStartTime = new Date().getTime();
    long extraAdd = 0;
    for (HttpRequestFutureTask<Participant> future : futures) {
        try {
            final long timePassed = (new Date().getTime() - loopStartTime);
            extraAdd += Constants.EXTRA_ADD_TIMEOUT_FOR_EACH_THREAD_MILLISECONDS;
            final long currentIterationTimeOut = extraAdd + Math.max(0, (timeOut - timePassed));
            if (logger.isDebugEnabled()) {
                logger.debug("Getting a future with time-out of " + currentIterationTimeOut + " milliseconds");
            }
            Participant participantOfThisFuture = future.get(currentIterationTimeOut, TimeUnit.MILLISECONDS);
            logger.info("System " + participantOfThisFuture.getUniqueSystemId()
                    + " has finished the question processing.");
            if (!future.isDone()) {
                logger.info("Processing by system: \"" + participantOfThisFuture.getUniqueSystemId()
                        + "\" is not done, and is being cancelled now.");
                future.cancel(true);
            } else {
                if (!future.isCancelled()) {
                    if (future.taskDuration() <= maximumAllowedDuration) {
                        systemsSucceeded.add(participantOfThisFuture);
                        boolean inMap = false;
                        if (mapParticipantToAnswer.containsKey(participantOfThisFuture)) {
                            final ParticipantResponse answer = mapParticipantToAnswer
                                    .get(participantOfThisFuture);
                            if (answer != null) {
                                inMap = true;
                                ResponseOperationInformation responseOperationInformation = new ResponseOperationInformation(
                                        future.startedTime(), future.endedTime(), future.taskDuration());
                                answer.setResponseOperationInformation(responseOperationInformation);
                            }
                        }
                        if (!inMap) {
                            logger.info("A request-response for participant \""
                                    + participantOfThisFuture.getUniqueSystemId()
                                    + "\" has completed with no answer."); // Such a behavior might follow
                                                                                                                                                                             // unsuccessful status code, or
                                                                                                                                                                             // when the participant decides
                                                                                                                                                                             // not to answer, while sending
                                                                                                                                                                             // an HTTP response.
                                                                                                                                                                             // logger.error("Unexpected behavior: A participant request-response ended successfully,
                                                                                                                                                                             // but the answer was not put in the map. This is a bug. Program continues, however.");
                        }
                    } else {
                        logger.info("System \"" + participantOfThisFuture.getUniqueSystemId()
                                + "\" has finished, but not in time (time out has not been reached, thanks to slack executor time. However, the required time constraints were not met).\n"
                                + "It\'s answer (if exists) will be discarded."); // will be discarded by
                                                                                                                                                                                                                                                                                                                    // not including that
                                                                                                                                                                                                                                                                                                                    // system in the
                                                                                                                                                                                                                                                                                                                    // "systemSucceeded" set.
                    }
                }
            }
        } catch (InterruptedException e) {
            // I was interrupted (someone called Thread.interrupt() on this thread. This has nothing to do with the
            // executor's threads).
            // I must stop. There is nothing special for cleanup, so let's just stop.
            throw e;
        } catch (CancellationException e) {
            // The task was cancelled. Nothing to worry about. If it has been cancelled, than it will not write into
            // the map. Just log it.
            logger.info("One of the requests was cancelled: " + e.getMessage() + ". Program continues.");
        } catch (ExecutionException e) {
            // An HTTP problem. Either IO or protocol problem. Never mind. This is not system-wide fatal problem.
            // Let's log it, and continue.
            logger.error("One of the requests failed to execute. Program continues.", e);
        } catch (TimeoutException e) {
            // A time-out has been reached. Again, nothing to worry about. I have to cancel the task.
            // Its output should be discarded, and I take care of it above (in the try block) implicitly, when I do
            // not include this
            // system-id in the "systemsSucceeded" set.
            // Even if the task writes its result into the map, it will be removed, and the removal happens after
            // the executor.shutdownNow(),
            // So we can be sure it is finally not in the map.
            String exceptionMessage = e.getMessage();
            if (null == exceptionMessage) {
                exceptionMessage = "";
            } else
                exceptionMessage = " <" + exceptionMessage + ">";
            logger.info("One of the requests has timed-out" + exceptionMessage + ". Program continues.");
            future.cancel(true);
        }

    }
}