Example usage for org.apache.http.auth AuthState AuthState

List of usage examples for org.apache.http.auth AuthState AuthState

Introduction

In this page you can find the example usage for org.apache.http.auth AuthState AuthState.

Prototype

public AuthState() 

Source Link

Usage

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

/**
 * @since 4.1//from  www .  jav a 2  s.  com
 */
public StatiscicsLoggingRequestDirector(final Log log, final HttpRequestExecutor requestExec,
        final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat,
        final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan,
        final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler,
        final RedirectStrategy redirectStrategy, final AuthenticationHandler targetAuthHandler,
        final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler,
        final HttpParams params, HashMap<Integer, ConnectionStatistics> connectionStats) {

    if (log == null) {
        throw new IllegalArgumentException("Log may not be null.");
    }
    if (requestExec == null) {
        throw new IllegalArgumentException("Request executor may not be null.");
    }
    if (conman == null) {
        throw new IllegalArgumentException("Client connection manager may not be null.");
    }
    if (reustrat == null) {
        throw new IllegalArgumentException("Connection reuse strategy may not be null.");
    }
    if (kastrat == null) {
        throw new IllegalArgumentException("Connection keep alive strategy may not be null.");
    }
    if (rouplan == null) {
        throw new IllegalArgumentException("Route planner may not be null.");
    }
    if (httpProcessor == null) {
        throw new IllegalArgumentException("HTTP protocol processor may not be null.");
    }
    if (retryHandler == null) {
        throw new IllegalArgumentException("HTTP request retry handler may not be null.");
    }
    if (redirectStrategy == null) {
        throw new IllegalArgumentException("Redirect strategy may not be null.");
    }
    if (targetAuthHandler == null) {
        throw new IllegalArgumentException("Target authentication handler may not be null.");
    }
    if (proxyAuthHandler == null) {
        throw new IllegalArgumentException("Proxy authentication handler may not be null.");
    }
    if (userTokenHandler == null) {
        throw new IllegalArgumentException("User token handler may not be null.");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.log = log;
    this.requestExec = requestExec;
    this.connManager = conman;
    this.reuseStrategy = reustrat;
    this.keepAliveStrategy = kastrat;
    this.routePlanner = rouplan;
    this.httpProcessor = httpProcessor;
    this.retryHandler = retryHandler;
    this.redirectStrategy = redirectStrategy;
    this.targetAuthHandler = targetAuthHandler;
    this.proxyAuthHandler = proxyAuthHandler;
    this.userTokenHandler = userTokenHandler;
    this.params = params;

    this.managedConn = null;

    this.execCount = 0;
    this.redirectCount = 0;
    this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
    this.targetAuthState = new AuthState();
    this.proxyAuthState = new AuthState();

    this.connectionStats = connectionStats;
}

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

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

    AuthState targetAuthState = context.getTargetAuthState();
    if (targetAuthState == null) {
        targetAuthState = new AuthState();
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState);
    }/*from w  ww. java 2s.  co m*/
    AuthState proxyAuthState = context.getProxyAuthState();
    if (proxyAuthState == null) {
        proxyAuthState = new AuthState();
        context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);
    }

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

    Object userToken = context.getUserToken();

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

    final RequestConfig config = context.getRequestConfig();

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

    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

public DefaultAsyncRequestDirector(final Log log, final HttpAsyncRequestProducer requestProducer,
        final HttpAsyncResponseConsumer<T> responseConsumer, final HttpContext localContext,
        final ResultCallback<T> callback, final ClientAsyncConnectionManager connmgr,
        final HttpProcessor httppocessor, final HttpRoutePlanner routePlanner,
        final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepaliveStrategy,
        final RedirectStrategy redirectStrategy, final AuthenticationStrategy targetAuthStrategy,
        final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler,
        final HttpParams clientParams) {
    super();//  ww w .j  a  v a  2 s.  co  m
    this.log = log;
    this.requestProducer = requestProducer;
    this.responseConsumer = responseConsumer;
    this.localContext = localContext;
    this.resultCallback = callback;
    this.connmgr = connmgr;
    this.httppocessor = httppocessor;
    this.routePlanner = routePlanner;
    this.reuseStrategy = reuseStrategy;
    this.keepaliveStrategy = keepaliveStrategy;
    this.redirectStrategy = redirectStrategy;
    this.routeDirector = new BasicRouteDirector();
    this.targetAuthStrategy = targetAuthStrategy;
    this.proxyAuthStrategy = proxyAuthStrategy;
    this.userTokenHandler = userTokenHandler;
    this.targetAuthState = new AuthState();
    this.proxyAuthState = new AuthState();
    this.authenticator = new HttpAuthenticator(log);
    this.clientParams = clientParams;
    this.id = COUNTER.getAndIncrement();
}