Example usage for org.apache.http.client.params HttpClientParams isAuthenticating

List of usage examples for org.apache.http.client.params HttpClientParams isAuthenticating

Introduction

In this page you can find the example usage for org.apache.http.client.params HttpClientParams isAuthenticating.

Prototype

public static boolean isAuthenticating(final HttpParams params) 

Source Link

Usage

From source file:com.google.android.apps.authenticator.testability.HttpClientFactoryTest.java

public void testClientConfiguration() throws Exception {
    HttpParams params = mClient.getParams();
    assertFalse(HttpClientParams.isRedirecting(params));
    assertFalse(HttpClientParams.isAuthenticating(params));
    assertEquals(HttpClientFactory.DEFAULT_CONNECT_TIMEOUT_MILLIS,
            HttpConnectionParams.getConnectionTimeout(params));
    assertEquals(HttpClientFactory.DEFAULT_READ_TIMEOUT_MILLIS, HttpConnectionParams.getSoTimeout(params));
    assertEquals(HttpClientFactory.DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS,
            ConnManagerParams.getTimeout(params));
}

From source file:org.opendatakit.http.conn.GaeManagedClientConnection.java

@Override
public void flush() throws IOException {
    // flush is always called by 
    // org.apache.http.protocol.HttpRequestExecutor.doSendRequest

    // Build and issue the URLFetch request here.
    URLFetchService service = URLFetchServiceFactory.getURLFetchService();

    boolean redirect = HttpClientParams.isRedirecting(params);
    @SuppressWarnings("unused")
    boolean authenticate = HttpClientParams.isAuthenticating(params);
    // TODO: verify that authentication is handled by URLFetchService...

    // default is to throw an exception on a overly-large request
    // follow redirects (e.g., to https), and to validate server
    // certificates.
    com.google.appengine.api.urlfetch.FetchOptions f = com.google.appengine.api.urlfetch.FetchOptions.Builder
            .withDefaults();//  w w  w.j  a va  2  s. co m
    f.disallowTruncate();
    f.validateCertificate();
    if (redirect) {
        f.followRedirects();
    } else {
        f.doNotFollowRedirects();
    }

    // set a deadline if we have a wait-for-continue limit
    // in an expectContinue situation 
    // or a timeout value set on the connection.
    HttpParams params = request.getParams();
    int deadline = 0;
    int msWaitForContinue = params.getIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000);
    if (expectContinueHeaders == null) {
        msWaitForContinue = 0;
    }
    int soTimeout = org.apache.http.params.HttpConnectionParams.getSoTimeout(params);
    int connTimeout = org.apache.http.params.HttpConnectionParams.getConnectionTimeout(params);
    if (soTimeout <= 0 || connTimeout <= 0) {
        deadline = 0; // wait forever...
    } else {
        int maxDelay = Math.max(Math.max(timeoutMilliseconds, msWaitForContinue), connTimeout);
        deadline = soTimeout + maxDelay;
    }

    if (deadline > 0) {
        logger.info("URLFetch timeout (socket + connection) (ms): " + deadline);
        f.setDeadline(new Double(0.001 * (double) deadline));
    }
    f.validateCertificate();

    com.google.appengine.api.urlfetch.HTTPMethod method;
    if (request instanceof HttpGet) {
        method = HTTPMethod.GET;
    } else if (request instanceof HttpPut) {
        method = HTTPMethod.PUT;
    } else if (request instanceof HttpPost) {
        method = HTTPMethod.POST;
    } else if (request instanceof HttpHead) {
        method = HTTPMethod.HEAD;
    } else if (request instanceof HttpDelete) {
        method = HTTPMethod.DELETE;
    } else if (request instanceof EntityEnclosingRequestWrapper) {
        String name = ((EntityEnclosingRequestWrapper) request).getMethod();
        method = HTTPMethod.valueOf(name);
    } else if (request instanceof RequestWrapper) {
        String name = ((RequestWrapper) request).getMethod();
        method = HTTPMethod.valueOf(name);
    } else {
        throw new IllegalStateException("Unrecognized Http request method");
    }

    // we need to construct the URL for the request
    // to the target host.  The request line, for, e.g., 
    // a get, needs to be added to the URL.
    URL url = new URL(targetHost.getSchemeName(), targetHost.getHostName(), targetHost.getPort(),
            request.getRequestLine().getUri());

    com.google.appengine.api.urlfetch.HTTPRequest req = new com.google.appengine.api.urlfetch.HTTPRequest(url,
            method, f);

    Header[] headers = request.getAllHeaders();
    for (Header h : headers) {
        req.addHeader(new com.google.appengine.api.urlfetch.HTTPHeader(h.getName(), h.getValue()));
    }
    // restore the expect-continue header
    if (expectContinueHeaders != null) {
        for (Header h : expectContinueHeaders) {
            req.addHeader(new com.google.appengine.api.urlfetch.HTTPHeader(h.getName(), h.getValue()));
        }
    }

    // see if we need to copy entity body over...
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        if (entity != null) {
            ByteArrayOutputStream blobStream = new ByteArrayOutputStream();
            entity.writeTo(blobStream);
            req.setPayload(blobStream.toByteArray());
        }
    }

    response = service.fetch(req);
}

From source file:x.y.z.DefaultRequestDirector.java

protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
            final HttpContext context) throws HttpException, IOException {
        test();//from ww w  .j a va 2  s  .  co m
        String something = new String();
        String somethingElse = "";
        List<Something> somethingList = null;
        test(something);
        final HttpRoute route = roureq.getRoute();
        final RequestWrapper request = roureq.getRequest();
        final HttpParams params = request.getParams();
        int i = org.apache.http.params.HttpConnectionParams.getConnectionTimeout(parmas);
        javax.rmi.CORBA obj;
        if (HttpClientParams.isAuthenticating(params)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            if (target.getPort() < 0) {
                final Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), target.getSchemeName());
            }
            final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target, response,
                    this.targetAuthStrategy, targetAuthState, context);
            HttpHost proxy = route.getProxyHost();
            if (proxy == null) {
                proxy = route.getTargetHost();
            }
            final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(proxy, response,
                    this.proxyAuthStrategy, proxyAuthState, context);
            if (targetAuthRequested) {
                if (this.authenticator.authenticate(target, response, this.targetAuthStrategy, this.targetAuthState,
                        context)) {
                    return roureq;
                }
            }
            if (proxyAuthRequested) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy, this.proxyAuthState,
                        context)) {
                    return roureq;
                }
            }
        }
        if (HttpClientParams.isRedirecting(params)
                && this.redirectStrategy.isRedirected(request, response, context)) {
            if (redirectCount >= maxRedirects) {
                throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
            }
            redirectCount++;
            virtualHost = null;
            final HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
            final HttpRequest orig = request.getOriginal();
            redirect.setHeaders(orig.getAllHeaders());
            final URI uri = redirect.getURI();
            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }
            if (!route.getTargetHost().equals(newTarget)) {
                this.log.debug("Resetting target auth state");
                targetAuthState.reset();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    this.log.debug("Resetting proxy auth state");
                    proxyAuthState.reset();
                }
            }
            final RequestWrapper wrapper = wrapRequest(redirect);
            wrapper.setParams(params);
            final HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
            final RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
            }
            return newRequest;
        }
        return null;
    }

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

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 * //from  w  ww  . j  a  v a  2s  .  c o  m
 * @param route
 *            the route to establish
 * @param context
 *            the context for request execution
 * 
 * @return <code>true</code> if the tunnelled route is secure,
 *         <code>false</code> otherwise.
 *         The implementation here always returns <code>false</code>,
 *         but derived classes may override.
 * 
 * @throws HttpException
 *             in case of a problem
 * @throws IOException
 *             in case of an IO problem
 */
private boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {

    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    boolean done = false;
    while (!done) {

        done = true;

        if (!managedConn.isOpen()) {
            managedConn.open(route, context, params);
        }

        HttpRequest connect = createConnectRequest(route);
        connect.setParams(params);

        // 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);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);

        requestExec.preProcess(connect, httpProcessor, context);

        response = requestExec.execute(connect, managedConn, context);

        response.setParams(params);
        requestExec.postProcess(response, httpProcessor, context);

        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);

        if ((credsProvider != null) && HttpClientParams.isAuthenticating(params)) {
            if (proxyAuthHandler.isAuthenticationRequested(response, context)) {

                LOGGER.debug("Proxy requested authentication");
                Map<String, Header> challenges = proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, proxyAuthState, proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    LOGGER.warn("Authentication error: " + ex.getMessage());
                }
                updateAuthState(proxyAuthState, proxy, credsProvider);

                if (proxyAuthState.getCredentials() != null) {
                    done = false;

                    // Retry request
                    if (reuseStrategy.keepAlive(response, context)) {
                        LOGGER.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        managedConn.close();
                    }

                }

            } else {
                // Reset proxy auth scope
                proxyAuthState.setAuthScope(null);
            }
        }
    }

    int status = response.getStatusLine().getStatusCode(); // can't be null

    if (status > 299) {

        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

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

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///from  ww  w . j  a  va 2  s . c  om
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {

    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    boolean done = false;
    while (!done) {

        done = true;

        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }

        HttpRequest connect = createConnectRequest(route, context);
        connect.setParams(this.params);

        // 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);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);

        this.requestExec.preProcess(connect, this.httpProcessor, context);

        response = this.requestExec.execute(connect, this.managedConn, context);

        response.setParams(this.params);
        this.requestExec.postProcess(response, this.httpProcessor, context);

        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);

        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response,
                            context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);

                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;

                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }

                }

            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }

    int status = response.getStatusLine().getStatusCode(); // can't be null

    if (status > 299) {

        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    this.managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

From source file:org.vietspider.net.apache.DefaultRequestDirector.java

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///from   w  w w .  ja  v a2s.  co m
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {

    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    boolean done = false;
    while (!done) {

        done = true;

        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }

        HttpRequest connect = createConnectRequest(route, context);
        connect.setParams(this.params);

        // 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);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);

        this.requestExec.preProcess(connect, this.httpProcessor, context);

        response = this.requestExec.execute(connect, this.managedConn, context);

        response.setParams(this.params);
        this.requestExec.postProcess(response, this.httpProcessor, context);

        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);

        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response,
                            context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);

                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;

                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        EntityUtils.consume(entity);
                    } else {
                        this.managedConn.close();
                    }

                }

            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }

    int status = response.getStatusLine().getStatusCode(); // can't be null

    if (status > 299) {

        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    this.managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

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

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *//*from w  w  w  .j ava  2  s . c o m*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();

    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {

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

        // Virtual host cannot be used any longer
        virtualHost = null;

        URI uri = this.redirectHandler.getLocationURI(response, context);

        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);

        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }

        HttpRedirect redirect = new HttpRedirect(request.getMethod(), uri);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        RequestWrapper wrapper = new RequestWrapper(redirect);
        wrapper.setParams(params);

        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);

    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {

        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }

            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);

            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }

        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost proxy = route.getProxyHost();

            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);

            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}

From source file:org.vietspider.net.apache.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///  w  w  w . j a v a  2 s  .  c  o  m
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();

    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params)
            && this.redirectStrategy.isRedirected(request, response, context)) {

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

        // Virtual host cannot be used any longer
        virtualHost = null;

        HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
        HttpRequest orig = request.getOriginal();
        //            redirect.setHeaders(orig.getAllHeaders());
        //VietSpider fix bug
        URI uri = redirect.getURI();
        Header[] headers = orig.getAllHeaders();
        for (Header header : headers) {
            if ("host".equalsIgnoreCase(header.getName())) {
                redirect.addHeader(new BasicHeader("Host", uri.getHost()));
            } else {
                redirect.addHeader(header);
            }
        }

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

        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);

        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }

        RequestWrapper wrapper = wrapRequest(redirect);
        wrapper.setParams(params);

        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);

    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {

        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }

            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);

            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }

        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost proxy = route.getProxyHost();

            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);

            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *//*from ww  w  .ja v a 2s .  c om*/
protected boolean createTunnelToTarget(final HttpRoute route, final HttpContext context)
        throws HttpException, IOException {

    final HttpHost proxy = route.getProxyHost();
    final HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    for (;;) {
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }

        final HttpRequest connect = createConnectRequest(route, context);
        connect.setParams(this.params);

        // 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(ExecutionContext.HTTP_REQUEST, connect);

        this.requestExec.preProcess(connect, this.httpProcessor, context);

        response = this.requestExec.execute(connect, this.managedConn, context);

        response.setParams(this.params);
        this.requestExec.postProcess(response, this.httpProcessor, context);

        final int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        if (HttpClientParams.isAuthenticating(this.params)) {
            if (this.authenticator.isAuthenticationRequested(proxy, response, this.proxyAuthStrategy,
                    this.proxyAuthState, context)) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy,
                        this.proxyAuthState, context)) {
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        final HttpEntity entity = response.getEntity();
                        EntityUtils.consume(entity);
                    } else {
                        this.managedConn.close();
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    final int status = response.getStatusLine().getStatusCode();

    if (status > 299) {

        // Buffer response content
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    this.managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///from ww  w.  j  a v  a2s .  c  o m
protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {

    final HttpRoute route = roureq.getRoute();
    final RequestWrapper request = roureq.getRequest();

    final HttpParams params = request.getParams();

    if (HttpClientParams.isAuthenticating(params)) {
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            target = route.getTargetHost();
        }
        if (target.getPort() < 0) {
            final Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
            target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), target.getSchemeName());
        }

        final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target, response,
                this.targetAuthStrategy, targetAuthState, context);

        HttpHost proxy = route.getProxyHost();
        // if proxy is not set use target host instead
        if (proxy == null) {
            proxy = route.getTargetHost();
        }
        final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(proxy, response,
                this.proxyAuthStrategy, proxyAuthState, context);

        if (targetAuthRequested) {
            if (this.authenticator.authenticate(target, response, this.targetAuthStrategy, this.targetAuthState,
                    context)) {
                // Re-try the same request via the same route
                return roureq;
            }
        }
        if (proxyAuthRequested) {
            if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy, this.proxyAuthState,
                    context)) {
                // Re-try the same request via the same route
                return roureq;
            }
        }
    }

    if (HttpClientParams.isRedirecting(params)
            && this.redirectStrategy.isRedirected(request, response, context)) {

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

        // Virtual host cannot be used any longer
        virtualHost = null;

        final HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
        final HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        final URI uri = redirect.getURI();
        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
        if (!route.getTargetHost().equals(newTarget)) {
            this.log.debug("Resetting target auth state");
            targetAuthState.reset();
            final AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                this.log.debug("Resetting proxy auth state");
                proxyAuthState.reset();
            }
        }

        final RequestWrapper wrapper = wrapRequest(redirect);
        wrapper.setParams(params);

        final HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        final RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    return null;
}