Example usage for org.apache.http.impl.client HttpRequestFutureTask startedTime

List of usage examples for org.apache.http.impl.client HttpRequestFutureTask startedTime

Introduction

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

Prototype

public long startedTime() 

Source Link

Usage

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());/*ww w. j a v  a  2  s  . c  o  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);
        }

    }
}