Example usage for org.apache.http.protocol ExecutionContext HTTP_PROXY_HOST

List of usage examples for org.apache.http.protocol ExecutionContext HTTP_PROXY_HOST

Introduction

In this page you can find the example usage for org.apache.http.protocol ExecutionContext HTTP_PROXY_HOST.

Prototype

String HTTP_PROXY_HOST

To view the source code for org.apache.http.protocol ExecutionContext HTTP_PROXY_HOST.

Click Source Link

Usage

From source file:yangqi.hc.HttpContextTest.java

/**
 * @param args//from  w  ww. j  av  a2 s.  co m
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    HttpContext context = new BasicHttpContext();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget, context);

    showAttr(ExecutionContext.HTTP_CONNECTION, context);
    showAttr(ExecutionContext.HTTP_PROXY_HOST, context);
    showAttr(ExecutionContext.HTTP_REQ_SENT, context);
    showAttr(ExecutionContext.HTTP_RESPONSE, context);
    showAttr(ExecutionContext.HTTP_REQUEST, context);
    showAttr(ExecutionContext.HTTP_TARGET_HOST, context);

}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from  w  ww.  jav a 2 s .  c  o  m
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:freeipa.client.negotiation.JBossNegotiateScheme.java

/**
 * Produces Negotiate authorization Header based on token created by processChallenge.
 *
 * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
 *        from JAAS will be used instead.
 * @param request The request being authenticated
 *
 * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
 *
 * @return an Negotiate authorization Header
 *//*  w  w w. j  a  va2  s  .co m*/
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = ExecutionContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }

        System.out.println("init " + authServer);

        final Oid negotiationOid = new Oid(SPNEGO_OID);

        final GSSManager manager = GSSManager.getInstance();
        final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid),
                negotiationOid, null, DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);

        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }

        state = State.TOKEN_GENERATED;
        String tokenstr = new String(base64codec.encode(token));
        System.out.println("Sending response '" + tokenstr + "' back to the auth server");

        CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.JBossNegotiateScheme.java

/**
 * Produces Negotiate authorization Header based on token created by processChallenge.
 * //from  ww w .j av  a 2s.c o  m
 * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
 *        from JAAS will be used instead.
 * @param request The request being authenticated
 * 
 * @throws AuthenticationException if authorisation string cannot be generated due to an authentication failure
 * 
 * @return an Negotiate authorisation Header
 */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = ExecutionContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }

        if (log.isDebugEnabled()) {
            log.debug("init " + authServer);
        }
        /*
         * Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JBoss. Unwrapping the initial token
         * when using SPNEGO OID looks like what is described here...
         * 
         * http://msdn.microsoft.com/en-us/library/ms995330.aspx
         * 
         * Another helpful URL...
         * 
         * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/
         * tsec_SPNEGO_token.html
         * 
         * Unfortunately SPNEGO is JRE >=1.6.
         */

        /** Try SPNEGO by default, fall back to Kerberos later if error */
        negotiationOid = new Oid(SPNEGO_OID);

        boolean tryKerberos = false;
        try {
            GSSManager manager = getManager();
            GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
            gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null,
                    DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        } catch (GSSException ex) {
            // BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH.
            // Rethrow any other exception.
            if (ex.getMajor() == GSSException.BAD_MECH) {
                log.debug("GSSException BAD_MECH, retry with Kerberos MECH");
                tryKerberos = true;
            } else {
                throw ex;
            }

        }
        if (tryKerberos) {
            /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */
            log.debug("Using Kerberos MECH " + KERBEROS_OID);
            negotiationOid = new Oid(KERBEROS_OID);
            GSSManager manager = getManager();
            GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
            gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null,
                    DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        }
        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }

        /*
         * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? seem to only accept SPNEGO. Below
         * wraps Kerberos into SPNEGO token.
         */
        if (spengoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) {
            token = spengoGenerator.generateSpnegoDERObject(token);
        }

        state = State.TOKEN_GENERATED;
        String tokenstr = new String(Base64.encodeBase64(token, false));
        if (log.isDebugEnabled()) {
            log.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        return new BasicHeader("Authorization", "Negotiate " + tokenstr);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    } catch (IOException ex) {
        state = State.FAILED;
        throw new AuthenticationException(ex.getMessage());
    }
}

From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java

/**
 * {@inheritDoc}/*from   www  . j a  v a  2  s.com*/
 */
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (target.getPort() < 0) {
        SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY);
        Scheme scheme = schemeRegistry.getScheme(target);
        target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()),
                target.getSchemeName());
    }

    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null) {
        authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        return;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        return;
    }

    final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(target);
        if (authScheme != null) {
            doPreemptiveAuth(target, authScheme, targetState, credsProvider);
        }
    }

    final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
    final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(proxy);
        if (authScheme != null) {
            doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
        }
    }
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java

@Override
public HttpResponse execute(HttpHost originalTarget, final HttpRequest request, HttpContext context)
        throws HttpException, IOException {
    HttpHost target = originalTarget;//from   w ww.  ja v  a2s .  c  o  m
    final HttpRoute route = determineRoute(target, request, context);

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

    long timeout = ConnManagerParams.getTimeout(params);

    try {
        HttpResponse 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 (request instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) request).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()) {
                    LOGGER.debug("Stale connection check");
                    if (managedConn.isStale()) {
                        LOGGER.debug("Stale connection detected");
                        managedConn.close();
                    }
                }
            }
        }

        if (request instanceof AbortableHttpRequest) {
            ((AbortableHttpRequest) request).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) {
            LOGGER.debug(ex.getMessage());
            response = ex.getResponse();
        }

        // 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(request, httpProcessor, context);

        try {
            response = requestExec.execute(request, managedConn, context);
        } catch (IOException ex) {
            LOGGER.debug("Closing connection after request failure.");
            managedConn.close();
            throw ex;
        }

        if (response == null) {
            return null;
        }

        // 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.
        boolean 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 (duration >= 0) {
                LOGGER.trace("Connection can be kept alive for " + duration + " ms");
            } else {
                LOGGER.trace("Connection can be kept alive indefinitely");
            }
        }

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

        // check for entity, release connection if possible
        if ((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: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;//  ww w.j  av  a  2 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.vietspider.net.apache.DefaultRequestDirector.java

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

    HttpRequest orig = request;/*from w w  w. j  ava  2  s .  co 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 = HttpConnectionParams.getConnectionTimeout(params);

    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 {
                    //                      if(timeout < 1) timeout = 30000;
                    //                      System.out.println(" =========== chay vao day roi nhe " + timeout );
                    //                      System.out.println(connRequest);
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                    //                        System.out.println("get thuc chuyen nay");
                } 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);
            }

            try {
                tryConnect(roureq, 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);

            response = tryExecute(roureq, context);
            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);
                if (this.log.isDebugEnabled()) {
                    String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
            }

            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();
                    EntityUtils.consume(entity);
                    // 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 (ConnectionShutdownException ex) {
        InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } 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;//w w  w .  j  a  va2  s  .co  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 | RuntimeException | IOException ex) {
        abortConnection();
        throw ex;
    }
}