List of usage examples for org.apache.http.client.protocol HttpClientContext getProxyAuthState
public AuthState getProxyAuthState()
From source file:org.artifactory.util.ProxyPreemptiveAuthInterceptor.java
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { HttpClientContext clientContext = HttpClientContext.adapt(context); AuthState proxyAuthState = clientContext.getProxyAuthState(); // If there's no auth scheme available yet, try to initialize it preemptively if (proxyAuthState.getAuthScheme() == null) { CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); RouteInfo route = clientContext.getHttpRoute(); if (route == null) { log.debug("No route found for {}", clientContext.getTargetHost()); return; }//from w ww. j a v a2s .c o m HttpHost proxyHost = route.getProxyHost(); if (proxyHost == null) { log.warn("No proxy host found in route {} for host {}", route, clientContext.getTargetHost()); return; } Credentials creds = credsProvider .getCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort())); if (creds == null) { log.info("No credentials found for proxy: " + proxyHost); return; } proxyAuthState.update(new BasicScheme(ChallengeState.PROXY), creds); } }
From source file:org.apache.http.client.protocol.RequestAuthCache.java
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final HttpClientContext clientContext = HttpClientContext.adapt(context); final AuthCache authCache = clientContext.getAuthCache(); if (authCache == null) { this.log.debug("Auth cache not set in the context"); return;/*from w w w . ja v a2s. c o m*/ } final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); if (credsProvider == null) { this.log.debug("Credentials provider not set in the context"); return; } final RouteInfo route = clientContext.getHttpRoute(); HttpHost target = clientContext.getTargetHost(); if (target.getPort() < 0) { target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(), target.getSchemeName()); } final AuthState targetState = clientContext.getTargetAuthState(); if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } final HttpHost proxy = route.getProxyHost(); final AuthState proxyState = clientContext.getProxyAuthState(); if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } }
From source file: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 w w.ja v a 2 s . c om 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.execchain.RedirectExec.java
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { redirectLocations.clear();/*from w ww. j a v a 2 s .c om*/ } final RequestConfig config = context.getRequestConfig(); final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; HttpRoute currentRoute = route; HttpRequestWrapper currentRequest = request; for (int redirectCount = 0;;) { final CloseableHttpResponse response = requestExecutor.execute(currentRoute, currentRequest, context, execAware); try { if (config.isRedirectsEnabled() && this.redirectStrategy.isRedirected(currentRequest, response, context)) { if (redirectCount >= maxRedirects) { throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded"); } redirectCount++; final HttpRequest redirect = this.redirectStrategy.getRedirect(currentRequest, response, context); if (!redirect.headerIterator().hasNext()) { final HttpRequest original = request.getOriginal(); redirect.setHeaders(original.getAllHeaders()); } currentRequest = HttpRequestWrapper.wrap(redirect); if (currentRequest instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) currentRequest); } final URI uri = currentRequest.getURI(); final HttpHost newTarget = URIUtils.extractHost(uri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } // Reset virtual host and auth states if redirecting to another host if (!currentRoute.getTargetHost().equals(newTarget)) { final AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState != null) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } final AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState != null) { final AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } } } currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); if (this.log.isDebugEnabled()) { this.log.debug("Redirecting to '" + uri + "' via " + currentRoute); } EntityUtils.consume(response.getEntity()); response.close(); } else { return response; } } catch (final RuntimeException ex) { response.close(); throw ex; } catch (final IOException ex) { response.close(); throw ex; } catch (final HttpException ex) { // Protocol exception related to a direct. // The underlying connection may still be salvaged. try { EntityUtils.consume(response.getEntity()); } catch (final IOException ioex) { this.log.debug("I/O error while releasing connection", ioex); } finally { response.close(); } throw ex; } } }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
@Override public HttpRequest generateRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws IOException, HttpException { final HttpRoute route = handler.getRoute(); handler.verifytRoute();/*from w w w . j ava 2 s. c o m*/ if (!handler.isRouteEstablished()) { int step; loop: do { final HttpRoute fact = handler.getActualRoute(); step = this.routeDirector.nextStep(route, fact); switch (step) { case HttpRouteDirector.CONNECT_TARGET: handler.onRouteToTarget(); break; case HttpRouteDirector.CONNECT_PROXY: handler.onRouteToProxy(); break; case HttpRouteDirector.TUNNEL_TARGET: if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Tunnel required"); } final HttpRequest connect = createConnectRequest(route, state); handler.setCurrentRequest(HttpRequestWrapper.wrap(connect)); break loop; case HttpRouteDirector.TUNNEL_PROXY: throw new HttpException("Proxy chains are not supported"); case HttpRouteDirector.LAYER_PROTOCOL: handler.onRouteUpgrade(); break; case HttpRouteDirector.UNREACHABLE: throw new HttpException( "Unable to establish route: " + "planned = " + route + "; current = " + fact); case HttpRouteDirector.COMPLETE: handler.onRouteComplete(); this.log.debug("Connection route established"); break; default: throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector."); } } while (step > HttpRouteDirector.COMPLETE); } final HttpClientContext localContext = state.getLocalContext(); HttpRequestWrapper currentRequest = handler.getCurrentRequest(); if (currentRequest == null) { currentRequest = state.getMainRequest(); handler.setCurrentRequest(currentRequest); } if (handler.isRouteEstablished()) { state.incrementExecCount(); if (state.getExecCount() > 1) { final HttpAsyncRequestProducer requestProducer = state.getRequestProducer(); if (!requestProducer.isRepeatable() && state.isRequestContentProduced()) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } requestProducer.resetRequest(); } if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Attempt " + state.getExecCount() + " to execute request"); } if (!currentRequest.containsHeader(AUTH.WWW_AUTH_RESP)) { final AuthState targetAuthState = localContext.getTargetAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, targetAuthState, localContext); } if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { final AuthState proxyAuthState = localContext.getProxyAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext); } } else { if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP)) { final AuthState proxyAuthState = localContext.getProxyAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext); } } final NHttpClientConnection managedConn = handler.getConnection(); localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); final RequestConfig config = localContext.getRequestConfig(); if (config.getSocketTimeout() > 0) { managedConn.setSocketTimeout(config.getSocketTimeout()); } return currentRequest; }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
@Override public void responseCompleted(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws IOException, HttpException { final HttpClientContext localContext = state.getLocalContext(); final HttpResponse currentResponse = handler.getCurrentResponse(); if (!handler.isRouteEstablished()) { final int status = currentResponse.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { handler.setCurrentResponse(null); return; }// w ww .j a v a 2 s.c o m } final boolean keepAlive = handler.manageConnectionPersistence(); if (!keepAlive) { handler.releaseConnection(); final AuthState proxyAuthState = localContext.getProxyAuthState(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state"); } proxyAuthState.reset(); } final AuthState targetAuthState = localContext.getTargetAuthState(); if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state"); } targetAuthState.reset(); } } Object userToken = localContext.getUserToken(); if (userToken == null) { userToken = this.userTokenHandler.getUserToken(localContext); localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (state.getFinalResponse() != null) { final HttpAsyncResponseConsumer<?> responseConsumer = state.getResponseConsumer(); responseConsumer.responseCompleted(localContext); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Response processed"); } handler.releaseConnection(); } else { if (state.getRedirect() != null) { final HttpUriRequest redirect = state.getRedirect(); final URI uri = redirect.getURI(); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Redirecting to '" + uri + "'"); } state.setRedirect(null); final HttpHost newTarget = URIUtils.extractHost(uri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } // Reset auth states if redirecting to another host final HttpRoute route = handler.getRoute(); if (!route.getTargetHost().equals(newTarget)) { final AuthState targetAuthState = localContext.getTargetAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state"); } targetAuthState.reset(); final AuthState proxyAuthState = localContext.getProxyAuthState(); final AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state"); } proxyAuthState.reset(); } } if (!redirect.headerIterator().hasNext()) { final HttpRequest original = state.getMainRequest().getOriginal(); redirect.setHeaders(original.getAllHeaders()); } final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(redirect); final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, newRequest, localContext); if (!route.equals(newRoute)) { handler.releaseConnection(); } handler.setRoute(newRoute); handler.setCurrentRequest(newRequest); state.setMainRequest(newRequest); prepareRequest(state, handler); } } handler.setCurrentResponse(null); }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
private boolean handleConnectResponse(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws HttpException { final HttpClientContext localContext = state.getLocalContext(); final RequestConfig config = localContext.getRequestConfig(); if (config.isAuthenticationEnabled()) { final CredentialsProvider credsProvider = localContext.getCredentialsProvider(); if (credsProvider != null) { final HttpRoute route = handler.getRoute(); final HttpHost proxy = route.getProxyHost(); final HttpResponse currentResponse = handler.getCurrentResponse(); final AuthState proxyAuthState = localContext.getProxyAuthState(); if (this.authenticator.isAuthenticationRequested(proxy, currentResponse, this.proxyAuthStrategy, proxyAuthState, localContext)) { return this.authenticator.handleAuthChallenge(proxy, currentResponse, this.proxyAuthStrategy, proxyAuthState, localContext); }//www . ja va2s. c o m } } return false; }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
private boolean needAuthentication(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws HttpException { final HttpClientContext localContext = state.getLocalContext(); final CredentialsProvider credsProvider = localContext.getCredentialsProvider(); if (credsProvider != null) { final HttpRoute route = handler.getRoute(); final HttpResponse currentResponse = handler.getCurrentResponse(); HttpHost target = localContext.getTargetHost(); if (target == null) { target = route.getTargetHost(); }/*from w w w. j a v a2 s . c o m*/ if (target.getPort() < 0) { target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(), target.getSchemeName()); } final AuthState targetAuthState = localContext.getTargetAuthState(); final AuthState proxyAuthState = localContext.getProxyAuthState(); final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target, currentResponse, this.targetAuthStrategy, targetAuthState, localContext); 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, currentResponse, this.proxyAuthStrategy, proxyAuthState, localContext); if (targetAuthRequested) { return this.authenticator.handleAuthChallenge(target, currentResponse, this.targetAuthStrategy, targetAuthState, localContext); } if (proxyAuthRequested) { return this.authenticator.handleAuthChallenge(proxy, currentResponse, this.proxyAuthStrategy, proxyAuthState, localContext); } } return false; }