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

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

Introduction

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

Prototype

public static boolean isRedirecting(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();//from w ww  .j  ava  2s . c o  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 av a 2s  .com*/
        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:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Despite its name, this method performs two tasks:
 *    1)sending the SOAP response to the WSP is the final step of the delegated
 *      SAML authentication//from   w  w w . ja  v a  2  s  . com
 *    2)when this succeeds, the WSP returns the resource originally requested,
 *      so this also means that upon return from this method, the DelegatedSAMLAuthenticationState object
 *      will contain a String representation of the requested resource.
 *       
 * @param samlSession   SAML session representing this user and a SAML assertion
 *                      for the WSP on behalf of this user.
 * @param authnState      DelegatedSAMLAuthenticationState object that tracks the state of the authentication
 * @return HttpResponse from the WSP after authentication.  Depending on the HTTP method used, this will
 *                      either include an HTTP 302 redirect to the originally requested resource or a result
 *                      of submitting form data in case if the initial request was from HTTP POST.
 */
private HttpResponse sendSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    HttpPost method = new HttpPost(authnState.getResponseConsumerURL());
    method.setHeader("Content-Type", SAMLConstants.HTTP_HEADER_PAOS_CONTENT_TYPE);

    try {
        StringEntity postData = new StringEntity(authnState.getModifiedSOAPResponse(), HTTP.UTF_8);
        method.setEntity(postData);

        // Disable redirection
        HttpParams params = method.getParams();
        boolean redirecting = HttpClientParams.isRedirecting(params);
        if (redirecting) {
            HttpClientParams.setRedirecting(params, false);
            method.setParams(params);
        }
        HttpResponse response = samlSession.getHttpClient().execute(method);

        // Not sure whether this is necessary.  Just restoring HttpParams to
        // their original state.
        if (redirecting) {
            HttpClientParams.setRedirecting(params, true);
            method.setParams(params);
        }
        return response;
    } catch (Exception ex) {
        // There is nothing that can be done about this exception other than to log it
        // Exception must be caught and not rethrown to allow normal processing to continue
        logger.error("Exception caught when trying to retrieve the resource.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught while sending the delegated authentication assertion to the service provider.",
                ex);
    }
}

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   ww w  . j a v a2 s .  c  om*/
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.ja 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

/**
 * 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 va2 s .c  om
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;
}

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

/**
 * Analyzes a response to check need for a followup.
 * /*from   ww w.  java 2s  .  c  o  m*/
 * @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} if the response should be returned as is
 * @throws HttpException
 *             in case of a problem
 * @throws IOException
 *             in case of an IO problem
 */
protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    String something = new String();
    String somethingElse = "";
    List<Something> somethingList = null;
    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 == 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:org.apache.http.impl.client.StatiscicsLoggingRequestDirector.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 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.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());

        URI uri = redirect.getURI();
        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.nio.client.DefaultAsyncRequestDirector.java

private RoutedRequest handleResponse() throws HttpException {
    RoutedRequest followup = null;/*from   w w w .  ja v a  2  s.  c  o  m*/
    if (HttpClientParams.isAuthenticating(this.params)) {
        final CredentialsProvider credsProvider = (CredentialsProvider) this.localContext
                .getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null) {
            followup = handleTargetChallenge(credsProvider);
            if (followup != null) {
                return followup;
            }
            followup = handleProxyChallenge(credsProvider);
            if (followup != null) {
                return followup;
            }
        }
    }
    if (HttpClientParams.isRedirecting(this.params)) {
        followup = handleRedirect();
        if (followup != null) {
            return followup;
        }
    }
    return null;
}