Example usage for org.apache.http.client NonRepeatableRequestException NonRepeatableRequestException

List of usage examples for org.apache.http.client NonRepeatableRequestException NonRepeatableRequestException

Introduction

In this page you can find the example usage for org.apache.http.client NonRepeatableRequestException NonRepeatableRequestException.

Prototype

public NonRepeatableRequestException(final String message) 

Source Link

Document

Creates a new NonRepeatableEntityException with the specified detail message.

Usage

From source file:com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;/*from  w  w w .  ja v  a2  s  .  c  o  m*/
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }

            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request "
                                + "with a non-repeatable request entity.  The cause lists the "
                                + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException(
                                "Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }

                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;

                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName()
                                    + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }

                    // If we have a direct route to the target host
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }

                }

            }

            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;//from   w ww  .  ja  v a 2  s  .  c om
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }

            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request "
                                + "with a non-repeatable request entity.  The cause lists the "
                                + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException(
                                "Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }

                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;

                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName()
                                    + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }

                    // If we have a direct route to the target host
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }

                }

            }

            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException | RuntimeException | IOException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.apache.http.impl.execchain.MainClientExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    AuthState targetAuthState = context.getTargetAuthState();
    if (targetAuthState == null) {
        targetAuthState = new AuthState();
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState);
    }//from  www . ja  v  a 2  s .  co m
    AuthState proxyAuthState = context.getProxyAuthState();
    if (proxyAuthState == null) {
        proxyAuthState = new AuthState();
        context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        Proxies.enhanceEntity((HttpEntityEnclosingRequest) request);
    }

    Object userToken = context.getUserToken();

    final ConnectionRequest connRequest = connManager.requestConnection(route, userToken);
    if (execAware != null) {
        if (execAware.isAborted()) {
            connRequest.cancel();
            throw new RequestAbortedException("Request aborted");
        } else {
            execAware.setCancellable(connRequest);
        }
    }

    final RequestConfig config = context.getRequestConfig();

    final HttpClientConnection managedConn;
    try {
        final int timeout = config.getConnectionRequestTimeout();
        managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException interrupted) {
        Thread.currentThread().interrupt();
        throw new RequestAbortedException("Request aborted", interrupted);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        throw new RequestAbortedException("Request execution failed", cause);
    }

    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);

    if (config.isStaleConnectionCheckEnabled()) {
        // validate connection
        if (managedConn.isOpen()) {
            this.log.debug("Stale connection check");
            if (managedConn.isStale()) {
                this.log.debug("Stale connection detected");
                managedConn.close();
            }
        }
    }

    final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn);
    try {
        if (execAware != null) {
            execAware.setCancellable(connHolder);
        }

        HttpResponse response;
        for (int execCount = 1;; execCount++) {

            if (execCount > 1 && !Proxies.isRepeatable(request)) {
                throw new NonRepeatableRequestException(
                        "Cannot retry request " + "with a non-repeatable request entity.");
            }

            if (execAware != null && execAware.isAborted()) {
                throw new RequestAbortedException("Request aborted");
            }

            if (!managedConn.isOpen()) {
                this.log.debug("Opening connection " + route);
                try {
                    establishRoute(proxyAuthState, managedConn, route, request, context);
                } catch (final TunnelRefusedException ex) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug(ex.getMessage());
                    }
                    response = ex.getResponse();
                    break;
                }
            }
            final int timeout = config.getSocketTimeout();
            if (timeout >= 0) {
                managedConn.setSocketTimeout(timeout);
            }

            if (execAware != null && execAware.isAborted()) {
                throw new RequestAbortedException("Request aborted");
            }

            if (this.log.isDebugEnabled()) {
                this.log.debug("Executing request " + request.getRequestLine());
            }

            if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Target auth state: " + targetAuthState.getState());
                }
                this.authenticator.generateAuthResponse(request, targetAuthState, context);
            }
            if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Proxy auth state: " + proxyAuthState.getState());
                }
                this.authenticator.generateAuthResponse(request, proxyAuthState, context);
            }

            response = requestExecutor.execute(request, managedConn, context);

            // The connection is in or can be brought to a re-usable state.
            if (reuseStrategy.keepAlive(response, context)) {
                // Set the idle duration of this connection
                final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
                connHolder.markReusable();
            } else {
                connHolder.markNonReusable();
            }

            if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) {
                // Make sure the response body is fully consumed, if present
                final HttpEntity entity = response.getEntity();
                if (connHolder.isReusable()) {
                    EntityUtils.consume(entity);
                } else {
                    managedConn.close();
                    if (proxyAuthState.getState() == AuthProtocolState.SUCCESS
                            && proxyAuthState.getAuthScheme() != null
                            && proxyAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting proxy auth state");
                        proxyAuthState.reset();
                    }
                    if (targetAuthState.getState() == AuthProtocolState.SUCCESS
                            && targetAuthState.getAuthScheme() != null
                            && targetAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                }
                // discard previous auth headers
                final HttpRequest original = request.getOriginal();
                if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) {
                    request.removeHeaders(AUTH.WWW_AUTH_RESP);
                }
                if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) {
                    request.removeHeaders(AUTH.PROXY_AUTH_RESP);
                }
            } else {
                break;
            }
        }

        if (userToken == null) {
            userToken = userTokenHandler.getUserToken(context);
            context.setAttribute(HttpClientContext.USER_TOKEN, userToken);
        }
        if (userToken != null) {
            connHolder.setState(userToken);
        }

        // check for entity, release connection if possible
        final HttpEntity entity = response.getEntity();
        if (entity == null || !entity.isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            connHolder.releaseConnection();
            return Proxies.enhanceResponse(response, null);
        } else {
            return Proxies.enhanceResponse(response, connHolder);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        connHolder.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        connHolder.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        connHolder.abortConnection();
        throw ex;
    }
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

@Override
public synchronized HttpRequest generateRequest() throws IOException, HttpException {
    final HttpRoute route = this.mainRequest.getRoute();
    if (!this.routeEstablished) {
        int step;
        do {//from  ww  w .  j av a2s  .  co  m
            final HttpRoute fact = this.managedConn.getRoute();
            step = this.routeDirector.nextStep(route, fact);
            switch (step) {
            case HttpRouteDirector.CONNECT_TARGET:
            case HttpRouteDirector.CONNECT_PROXY:
                break;
            case HttpRouteDirector.TUNNEL_TARGET:
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + this.id + "] Tunnel required");
                }
                final HttpRequest connect = createConnectRequest(route);
                this.currentRequest = wrapRequest(connect);
                this.currentRequest.setParams(this.params);
                break;
            case HttpRouteDirector.TUNNEL_PROXY:
                throw new HttpException("Proxy chains are not supported");
            case HttpRouteDirector.LAYER_PROTOCOL:
                managedConn.layerProtocol(this.localContext, this.params);
                break;
            case HttpRouteDirector.UNREACHABLE:
                throw new HttpException(
                        "Unable to establish route: " + "planned = " + route + "; current = " + fact);
            case HttpRouteDirector.COMPLETE:
                this.routeEstablished = true;
                break;
            default:
                throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector.");
            }
        } while (step > HttpRouteDirector.COMPLETE && this.currentRequest == null);
    }

    HttpHost target = (HttpHost) this.params.getParameter(ClientPNames.VIRTUAL_HOST);
    if (target == null) {
        target = route.getTargetHost();
    }
    final HttpHost proxy = route.getProxyHost();
    this.localContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
    this.localContext.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
    this.localContext.setAttribute(ExecutionContext.HTTP_CONNECTION, this.managedConn);
    this.localContext.setAttribute(ClientContext.ROUTE, route);

    if (this.currentRequest == null) {
        this.currentRequest = this.mainRequest.getRequest();

        final String userinfo = this.currentRequest.getURI().getUserInfo();
        if (userinfo != null) {
            this.targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
        }

        // Re-write request URI if needed
        rewriteRequestURI(this.currentRequest, route);
    }
    // Reset headers on the request wrapper
    this.currentRequest.resetHeaders();

    this.currentRequest.incrementExecCount();
    if (this.currentRequest.getExecCount() > 1 && !this.requestProducer.isRepeatable()
            && this.requestContentProduced) {
        throw new NonRepeatableRequestException(
                "Cannot retry request " + "with a non-repeatable request entity.");
    }
    this.execCount++;
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + this.id + "] Attempt " + this.execCount + " to execute request");
    }
    return this.currentRequest;
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

@Override
public HttpRequest generateRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {

    final HttpRoute route = handler.getRoute();

    handler.verifytRoute();/*from  w  ww  .jav  a2  s .c  o m*/

    if (!handler.isRouteEstablished()) {
        int step;
        loop: do {
            final HttpRoute fact = handler.getActualRoute();
            step = this.routeDirector.nextStep(route, fact);
            switch (step) {
            case HttpRouteDirector.CONNECT_TARGET:
                handler.onRouteToTarget();
                break;
            case HttpRouteDirector.CONNECT_PROXY:
                handler.onRouteToProxy();
                break;
            case HttpRouteDirector.TUNNEL_TARGET:
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + state.getId() + "] Tunnel required");
                }
                final HttpRequest connect = createConnectRequest(route, state);
                handler.setCurrentRequest(HttpRequestWrapper.wrap(connect));
                break loop;
            case HttpRouteDirector.TUNNEL_PROXY:
                throw new HttpException("Proxy chains are not supported");
            case HttpRouteDirector.LAYER_PROTOCOL:
                handler.onRouteUpgrade();
                break;
            case HttpRouteDirector.UNREACHABLE:
                throw new HttpException(
                        "Unable to establish route: " + "planned = " + route + "; current = " + fact);
            case HttpRouteDirector.COMPLETE:
                handler.onRouteComplete();
                this.log.debug("Connection route established");
                break;
            default:
                throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector.");
            }
        } while (step > HttpRouteDirector.COMPLETE);
    }

    final HttpClientContext localContext = state.getLocalContext();
    HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    if (currentRequest == null) {
        currentRequest = state.getMainRequest();
        handler.setCurrentRequest(currentRequest);
    }

    if (handler.isRouteEstablished()) {
        state.incrementExecCount();
        if (state.getExecCount() > 1) {
            final HttpAsyncRequestProducer requestProducer = state.getRequestProducer();
            if (!requestProducer.isRepeatable() && state.isRequestContentProduced()) {
                throw new NonRepeatableRequestException(
                        "Cannot retry request " + "with a non-repeatable request entity.");
            }
            requestProducer.resetRequest();
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + state.getId() + "] Attempt " + state.getExecCount()
                    + " to execute request");
        }

        if (!currentRequest.containsHeader(AUTH.WWW_AUTH_RESP)) {
            final AuthState targetAuthState = localContext.getTargetAuthState();
            if (this.log.isDebugEnabled()) {
                this.log.debug("Target auth state: " + targetAuthState.getState());
            }
            this.authenticator.generateAuthResponse(currentRequest, targetAuthState, localContext);
        }
        if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) {
            final AuthState proxyAuthState = localContext.getProxyAuthState();
            if (this.log.isDebugEnabled()) {
                this.log.debug("Proxy auth state: " + proxyAuthState.getState());
            }
            this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext);
        }
    } else {
        if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP)) {
            final AuthState proxyAuthState = localContext.getProxyAuthState();
            if (this.log.isDebugEnabled()) {
                this.log.debug("Proxy auth state: " + proxyAuthState.getState());
            }
            this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext);
        }
    }

    final NHttpClientConnection managedConn = handler.getConnection();
    localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
    final RequestConfig config = localContext.getRequestConfig();
    if (config.getSocketTimeout() > 0) {
        managedConn.setSocketTimeout(config.getSocketTimeout());
    }
    return currentRequest;
}