httpclient-4.3.5

    
    rewriteRequestURI(request, route);
    
    HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost)params.getParameter("http.virtual-host");
    if ((virtualHost != null) && (virtualHost.getPort() == -1))
    {
      int port = route.getTargetHost().getPort();
      if (port != -1) {
        virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
      }
      if (log.isDebugEnabled()) {
        log.debug("Using virtual host" + virtualHost);
      }
    }
    HttpHost target = null;
    if (virtualHost != null) {
      target = virtualHost;
    } else if ((uri != null) && (uri.isAbsolute()) && (uri.getHost() != null)) {
      target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
      target = route.getTargetHost();
    }
    if (uri != null)
    {
      String userinfo = uri.getUserInfo();
      if (userinfo != null)
      {
        CredentialsProvider credsProvider = context.getCredentialsProvider();
        if (credsProvider == null)
        {
          credsProvider = new BasicCredentialsProvider();
          context.setCredentialsProvider(credsProvider);
        }
        credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
      }
    }
    context.setAttribute("http.target_host", target);
    context.setAttribute("http.route", route);
    context.setAttribute("http.request", request);
    
    httpProcessor.process(request, context);
    
    CloseableHttpResponse response = requestExecutor.execute(route, request, context, execAware);
    try
    {
      context.setAttribute("http.response", response);
      httpProcessor.process(response, context);
      return response;
    }
    catch (RuntimeException ex)
    {
      response.close();
      throw ex;
    }
    catch (IOException ex)
    {
      response.close();
      throw ex;
    }
    catch (HttpException ex)
    {
      response.close();
      throw ex;
    }
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.ProtocolExec
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import org.apache.http.HttpException;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.BackoffManager;
import org.apache.http.client.ConnectionBackoffStrategy;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.util.Args;

@Immutable
public class BackoffStrategyExec
  implements ClientExecChain
{
  private final ClientExecChain requestExecutor;
  private final ConnectionBackoffStrategy connectionBackoffStrategy;
  private final BackoffManager backoffManager;
  
  public BackoffStrategyExec(ClientExecChain requestExecutor, ConnectionBackoffStrategy connectionBackoffStrategy, BackoffManager backoffManager)
  {
    Args.notNull(requestExecutor, "HTTP client request executor");
    Args.notNull(connectionBackoffStrategy, "Connection backoff strategy");
    Args.notNull(backoffManager, "Backoff manager");
    this.requestExecutor = requestExecutor;
    this.connectionBackoffStrategy = connectionBackoffStrategy;
    this.backoffManager = backoffManager;
  }
  
  public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware)
    throws IOException, HttpException
  {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    CloseableHttpResponse out = null;
    try
    {
      out = requestExecutor.execute(route, request, context, execAware);
    }
    catch (Exception ex)
    {
      if (out != null) {
        out.close();
      }
      if (connectionBackoffStrategy.shouldBackoff(ex)) {
        backoffManager.backOff(route);
      }
      if ((ex instanceof RuntimeException)) {
        throw ((RuntimeException)ex);
      }
      if ((ex instanceof HttpException)) {
        throw ((HttpException)ex);
      }
      if ((ex instanceof IOException)) {
        throw ((IOException)ex);
      }
      throw new UndeclaredThrowableException(ex);
    }
    if (connectionBackoffStrategy.shouldBackoff(out)) {
      backoffManager.backOff(route);
    } else {
      backoffManager.probe(route);
    }
    return out;
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.BackoffStrategyExec
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.params.HttpParams;

@NotThreadSafe
class HttpResponseProxy
  implements CloseableHttpResponse
{
  private final HttpResponse original;
  private final ConnectionHolder connHolder;
  
  public HttpResponseProxy(HttpResponse original, ConnectionHolder connHolder)
  {
    this.original = original;
    this.connHolder = connHolder;
    ResponseEntityProxy.enchance(original, connHolder);
  }
  
  public void close()
    throws IOException
  {
    if (connHolder != null) {
      connHolder.abortConnection();
    }
  }
  
  public StatusLine getStatusLine()
  {
    return original.getStatusLine();
  }
  
  public void setStatusLine(StatusLine statusline)
  {
    original.setStatusLine(statusline);
  }
  
  public void setStatusLine(ProtocolVersion ver, int code)
  {
    original.setStatusLine(ver, code);
  }
  
  public void setStatusLine(ProtocolVersion ver, int code, String reason)
  {
    original.setStatusLine(ver, code, reason);
  }
  
  public void setStatusCode(int code)
    throws IllegalStateException
  {
    original.setStatusCode(code);
  }
  
  public void setReasonPhrase(String reason)
    throws IllegalStateException
  {
    original.setReasonPhrase(reason);
  }
  
  public HttpEntity getEntity()
  {
    return original.getEntity();
  }
  
  public void setEntity(HttpEntity entity)
  {
    original.setEntity(entity);
  }
  
  public Locale getLocale()
  {
    return original.getLocale();
  }
  
  public void setLocale(Locale loc)
  {
    original.setLocale(loc);
  }
  
  public ProtocolVersion getProtocolVersion()
  {
    return original.getProtocolVersion();
  }
  
  public boolean containsHeader(String name)
  {
    return original.containsHeader(name);
  }
  
  public Header[] getHeaders(String name)
  {
    return original.getHeaders(name);
  }
  
  public Header getFirstHeader(String name)
  {
    return original.getFirstHeader(name);
  }
  
  public Header getLastHeader(String name)
  {
    return original.getLastHeader(name);
  }
  
  public Header[] getAllHeaders()
  {
    return original.getAllHeaders();
  }
  
  public void addHeader(Header header)
  {
    original.addHeader(header);
  }
  
  public void addHeader(String name, String value)
  {
    original.addHeader(name, value);
  }
  
  public void setHeader(Header header)
  {
    original.setHeader(header);
  }
  
  public void setHeader(String name, String value)
  {
    original.setHeader(name, value);
  }
  
  public void setHeaders(Header[] headers)
  {
    original.setHeaders(headers);
  }
  
  public void removeHeader(Header header)
  {
    original.removeHeader(header);
  }
  
  public void removeHeaders(String name)
  {
    original.removeHeaders(name);
  }
  
  public HeaderIterator headerIterator()
  {
    return original.headerIterator();
  }
  
  public HeaderIterator headerIterator(String name)
  {
    return original.headerIterator(name);
  }
  
  @Deprecated
  public HttpParams getParams()
  {
    return original.getParams();
  }
  
  @Deprecated
  public void setParams(HttpParams params)
  {
    original.setParams(params);
  }
  
  public String toString()
  {
    StringBuilder sb = new StringBuilder("HttpResponseProxy{");
    sb.append(original);
    sb.append('}');
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.HttpResponseProxy
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AuthProtocolState;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthState;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.NonRepeatableRequestException;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.protocol.RequestClientConnControl;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.BasicRouteDirector;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRouteDirector;
import org.apache.http.conn.routing.RouteTracker;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.HttpAuthenticator;
import org.apache.http.impl.conn.ConnectionShutdownException;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.util.Args;
import org.apache.http.util.EntityUtils;

@Immutable
public class MainClientExec
  implements ClientExecChain
{
  private final Log log = LogFactory.getLog(getClass());
  private final HttpRequestExecutor requestExecutor;
  private final HttpClientConnectionManager connManager;
  private final ConnectionReuseStrategy reuseStrategy;
  private final ConnectionKeepAliveStrategy keepAliveStrategy;
  private final HttpProcessor proxyHttpProcessor;
  private final AuthenticationStrategy targetAuthStrategy;
  private final AuthenticationStrategy proxyAuthStrategy;
  private final HttpAuthenticator authenticator;
  private final UserTokenHandler userTokenHandler;
  private final HttpRouteDirector routeDirector;
  
  public MainClientExec(HttpRequestExecutor requestExecutor, HttpClientConnectionManager connManager, ConnectionReuseStrategy reuseStrategy, ConnectionKeepAliveStrategy keepAliveStrategy, AuthenticationStrategy targetAuthStrategy, AuthenticationStrategy proxyAuthStrategy, UserTokenHandler userTokenHandler)
  {
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(connManager, "Client connection manager");
    Args.notNull(reuseStrategy, "Connection reuse strategy");
    Args.notNull(keepAliveStrategy, "Connection keep alive strategy");
    Args.notNull(targetAuthStrategy, "Target authentication strategy");
    Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
    Args.notNull(userTokenHandler, "User token handler");
    authenticator = new HttpAuthenticator();
    proxyHttpProcessor = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestTargetHost(), new RequestClientConnControl() });
    
    routeDirector = new BasicRouteDirector();
    this.requestExecutor = requestExecutor;
    this.connManager = connManager;
    this.reuseStrategy = reuseStrategy;
    this.keepAliveStrategy = keepAliveStrategy;
    this.targetAuthStrategy = targetAuthStrategy;
    this.proxyAuthStrategy = proxyAuthStrategy;
    this.userTokenHandler = userTokenHandler;
  }
  
  public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, 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("http.auth.target-scope", targetAuthState);
    }
    AuthState proxyAuthState = context.getProxyAuthState();
    if (proxyAuthState == null)
    {
      proxyAuthState = new AuthState();
      context.setAttribute("http.auth.proxy-scope", proxyAuthState);
    }
    if ((request instanceof HttpEntityEnclosingRequest)) {
      RequestEntityProxy.enhance((HttpEntityEnclosingRequest)request);
    }
    Object userToken = context.getUserToken();
    
    ConnectionRequest connRequest = connManager.requestConnection(route, userToken);
    if (execAware != null)
    {
      if (execAware.isAborted())
      {
        connRequest.cancel();
        throw new RequestAbortedException("Request aborted");
      }
      execAware.setCancellable(connRequest);
    }
    RequestConfig config = context.getRequestConfig();
    HttpClientConnection managedConn;
    try
    {
      int timeout = config.getConnectionRequestTimeout();
      managedConn = connRequest.get(timeout > 0 ? timeout : 0L, TimeUnit.MILLISECONDS);
    }
    catch (InterruptedException interrupted)
    {
      Thread.currentThread().interrupt();
      throw new RequestAbortedException("Request aborted", interrupted);
    }
    catch (ExecutionException ex)
    {
      Throwable cause = ex.getCause();
      if (cause == null) {
        cause = ex;
      }
      throw new RequestAbortedException("Request execution failed", cause);
    }
    context.setAttribute("http.connection", managedConn);
    if (config.isStaleConnectionCheckEnabled()) {
      if (managedConn.isOpen())
      {
        log.debug("Stale connection check");
        if (managedConn.isStale())
        {
          log.debug("Stale connection detected");
          managedConn.close();
        }
      }
    }
    ConnectionHolder connHolder = new ConnectionHolder(log, connManager, managedConn);
    try
    {
      if (execAware != null) {
        execAware.setCancellable(connHolder);
      }
      HttpResponse response;
      for (int execCount = 1;; execCount++)
      {
        if ((execCount > 1) && (!RequestEntityProxy.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())
        {
          log.debug("Opening connection " + route);
          try
          {
            establishRoute(proxyAuthState, managedConn, route, request, context);
          }
          catch (TunnelRefusedException ex)
          {
            if (log.isDebugEnabled()) {
              log.debug(ex.getMessage());
            }
            HttpResponse response = ex.getResponse();
            break;
          }
        }
        int timeout = config.getSocketTimeout();
        if (timeout >= 0) {
          managedConn.setSocketTimeout(timeout);
        }
        if ((execAware != null) && (execAware.isAborted())) {
          throw new RequestAbortedException("Request aborted");
        }
        if (log.isDebugEnabled()) {
          log.debug("Executing request " + request.getRequestLine());
        }
        if (!request.containsHeader("Authorization"))
        {
          if (log.isDebugEnabled()) {
            log.debug("Target auth state: " + targetAuthState.getState());
          }
          authenticator.generateAuthResponse(request, targetAuthState, context);
        }
        if ((!request.containsHeader("Proxy-Authorization")) && (!route.isTunnelled()))
        {
          if (log.isDebugEnabled()) {
            log.debug("Proxy auth state: " + proxyAuthState.getState());
          }
          authenticator.generateAuthResponse(request, proxyAuthState, context);
        }
        response = requestExecutor.execute(request, managedConn, context);
        if (reuseStrategy.keepAlive(response, context))
        {
          long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
          if (log.isDebugEnabled())
          {
            String s;
            String s;
            if (duration > 0L) {
              s = "for " + duration + " " + TimeUnit.MILLISECONDS;
            } else {
              s = "indefinitely";
            }
            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)) {
          break;
        }
        HttpEntity entity = response.getEntity();
        if (connHolder.isReusable())
        {
          EntityUtils.consume(entity);
        }
        else
        {
          managedConn.close();
          if ((proxyAuthState.getState() == AuthProtocolState.SUCCESS) && (proxyAuthState.getAuthScheme() != null) && (proxyAuthState.getAuthScheme().isConnectionBased()))
          {
            log.debug("Resetting proxy auth state");
            proxyAuthState.reset();
          }
          if ((targetAuthState.getState() == AuthProtocolState.SUCCESS) && (targetAuthState.getAuthScheme() != null) && (targetAuthState.getAuthScheme().isConnectionBased()))
          {
            log.debug("Resetting target auth state");
            targetAuthState.reset();
          }
        }
        HttpRequest original = request.getOriginal();
        if (!original.containsHeader("Authorization")) {
          request.removeHeaders("Authorization");
        }
        if (!original.containsHeader("Proxy-Authorization")) {
          request.removeHeaders("Proxy-Authorization");
        }
      }
      if (userToken == null)
      {
        userToken = userTokenHandler.getUserToken(context);
        context.setAttribute("http.user-token", userToken);
      }
      if (userToken != null) {
        connHolder.setState(userToken);
      }
      HttpEntity entity = response.getEntity();
      if ((entity == null) || (!entity.isStreaming()))
      {
        connHolder.releaseConnection();
        return new HttpResponseProxy(response, null);
      }
      return new HttpResponseProxy(response, connHolder);
    }
    catch (ConnectionShutdownException ex)
    {
      InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
      
      ioex.initCause(ex);
      throw ioex;
    }
    catch (HttpException ex)
    {
      connHolder.abortConnection();
      throw ex;
    }
    catch (IOException ex)
    {
      connHolder.abortConnection();
      throw ex;
    }
    catch (RuntimeException ex)
    {
      connHolder.abortConnection();
      throw ex;
    }
  }
  
  void establishRoute(AuthState proxyAuthState, HttpClientConnection managedConn, HttpRoute route, HttpRequest request, HttpClientContext context)
    throws HttpException, IOException
  {
    RequestConfig config = context.getRequestConfig();
    int timeout = config.getConnectTimeout();
    RouteTracker tracker = new RouteTracker(route);
    int step;
    do
    {
      HttpRoute fact = tracker.toRoute();
      step = routeDirector.nextStep(route, fact);
      switch (step)
      {
      case 1: 
        connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
        
        tracker.connectTarget(route.isSecure());
        break;
      case 2: 
        connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
        
        HttpHost proxy = route.getProxyHost();
        tracker.connectProxy(proxy, false);
        break;
      case 3: 
        boolean secure = createTunnelToTarget(proxyAuthState, managedConn, route, request, context);
        
        log.debug("Tunnel to target created.");
        tracker.tunnelTarget(secure);
        break;
      case 4: 
        int hop = fact.getHopCount() - 1;
        boolean secure = createTunnelToProxy(route, hop, context);
        log.debug("Tunnel to proxy created.");
        tracker.tunnelProxy(route.getHopTarget(hop), secure);
        break;
      case 5: 
        connManager.upgrade(managedConn, route, context);
        tracker.layerProtocol(route.isSecure());
        break;
      case -1: 
        throw new HttpException("Unable to establish route: planned = " + route + "; current = " + fact);
      case 0: 
        connManager.routeComplete(managedConn, route, context);
        break;
      default: 
        throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector.");
      }
    } while (step > 0);
  }
  
  private boolean createTunnelToTarget(AuthState proxyAuthState, HttpClientConnection managedConn, HttpRoute route, HttpRequest request, HttpClientContext context)
    throws HttpException, IOException
  {
    RequestConfig config = context.getRequestConfig();
    int timeout = config.getConnectTimeout();
    
    HttpHost target = route.getTargetHost();
    HttpHost proxy = route.getProxyHost();
    HttpResponse response = null;
    
    String authority = target.toHostString();
    HttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion());
    
    requestExecutor.preProcess(connect, proxyHttpProcessor, context);
    while (response == null)
    {
      if (!managedConn.isOpen()) {
        connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
      }
      connect.removeHeaders("Proxy-Authorization");
      authenticator.generateAuthResponse(connect, proxyAuthState, context);
      
      response = requestExecutor.execute(connect, managedConn, context);
      
      int status = response.getStatusLine().getStatusCode();
      if (status < 200) {
        throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
      }
      if ((config.isAuthenticationEnabled()) && 
        (authenticator.isAuthenticationRequested(proxy, response, proxyAuthStrategy, proxyAuthState, context))) {
        if (authenticator.handleAuthChallenge(proxy, response, proxyAuthStrategy, proxyAuthState, context))
        {
          if (reuseStrategy.keepAlive(response, context))
          {
            log.debug("Connection kept alive");
            
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
          }
          else
          {
            managedConn.close();
          }
          response = null;
        }
      }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299)
    {
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        response.setEntity(new BufferedHttpEntity(entity));
      }
      managedConn.close();
      throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    return false;
  }
  
  private boolean createTunnelToProxy(HttpRoute route, int hop, HttpClientContext context)
    throws HttpException
  {
    throw new HttpException("Proxy chains are not supported.");
  }
  
  private boolean needAuthentication(AuthState targetAuthState, AuthState proxyAuthState, HttpRoute route, HttpResponse response, HttpClientContext context)
  {
    RequestConfig config = context.getRequestConfig();
    if (config.isAuthenticationEnabled())
    {
      HttpHost target = context.getTargetHost();
      if (target == null) {
        target = route.getTargetHost();
      }
      if (target.getPort() < 0) {
        target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(), target.getSchemeName());
      }
      boolean targetAuthRequested = authenticator.isAuthenticationRequested(target, response, targetAuthStrategy, targetAuthState, context);
      
      HttpHost proxy = route.getProxyHost();
      if (proxy == null) {
        proxy = route.getTargetHost();
      }
      boolean proxyAuthRequested = authenticator.isAuthenticationRequested(proxy, response, proxyAuthStrategy, proxyAuthState, context);
      if (targetAuthRequested) {
        return authenticator.handleAuthChallenge(target, response, targetAuthStrategy, targetAuthState, context);
      }
      if (proxyAuthRequested) {
        return authenticator.handleAuthChallenge(proxy, response, proxyAuthStrategy, proxyAuthState, context);
      }
    }
    return false;
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.MainClientExec
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.io.InterruptedIOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.util.Args;

@Immutable
public class ServiceUnavailableRetryExec
  implements ClientExecChain
{
  private final Log log = LogFactory.getLog(getClass());
  private final ClientExecChain requestExecutor;
  private final ServiceUnavailableRetryStrategy retryStrategy;
  
  public ServiceUnavailableRetryExec(ClientExecChain requestExecutor, ServiceUnavailableRetryStrategy retryStrategy)
  {
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(retryStrategy, "Retry strategy");
    this.requestExecutor = requestExecutor;
    this.retryStrategy = retryStrategy;
  }
  
  public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware)
    throws IOException, HttpException
  {
    Header[] origheaders = request.getAllHeaders();
    for (int c = 1;; c++)
    {
      CloseableHttpResponse response = requestExecutor.execute(route, request, context, execAware);
      try
      {
        if (retryStrategy.retryRequest(response, c, context))
        {
          response.close();
          long nextInterval = retryStrategy.getRetryInterval();
          if (nextInterval > 0L) {
            try
            {
              log.trace("Wait for " + nextInterval);
              Thread.sleep(nextInterval);
            }
            catch (InterruptedException e)
            {
              Thread.currentThread().interrupt();
              throw new InterruptedIOException();
            }
          }
          request.setHeaders(origheaders);
        }
        else
        {
          return response;
        }
      }
      catch (RuntimeException ex)
      {
        response.close();
        throw ex;
      }
    }
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.ServiceUnavailableRetryExec
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.NotThreadSafe;

@NotThreadSafe
class RequestEntityProxy
  implements HttpEntity
{
  private final HttpEntity original;
  
  static void enhance(HttpEntityEnclosingRequest request)
  {
    HttpEntity entity = request.getEntity();
    if ((entity != null) && (!entity.isRepeatable()) && (!isEnhanced(entity))) {
      request.setEntity(new RequestEntityProxy(entity));
    }
  }
  
  static boolean isEnhanced(HttpEntity entity)
  {
    return entity instanceof RequestEntityProxy;
  }
  
  static boolean isRepeatable(HttpRequest request)
  {
    if ((request instanceof HttpEntityEnclosingRequest))
    {
      HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
      if (entity != null)
      {
        if (isEnhanced(entity))
        {
          RequestEntityProxy proxy = (RequestEntityProxy)entity;
          if (!proxy.isConsumed()) {
            return true;
          }
        }
        return entity.isRepeatable();
      }
    }
    return true;
  }
  
  private boolean consumed = false;
  
  RequestEntityProxy(HttpEntity original)
  {
    this.original = original;
  }
  
  public HttpEntity getOriginal()
  {
    return original;
  }
  
  public boolean isConsumed()
  {
    return consumed;
  }
  
  public boolean isRepeatable()
  {
    return original.isRepeatable();
  }
  
  public boolean isChunked()
  {
    return original.isChunked();
  }
  
  public long getContentLength()
  {
    return original.getContentLength();
  }
  
  public Header getContentType()
  {
    return original.getContentType();
  }
  
  public Header getContentEncoding()
  {
    return original.getContentEncoding();
  }
  
  public InputStream getContent()
    throws IOException, IllegalStateException
  {
    return original.getContent();
  }
  
  public void writeTo(OutputStream outstream)
    throws IOException
  {
    consumed = true;
    original.writeTo(outstream);
  }
  
  public boolean isStreaming()
  {
    return original.isStreaming();
  }
  
  @Deprecated
  public void consumeContent()
    throws IOException
  {
    consumed = true;
    original.consumeContent();
  }
  
  public String toString()
  {
    StringBuilder sb = new StringBuilder("RequestEntityProxy{");
    sb.append(original);
    sb.append('}');
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.RequestEntityProxy
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.conn.EofSensorInputStream;
import org.apache.http.conn.EofSensorWatcher;
import org.apache.http.entity.HttpEntityWrapper;

@NotThreadSafe
class ResponseEntityProxy
  extends HttpEntityWrapper
  implements EofSensorWatcher
{
  private final ConnectionHolder connHolder;
  
  public static void enchance(HttpResponse response, ConnectionHolder connHolder)
  {
    HttpEntity entity = response.getEntity();
    if ((entity != null) && (entity.isStreaming()) && (connHolder != null)) {
      response.setEntity(new ResponseEntityProxy(entity, connHolder));
    }
  }
  
  ResponseEntityProxy(HttpEntity entity, ConnectionHolder connHolder)
  {
    super(entity);
    this.connHolder = connHolder;
  }
  
  private void cleanup()
  {
    if (connHolder != null) {
      connHolder.abortConnection();
    }
  }
  
  public void releaseConnection()
    throws IOException
  {
    if (connHolder != null) {
      try
      {
        if (connHolder.isReusable()) {
          connHolder.releaseConnection();
        }
      }
      finally
      {
        cleanup();
      }
    }
  }
  
  public boolean isRepeatable()
  {
    return false;
  }
  
  public InputStream getContent()
    throws IOException
  {
    return new EofSensorInputStream(wrappedEntity.getContent(), this);
  }
  
  @Deprecated
  public void consumeContent()
    throws IOException
  {
    releaseConnection();
  }
  
  public void writeTo(OutputStream outstream)
    throws IOException
  {
    try
    {
      wrappedEntity.writeTo(outstream);
      releaseConnection();
    }
    finally
    {
      cleanup();
    }
  }
  
  public boolean eofDetected(InputStream wrapped)
    throws IOException
  {
    try
    {
      wrapped.close();
      releaseConnection();
    }
    finally
    {
      cleanup();
    }
    return false;
  }
  
  public boolean streamClosed(InputStream wrapped)
    throws IOException
  {
    try
    {
      boolean open = (connHolder != null) && (!connHolder.isReleased());
      try
      {
        wrapped.close();
        releaseConnection();
      }
      catch (SocketException ex)
      {
        if (open) {
          throw ex;
        }
      }
    }
    finally
    {
      cleanup();
    }
    return false;
  }
  
  public boolean streamAbort(InputStream wrapped)
    throws IOException
  {
    cleanup();
    return false;
  }
  
  public String toString()
  {
    StringBuilder sb = new StringBuilder("ResponseEntityProxy{");
    sb.append(wrappedEntity);
    sb.append('}');
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.ResponseEntityProxy
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.ProtocolException;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthState;
import org.apache.http.client.RedirectException;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.util.Args;
import org.apache.http.util.EntityUtils;

@ThreadSafe
public class RedirectExec
  implements ClientExecChain
{
  private final Log log = LogFactory.getLog(getClass());
  private final ClientExecChain requestExecutor;
  private final RedirectStrategy redirectStrategy;
  private final HttpRoutePlanner routePlanner;
  
  public RedirectExec(ClientExecChain requestExecutor, HttpRoutePlanner routePlanner, RedirectStrategy redirectStrategy)
  {
    Args.notNull(requestExecutor, "HTTP client request executor");
    Args.notNull(routePlanner, "HTTP route planner");
    Args.notNull(redirectStrategy, "HTTP redirect strategy");
    this.requestExecutor = requestExecutor;
    this.routePlanner = routePlanner;
    this.redirectStrategy = redirectStrategy;
  }
  
  public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware)
    throws IOException, HttpException
  {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    
    List<URI> redirectLocations = context.getRedirectLocations();
    if (redirectLocations != null) {
      redirectLocations.clear();
    }
    RequestConfig config = context.getRequestConfig();
    int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
    HttpRoute currentRoute = route;
    HttpRequestWrapper currentRequest = request;
    int redirectCount = 0;
    for (;;)
    {
      CloseableHttpResponse response = requestExecutor.execute(currentRoute, currentRequest, context, execAware);
      try
      {
        if ((config.isRedirectsEnabled()) && (redirectStrategy.isRedirected(currentRequest, response, context)))
        {
          if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
          }
          redirectCount++;
          
          HttpRequest redirect = redirectStrategy.getRedirect(currentRequest, response, context);
          if (!redirect.headerIterator().hasNext())
          {
            HttpRequest original = request.getOriginal();
            redirect.setHeaders(original.getAllHeaders());
          }
          currentRequest = HttpRequestWrapper.wrap(redirect);
          if ((currentRequest instanceof HttpEntityEnclosingRequest)) {
            RequestEntityProxy.enhance((HttpEntityEnclosingRequest)currentRequest);
          }
          URI uri = currentRequest.getURI();
          HttpHost newTarget = URIUtils.extractHost(uri);
          if (newTarget == null) {
            throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
          }
          if (!currentRoute.getTargetHost().equals(newTarget))
          {
            AuthState targetAuthState = context.getTargetAuthState();
            if (targetAuthState != null)
            {
              log.debug("Resetting target auth state");
              targetAuthState.reset();
            }
            AuthState proxyAuthState = context.getProxyAuthState();
            if (proxyAuthState != null)
            {
              AuthScheme authScheme = proxyAuthState.getAuthScheme();
              if ((authScheme != null) && (authScheme.isConnectionBased()))
              {
                log.debug("Resetting proxy auth state");
                proxyAuthState.reset();
              }
            }
          }
          currentRoute = routePlanner.determineRoute(newTarget, currentRequest, context);
          if (log.isDebugEnabled()) {
            log.debug("Redirecting to '" + uri + "' via " + currentRoute);
          }
          EntityUtils.consume(response.getEntity());
          response.close();
        }
        else
        {
          return response;
        }
      }
      catch (RuntimeException ex)
      {
        response.close();
        throw ex;
      }
      catch (IOException ex)
      {
        response.close();
        throw ex;
      }
      catch (HttpException ex)
      {
        try
        {
          EntityUtils.consume(response.getEntity());
        }
        catch (IOException ioex)
        {
          log.debug("I/O error while releasing connection", ioex);
        }
        finally
        {
          response.close();
        }
        throw ex;
      }
    }
  }
}

/* Location:
 * Qualified Name:     org.apache.http.impl.execchain.RedirectExec
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.http.impl.execchain;

import java.io.InterruptedIOException;
import org.apache.http.annotation.Immutable;

@Immutable
public class RequestAbortedException
  extends InterruptedIOException
{
  private stat
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd