Example usage for org.apache.http.client.methods HttpRequestWrapper wrap

List of usage examples for org.apache.http.client.methods HttpRequestWrapper wrap

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestWrapper wrap.

Prototype

public static HttpRequestWrapper wrap(final HttpRequest request) 

Source Link

Usage

From source file:org.apache.http.impl.execchain.RedirectExec.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");

    final List<URI> redirectLocations = context.getRedirectLocations();
    if (redirectLocations != null) {
        redirectLocations.clear();/*from www .j a  va 2  s  .c om*/
    }

    final RequestConfig config = context.getRequestConfig();
    final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
    HttpRoute currentRoute = route;
    HttpRequestWrapper currentRequest = request;
    for (int redirectCount = 0;;) {
        final CloseableHttpResponse response = requestExecutor.execute(currentRoute, currentRequest, context,
                execAware);
        try {
            if (config.isRedirectsEnabled()
                    && this.redirectStrategy.isRedirected(currentRequest, response, context)) {

                if (redirectCount >= maxRedirects) {
                    throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
                }
                redirectCount++;

                final HttpRequest redirect = this.redirectStrategy.getRedirect(currentRequest, response,
                        context);
                if (!redirect.headerIterator().hasNext()) {
                    final HttpRequest original = request.getOriginal();
                    redirect.setHeaders(original.getAllHeaders());
                }
                currentRequest = HttpRequestWrapper.wrap(redirect);

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

                final URI uri = currentRequest.getURI();
                final HttpHost newTarget = URIUtils.extractHost(uri);
                if (newTarget == null) {
                    throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
                }

                // Reset virtual host and auth states if redirecting to another host
                if (!currentRoute.getTargetHost().equals(newTarget)) {
                    final AuthState targetAuthState = context.getTargetAuthState();
                    if (targetAuthState != null) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                    final AuthState proxyAuthState = context.getProxyAuthState();
                    if (proxyAuthState != null) {
                        final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                        if (authScheme != null && authScheme.isConnectionBased()) {
                            this.log.debug("Resetting proxy auth state");
                            proxyAuthState.reset();
                        }
                    }
                }

                currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Redirecting to '" + uri + "' via " + currentRoute);
                }
                EntityUtils.consume(response.getEntity());
                response.close();
            } else {
                return response;
            }
        } catch (final RuntimeException ex) {
            response.close();
            throw ex;
        } catch (final IOException ex) {
            response.close();
            throw ex;
        } catch (final HttpException ex) {
            // Protocol exception related to a direct.
            // The underlying connection may still be salvaged.
            try {
                EntityUtils.consume(response.getEntity());
            } catch (final IOException ioex) {
                this.log.debug("I/O error while releasing connection", ioex);
            } finally {
                response.close();
            }
            throw ex;
        }
    }
}

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

@Override
public void prepare(final HttpHost target, final HttpRequest original, final InternalState state,
        final AbstractClientExchangeHandler<?> handler) throws HttpException, IOException {
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + state.getId() + "] start execution");
    }/*  w w w .j  a  va  2s  . com*/

    final HttpClientContext localContext = state.getLocalContext();

    if (original instanceof Configurable) {
        final RequestConfig config = ((Configurable) original).getConfig();
        if (config != null) {
            localContext.setRequestConfig(config);
        }
    }

    final List<URI> redirectLocations = localContext.getRedirectLocations();
    if (redirectLocations != null) {
        redirectLocations.clear();
    }

    final HttpRequestWrapper request = HttpRequestWrapper.wrap(original);
    final HttpRoute route = this.routePlanner.determineRoute(target, request, localContext);

    handler.setRoute(route);

    state.setMainRequest(request);
    handler.setCurrentRequest(request);

    prepareRequest(state, handler);
}

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  w  w.  j a  v 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;
}

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

@Override
public void responseCompleted(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpResponse currentResponse = handler.getCurrentResponse();

    if (!handler.isRouteEstablished()) {
        final int status = currentResponse.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            handler.setCurrentResponse(null);
            return;
        }//from  w  w w.jav  a 2 s  .co  m
    }

    final boolean keepAlive = handler.manageConnectionPersistence();
    if (!keepAlive) {
        handler.releaseConnection();
        final AuthState proxyAuthState = localContext.getProxyAuthState();
        if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null
                && proxyAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
            }
            proxyAuthState.reset();
        }
        final AuthState targetAuthState = localContext.getTargetAuthState();
        if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null
                && targetAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
            }
            targetAuthState.reset();
        }
    }

    Object userToken = localContext.getUserToken();
    if (userToken == null) {
        userToken = this.userTokenHandler.getUserToken(localContext);
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
    }

    if (state.getFinalResponse() != null) {
        final HttpAsyncResponseConsumer<?> responseConsumer = state.getResponseConsumer();
        responseConsumer.responseCompleted(localContext);
        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + state.getId() + "] Response processed");
        }
        handler.releaseConnection();
    } else {
        if (state.getRedirect() != null) {
            final HttpUriRequest redirect = state.getRedirect();
            final URI uri = redirect.getURI();
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Redirecting to '" + uri + "'");
            }
            state.setRedirect(null);

            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }

            // Reset auth states if redirecting to another host
            final HttpRoute route = handler.getRoute();
            if (!route.getTargetHost().equals(newTarget)) {
                final AuthState targetAuthState = localContext.getTargetAuthState();
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
                }
                targetAuthState.reset();
                final AuthState proxyAuthState = localContext.getProxyAuthState();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
                    }
                    proxyAuthState.reset();
                }
            }

            if (!redirect.headerIterator().hasNext()) {
                final HttpRequest original = state.getMainRequest().getOriginal();
                redirect.setHeaders(original.getAllHeaders());
            }

            final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(redirect);
            final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, newRequest, localContext);
            if (!route.equals(newRoute)) {
                handler.releaseConnection();
            }
            handler.setRoute(newRoute);
            handler.setCurrentRequest(newRequest);
            state.setMainRequest(newRequest);
            prepareRequest(state, handler);
        }
    }
    handler.setCurrentResponse(null);
}

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

public void start() throws HttpException, IOException {
    final HttpHost target = this.requestProducer.getTarget();
    final HttpRequest original = this.requestProducer.generateRequest();

    if (original instanceof HttpExecutionAware) {
        ((HttpExecutionAware) original).setCancellable(this);
    }/* ww w.  ja  v  a  2  s  .  c  om*/
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + getId() + "] start execution");
    }

    if (original instanceof Configurable) {
        final RequestConfig config = ((Configurable) original).getConfig();
        if (config != null) {
            this.localContext.setRequestConfig(config);
        }
    }

    final HttpRequestWrapper request = HttpRequestWrapper.wrap(original);
    final HttpRoute route = new HttpRoute(target);
    setCurrentRequest(request);
    setRoute(route);

    this.localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    this.localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    this.localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);

    this.httpProcessor.process(request, this.localContext);

    requestConnection();
}

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

@Override
public HttpRequest generateRequest() throws IOException, HttpException {
    verifytRoute();/*  www.j a  va 2  s. com*/
    if (!isRouteEstablished()) {
        onRouteToTarget();
        onRouteComplete();
    }
    final NHttpClientConnection localConn = getConnection();
    this.localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, localConn);

    Asserts.check(this.requestProducerRef.get() == null,
            "Inconsistent state: currentRequest producer is not null");
    final HttpAsyncRequestProducer requestProducer = this.requestProducerQueue.poll();
    if (requestProducer == null) {
        return null;
    }
    this.requestProducerRef.set(requestProducer);

    final HttpRequest original = requestProducer.generateRequest();
    final HttpRequestWrapper currentRequest = HttpRequestWrapper.wrap(original);
    final RequestConfig config = this.localContext.getRequestConfig();
    if (config.getSocketTimeout() > 0) {
        localConn.setSocketTimeout(config.getSocketTimeout());
    }

    this.httpProcessor.process(currentRequest, this.localContext);

    this.requestQueue.add(currentRequest);
    setCurrentRequest(currentRequest);

    return currentRequest;
}

From source file:org.opennms.core.web.HttpClientWrapper.java

/**
 * Execute the given HTTP method, returning an HTTP response.
 * /*w w w  .  jav  a  2 s .  com*/
 * Note that when you are done with the response, you must call {@link #closeResponse()} so that it gets cleaned up properly.
 */
public CloseableHttpResponse execute(final HttpUriRequest method) throws ClientProtocolException, IOException {
    LOG.debug("execute: " + this.toString() + "; method: " + method.toString());
    // override some headers with our versions
    final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(method);
    if (!isEmpty(m_userAgent)) {
        requestWrapper.setHeader(HTTP.USER_AGENT, m_userAgent);
    }
    if (!isEmpty(m_virtualHost)) {
        requestWrapper.setHeader(HTTP.TARGET_HOST, m_virtualHost);
    }

    if (m_version != null) {
        if (HttpVersion.HTTP_1_1.equals(m_version) && isEmpty(m_virtualHost)) {
            // NMS-7506, set HTTP version to 1.0 if virtual host is not set (since 1.1 requires a virtual host)
            requestWrapper.setProtocolVersion(HttpVersion.HTTP_1_0);
        } else {
            requestWrapper.setProtocolVersion(m_version);
        }
    }

    return getClient().execute(requestWrapper);
}