httpclient-4.3.5

unt;
  private int redirectCount;
  private final int maxRedirects;
  private HttpHost virtualHost;
  
  @Deprecated
  public DefaultRequestDirector(HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler userTokenHandler, HttpParams params)
  {
    this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, new DefaultRedirectStrategyAdaptor(redirectHandler), new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params);
  }
  
  @Deprecated
  public DefaultRequestDirector(Log log, HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectStrategy redirectStrategy, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler userTokenHandler, HttpParams params)
  {
    this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params);
  }
  
  public DefaultRequestDirector(Log log, HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectStrategy redirectStrategy, AuthenticationStrategy targetAuthStrategy, AuthenticationStrategy proxyAuthStrategy, UserTokenHandler userTokenHandler, HttpParams params)
  {
    Args.notNull(log, "Log");
    Args.notNull(requestExec, "Request executor");
    Args.notNull(conman, "Client connection manager");
    Args.notNull(reustrat, "Connection reuse strategy");
    Args.notNull(kastrat, "Connection keep alive strategy");
    Args.notNull(rouplan, "Route planner");
    Args.notNull(httpProcessor, "HTTP protocol processor");
    Args.notNull(retryHandler, "HTTP request retry handler");
    Args.notNull(redirectStrategy, "Redirect strategy");
    Args.notNull(targetAuthStrategy, "Target authentication strategy");
    Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
    Args.notNull(userTokenHandler, "User token handler");
    Args.notNull(params, "HTTP parameters");
    this.log = log;
    authenticator = new HttpAuthenticator(log);
    this.requestExec = requestExec;
    connManager = conman;
    reuseStrategy = reustrat;
    keepAliveStrategy = kastrat;
    routePlanner = rouplan;
    this.httpProcessor = httpProcessor;
    this.retryHandler = retryHandler;
    this.redirectStrategy = redirectStrategy;
    this.targetAuthStrategy = targetAuthStrategy;
    this.proxyAuthStrategy = proxyAuthStrategy;
    this.userTokenHandler = userTokenHandler;
    this.params = params;
    if ((redirectStrategy instanceof DefaultRedirectStrategyAdaptor)) {
      redirectHandler = ((DefaultRedirectStrategyAdaptor)redirectStrategy).getHandler();
    } else {
      redirectHandler = null;
    }
    if ((targetAuthStrategy instanceof AuthenticationStrategyAdaptor)) {
      targetAuthHandler = ((AuthenticationStrategyAdaptor)targetAuthStrategy).getHandler();
    } else {
      targetAuthHandler = null;
    }
    if ((proxyAuthStrategy instanceof AuthenticationStrategyAdaptor)) {
      proxyAuthHandler = ((AuthenticationStrategyAdaptor)proxyAuthStrategy).getHandler();
    } else {
      proxyAuthHandler = null;
    }
    managedConn = null;
    
    execCount = 0;
    redirectCount = 0;
    targetAuthState = new AuthState();
    proxyAuthState = new AuthState();
    maxRedirects = this.params.getIntParameter("http.protocol.max-redirects", 100);
  }
  
  private RequestWrapper wrapRequest(HttpRequest request)
    throws ProtocolException
  {
    if ((request instanceof HttpEntityEnclosingRequest)) {
      return new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest)request);
    }
    return new RequestWrapper(request);
  }
  
  protected void rewriteRequestURI(RequestWrapper request, HttpRoute route)
    throws ProtocolException
  {
    try
    {
      URI uri = request.getURI();
      if ((route.getProxyHost() != null) && (!route.isTunnelled()))
      {
        if (!uri.isAbsolute())
        {
          HttpHost target = route.getTargetHost();
          uri = URIUtils.rewriteURI(uri, target, true);
        }
        else
        {
          uri = URIUtils.rewriteURI(uri);
        }
      }
      else if (uri.isAbsolute()) {
        uri = URIUtils.rewriteURI(uri, null, true);
      } else {
        uri = URIUtils.rewriteURI(uri);
      }
      request.setURI(uri);
    }
    catch (URISyntaxException ex)
    {
      throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
  }
  
  public HttpResponse execute(HttpHost targetHost, HttpRequest request, HttpContext context)
    throws HttpException, IOException
  {
    context.setAttribute("http.auth.target-scope", targetAuthState);
    context.setAttribute("http.auth.proxy-scope", proxyAuthState);
    
    HttpHost target = targetHost;
    
    HttpRequest orig = request;
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);
    
    virtualHost = ((HttpHost)origWrapper.getParams().getParameter("http.virtual-host"));
    if ((virtualHost != null) && (virtualHost.getPort() == -1))
    {
      HttpHost host = target != null ? target : origRoute.getTargetHost();
      int port = host.getPort();
      if (port != -1) {
        virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
      }
    }
    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);
    
    boolean reuse = false;
    boolean done = false;
    try
    {
      HttpResponse response = null;
      while (!done)
      {
        RequestWrapper wrapper = roureq.getRequest();
        HttpRoute route = roureq.getRoute();
        response = null;
        
        Object userToken = context.getAttribute("http.user-token");
        if (managedConn == null)
        {
          ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
          if ((orig instanceof AbortableHttpRequest)) {
            ((AbortableHttpRequest)orig).setConnectionRequest(connRequest);
          }
          long timeout = HttpClientParams.getConnectionManagerTimeout(params);
          try
          {
            managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
          }
          catch (InterruptedException interrupted)
          {
            Thread.currentThread().interrupt();
            throw new InterruptedIOException();
          }
          if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
            if (managedConn.isOpen())
            {
              log.debug("Stale connection check");
              if (managedConn.isStale())
              {
                log.debug("Stale connection detected");
                managedConn.close();
              }
            }
          }
        }
        if ((orig instanceof AbortableHttpRequest)) {
          ((AbortableHttpRequest)orig).setReleaseTrigger(managedConn);
        }
        try
        {
          tryConnect(roureq, context);
        }
        catch (TunnelRefusedException ex)
        {
          if (log.isDebugEnabled()) {
            log.debug(ex.getMessage());
          }
          response = ex.getResponse();
          break;
        }
        String userinfo = wrapper.getURI().getUserInfo();
        if (userinfo != null) {
          targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
        }
        if (virtualHost != null)
        {
          target = virtualHost;
        }
        else
        {
          URI requestURI = wrapper.getURI();
          if (requestURI.isAbsolute()) {
            target = URIUtils.extractHost(requestURI);
          }
        }
        if (target == null) {
          target = route.getTargetHost();
        }
        wrapper.resetHeaders();
        
        rewriteRequestURI(wrapper, route);
        
        context.setAttribute("http.target_host", target);
        context.setAttribute("http.route", route);
        context.setAttribute("http.connection", managedConn);
        
        requestExec.preProcess(wrapper, httpProcessor, context);
        
        response = tryExecute(roureq, context);
        if (response != null)
        {
          response.setParams(params);
          requestExec.postProcess(response, httpProcessor, context);
          
          reuse = reuseStrategy.keepAlive(response, context);
          if (reuse)
          {
            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);
            }
            managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
          }
          RoutedRequest followup = handleResponse(roureq, response, context);
          if (followup == null)
          {
            done = true;
          }
          else
          {
            if (reuse)
            {
              HttpEntity entity = response.getEntity();
              EntityUtils.consume(entity);
              
              managedConn.markReusable();
            }
            else
            {
              managedConn.close();
              if ((proxyAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0) && (proxyAuthState.getAuthScheme() != null) && (proxyAuthState.getAuthScheme().isConnectionBased()))
              {
                log.debug("Resetting proxy auth state");
                proxyAuthState.reset();
              }
              if ((targetAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0) && (targetAuthState.getAuthScheme() != null) && (targetAuthState.getAuthScheme().isConnectionBased()))
              {
                log.debug("Resetting target auth state");
                targetAuthState.reset();
              }
            }
            if (!followup.getRoute().equals(roureq.getRoute())) {
              releaseConnection();
            }
            roureq = followup;
          }
          if (managedConn != null)
          {
            if (userToken == null)
            {
              userToken = userTokenHandler.getUserToken(context);
              context.setAttribute("http.user-token", userToken);
            }
            if (userToken != null) {
              managedConn.setState(userToken);
            }
          }
        }
      }
      if ((response == null) || (response.getEntity() == null) || (!response.getEntity().isStreaming()))
      {
        if (reuse) {
          managedConn.markReusable();
        }
        releaseConnection();
      }
      else
      {
        HttpEntity entity = response.getEntity();
        entity = new BasicManagedEntity(entity, managedConn, reuse);
        response.setEntity(entity);
      }
      return response;
    }
    catch (ConnectionShutdownException ex)
    {
      InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
      
      ioex.initCause(ex);
      throw ioex;
    }
    catch (HttpException ex)
    {
      abortConnection();
      throw ex;
    }
    catch (IOException ex)
    {
      abortConnection();
      throw ex;
    }
    catch (RuntimeException ex)
    {
      abortConnection();
      throw ex;
    }
  }
  
  private void tryConnect(RoutedRequest req, HttpContext context)
    throws HttpException, IOException
  {
    HttpRoute route = req.getRoute();
    HttpRequest wrapper = req.getRequest();
    
    int connectCount = 0;
    for (;;)
    {
      context.setAttribute("http.request", wrapper);
      
      connectCount++;
      try
      {
        if (!managedConn.isOpen()) {
          managedConn.open(route, context, params);
        } else {
          managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
        }
        establishRoute(route, context);
      }
      catch (IOException ex)
      {
        try
        {
          managedConn.close();
        }
        catch (IOException ignore) {}
        if (retryHandler.retryRequest(ex, connectCount, context))
        {
          if (log.isInfoEnabled())
          {
            log.info("I/O exception (" + ex.getClass().getName() + ") caught when connecting to " + route + ": " + ex.getMessage());
            if (log.isDebugEnabled()) {
              log.debug(ex.getMessage(), ex);
            }
            log.info("Retrying connect to " + route);
          }
        }
        else {
          throw ex;
        }
      }
    }
  }
  
  private HttpResponse tryExecute(RoutedRequest req, HttpContext context)
    throws HttpException, IOException
  {
    RequestWrapper wrapper = req.getRequest();
    HttpRoute route = req.getRoute();
    HttpResponse response = null;
    
    Exception retryReason = null;
    for (;;)
    {
      execCount += 1;
      
      wrapper.incrementExecCount();
      if (!wrapper.isRepeatable())
      {
        log.debug("Cannot retry non-repeatable request");
        if (retryReason != null) {
          throw new NonRepeatableRequestException("Cannot retry request with a non-repeatable request entity.  The cause lists the reason the original request failed.", retryReason);
        }
        throw new NonRepeatableRequestException("Cannot retry request with a non-repeatable request entity.");
      }
      try
      {
        if (!managedConn.isOpen()) {
          if (!route.isTunnelled())
          {
            log.debug("Reopening the direct connection.");
            managedConn.open(route, context, params);
          }
          else
          {
            log.debug("Proxied connection. Need to start over.");
            break;
          }
        }
        if (log.isDebugEnabled()) {
          log.debug("Attempt " + execCount + " to execute request");
        }
        response = requestExec.execute(wrapper, managedConn, context);
      }
      catch (IOException ex)
      {
        log.debug("Closing the connection.");
        try
        {
          managedConn.close();
        }
        catch (IOException ignore) {}
        if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context))
        {
          if (log.isInfoEnabled()) {
            log.info("I/O exception (" + ex.getClass().getName() + ") caught when processing request to " + route + ": " + ex.getMessage());
          }
          if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
          }
          if (log.isInfoEnabled()) {
            log.info("Retrying request to " + route);
          }
          retryReason = ex;
        }
        else
        {
          if ((ex instanceof NoHttpResponseException))
          {
            NoHttpResponseException updatedex = new NoHttpResponseException(route.getTargetHost().toHostString() + " failed to respond");
            
            updatedex.setStackTrace(ex.getStackTrace());
            throw updatedex;
          }
          throw ex;
        }
      }
    }
    return response;
  }
  
  protected void releaseConnection()
  {
    try
    {
      managedConn.releaseConnection();
    }
    catch (IOException ignored)
    {
      log.debug("IOException releasing connection", ignored);
    }
    managedConn = null;
  }
  
  protected HttpRoute determineRoute(HttpHost targetHost, HttpRequest request, HttpContext context)
    throws HttpException
  {
    return routePlanner.determineRoute(targetHost != null ? targetHost : (HttpHost)request.getParams().getParameter("http.default-host"), request, context);
  }
  
  protected void establishRoute(HttpRoute route, HttpContext context)
    throws HttpException, IOException
  {
    HttpRouteDirector rowdy = new BasicRouteDirector();
    int step;
    do
    {
      HttpRoute fact = managedConn.getRoute();
      step = rowdy.nextStep(route, fact);
      switch (step)
      {
      case 1: 
      case 2: 
        managedConn.open(route, context, params);
        break;
      case 3: 
        boolean secure = createTunnelToTarget(route, context);
        log.debug("Tunnel to target created.");
        managedConn.tunnelTarget(secure, params);
        break;
      case 4: 
        int hop = fact.getHopCount() - 1;
        boolean secure = createTunnelToProxy(route, hop, context);
        log.debug("Tunnel to proxy created.");
        managedConn.tunnelProxy(route.getHopTarget(hop), secure, params);
        
        break;
      case 5: 
        managedConn.layerProtocol(context, params);
        break;
      case -1: 
        throw new HttpException("Unable to establish route: planned = " + route + "; current = " + fact);
      case 0: 
        break;
      default: 
        throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector.");
      }
    } while (step > 0);
  }
  
  protected boolean createTunnelToTarget(HttpRoute route, HttpContext context)
    throws HttpException, IOException
  {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    for (;;)
    {
      if (!managedConn.isOpen()) {
        managedConn.open(route, context, params);
      }
      HttpRequest connect = createConnectRequest(route, context);
      connect.setParams(params);
      
      context.setAttribute("http.target_host", target);
      context.setAttribute("http.route", route);
      context.setAttribute("http.proxy_host", proxy);
      context.setAttribute("http.connection", managedConn);
      context.setAttribute("http.request", connect);
      
      requestExec.preProcess(connect, httpProcessor, context);
      
      response = requestExec.execute(connect, managedConn, context);
      
      response.setParams(params);
      requestExec.postProcess(response, httpProcessor, context);
      
      int status = response.getStatusLine().getStatusCode();
      if (status < 200) {
        throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
      }
      if (HttpClientParams.isAuthenticating(params))
      {
        if (!authenticator.isAuthenticationRequested(proxy, response, proxyAuthStrategy, proxyAuthState, context)) {
          break;
        }
        if (!authenticator.authenticate(proxy, response, proxyAuthStrategy, proxyAuthState, context)) {
          break;
        }
        if (reuseStrategy.keepAlive(response, context))
        {
          log.debug("Connection kept alive");
          
          HttpEntity entity = response.getEntity();
          EntityUtils.consume(entity);
        }
        else
        {
          managedConn.close();
        }
      }
    }
    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);
    }
    managedConn.markReusable();
    
    return false;
  }
  
  protected boolean createTunnelToProxy(HttpRoute route, int hop, HttpContext context)
    throws HttpException, IOException
  {
    throw new HttpException("Proxy chains are not supported.");
  }
  
  protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context)
  {
    HttpHost target = route.getTargetHost();
    
    String host = target.getHostName();
    int port = target.getPort();
    if (port < 0)
    {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(target.getSchemeName());
      
      port = scheme.getDefaultPort();
    }
    StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));
    
    String authority = buffer.toString();
    ProtocolVersion ver = HttpProtocolParams.getVersion(params);
    HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);
    
    return req;
  }
  
  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.isAuthenticating(params))
    {
      HttpHost target = (HttpHost)context.getAttribute("http.target_host");
      if (target == null) {
        target = route.getTargetHost();
      }
      if (target.getPort() < 0)
      {
        Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
        target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), 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) && 
        (authenticator.authenticate(target, response, targetAuthStrategy, targetAuthState, context))) {
        return roureq;
      }
      if ((proxyAuthRequested) && 
        (authenticator.authenticate(proxy, response, proxyAuthStrategy, proxyAuthState, context))) {
        return roureq;
      }
    }
    if ((HttpClientParams.isRedirecting(params)) && (redirectStrategy.isRedirected(request, response, context)))
    {
      if (redirectCount >= maxRedirects) {
        throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
      }
      redirectCount += 1;
      
      virtualHost = null;
      
      HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
      HttpRequest orig = request.getOriginal();
      redirect.setHeaders(orig.getAllHeaders());
      
      URI uri = redirect.getURI();
      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))
      {
        log.debug("Resetting target auth state");
        targetAuthState.reset();
        AuthScheme authScheme = proxyAuthState.getAuthScheme();
        if ((authScheme != null) && (authScheme.isConnectionBased()))
        {
          log.debug("Resetting proxy auth state");
          proxyAuthState.reset();
        }
      }
      RequestWrapper wrapper = wrapRequest(redirect);
      wrapper.setParams(params);
      
      HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
      RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
      if (log.isDebugEnabled()) {
        log.debug("Redirecting to '" + uri + "' via " + newRoute);
      }
      return newRequest;
    }
    return null;
  }
  
  private void abortConnection()
  {
    ManagedClientConnection mcc = managedConn;
    if (mcc != null)
    {
      managedConn = null;
      try
      {
        mcc.abortConnection();
      }
      catch (IOException ex)
      {
        if (log.isDebugEnabled()) {
          log.debug(ex.getMessage(), ex);
        }
      }
      try
      {
        mcc.releaseConnection();
      }
      catch (IOException ignored)
      {
        log.debug("Error releasing connection", ignored);
      }
    }
  }
}

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

import java.util.concurrent.atomic.AtomicLong;

public final class FutureRequestExecutionMetrics
{
  private final AtomicLong activeConnections = new AtomicLong();
  private final AtomicLong scheduledConnections = new AtomicLong();
  private final DurationCounter successfulConnections = new DurationCounter();
  private final DurationCounter failedConnections = new DurationCounter();
  private final DurationCounter requests = new DurationCounter();
  private final DurationCounter tasks = new DurationCounter();
  
  AtomicLong getActiveConnections()
  {
    return activeConnections;
  }
  
  AtomicLong getScheduledConnections()
  {
    return scheduledConnections;
  }
  
  DurationCounter getSuccessfulConnections()
  {
    return successfulConnections;
  }
  
  DurationCounter getFailedConnections()
  {
    return failedConnections;
  }
  
  DurationCounter getRequests()
  {
    return requests;
  }
  
  DurationCounter getTasks()
  {
    return tasks;
  }
  
  public long getActiveConnectionCount()
  {
    return activeConnections.get();
  }
  
  public long getScheduledConnectionCount()
  {
    return scheduledConnections.get();
  }
  
  public long getSuccessfulConnectionCount()
  {
    return successfulConnections.count();
  }
  
  public long getSuccessfulConnectionAverageDuration()
  {
    return successfulConnections.averageDuration();
  }
  
  public long getFailedConnectionCount()
  {
    return failedConnections.count();
  }
  
  public long getFailedConnectionAverageDuration()
  {
    return failedConnections.averageDuration();
  }
  
  public long getRequestCount()
  {
    return requests.count();
  }
  
  public long getRequestAverageDuration()
  {
    return requests.averageDuration();
  }
  
  public long getTaskCount()
  {
    return tasks.count();
  }
  
  public long getTaskAverageDuration()
  {
    return tasks.averageDuration();
  }
  
  public String toString()
  {
    StringBuilder builder = new StringBuilder();
    builder.append("[activeConnections=").append(activeConnections).append(", scheduledConnections=").append(scheduledConnections).append(", successfulConnections=").append(successfulConnections).append(", failedConnections=").append(failedConnections).append(", requests=").append(requests).append(", tasks=").append(tasks).append("]");
    
    return builder.toString();
  }
  
  static class DurationCounter
  {
    private final AtomicLong count = new AtomicLong(0L);
    private final AtomicLong cumulativeDuration = new AtomicLong(0L);
    
    public void increment(long startTime)
    {
      count.incrementAndGet();
      cumulativeDuration.addAndGet(System.currentTimeMillis() - startTime);
    }
    
    public long count()
    {
      return count.get();
    }
    
    public long averageDuration()
    {
      long counter = count.get();
      return counter > 0L ? cumulativeDuration.get() / counter : 0L;
    }
    
    public String toString()
    {
      StringBuilder builder = new StringBuilder();
      builder.append("[count=").append(count()).append(", averageDuration=").append(averageDuration()).append("]");
      
      return builder.toString();
    }
  }
}

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

import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.SchemeRegistry;

class InternalHttpClient$1
  implements ClientConnectionManager
{
  InternalHttpClient$1(InternalHttpClient paramInternalHttpClient) {}
  
  public void shutdown()
  {
    InternalHttpClient.access$000(this$0).shutdown();
  }
  
  public ClientConnectionRequest requestConnection(HttpRoute route, Object state)
  {
    throw new UnsupportedOperationException();
  }
  
  public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit)
  {
    throw new UnsupportedOperationException();
  }
  
  public SchemeRegistry getSchemeRegistry()
  {
    throw new UnsupportedOperationException();
  }
  
  public void closeIdleConnections(long idletime, TimeUnit tunit)
  {
    InternalHttpClient.access$000(this$0).closeIdleConnections(idletime, tunit);
  }
  
  public void closeExpiredConnections()
  {
    InternalHttpClient.access$000(this$0).closeExpiredConnections();
  }
}

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;

class EntityEnclosingRequestWrapper$EntityWrapper
  extends HttpEntityWrapper
{
  EntityEnclosingRequestWrapper$EntityWrapper(EntityEnclosingRequestWrapper paramEntityEnclosingRequestWrapper, HttpEntity entity)
  {
    super(entity);
  }
  
  public void consumeContent()
    throws IOException
  {
    EntityEnclosingRequestWrapper.access$002(this$0, true);
    super.consumeContent();
  }
  
  public InputStream getContent()
    throws IOException
  {
    EntityEnclosingRequestWrapper.access$002(this$0, true);
    return super.getContent();
  }
  
  public void writeTo(OutputStream outstream)
    throws IOException
  {
    EntityEnclosingRequestWrapper.access$002(this$0, true);
    super.writeTo(outstream);
  }
}

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

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.apache.http.util.EntityUtils;

@ThreadSafe
public abstract class CloseableHttpClient
  implements HttpClient, Closeable
{
  private final Log log = LogFactory.getLog(getClass());
  
  protected abstract CloseableHttpResponse doExecute(HttpHost paramHttpHost, HttpRequest paramHttpRequest, HttpContext paramHttpContext)
    throws IOException, ClientProtocolException;
  
  public CloseableHttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
    throws IOException, ClientProtocolException
  {
    return doExecute(target, request, context);
  }
  
  public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context)
    throws IOException, ClientProtocolException
  {
    Args.notNull(request, "HTTP request");
    return doExecute(determineTarget(request), request, context);
  }
  
  private static HttpHost determineTarget(HttpUriRequest request)
    throws ClientProtocolException
  {
    HttpHost target = null;
    
    URI requestURI = request.getURI();
    if (requestURI.isAbsolute())
    {
      target = URIUtils.extractHost(requestURI);
      if (target == null) {
        throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI);
      }
    }
    return target;
  }
  
  public CloseableHttpResponse execute(HttpUriRequest request)
    throws IOException, ClientProtocolException
  {
    return execute(request, (HttpContext)null);
  }
  
  public CloseableHttpResponse execute(HttpHost target, HttpRequest request)
    throws IOException, ClientProtocolException
  {
    return doExecute(target, request, (HttpContext)null);
  }
  
  public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
    throws IOException, ClientProtocolException
  {
    return (T)execute(request, responseHandler, null);
  }
  
  public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
    throws IOException, ClientProtocolException
  {
    HttpHost target = determineTarget(request);
    return (T)execute(target, request, responseHandler, context);
  }
  
  public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
    throws IOException, ClientProtocolException
  {
    return (T)execute(target, request, responseHandler, null);
  }
  
  public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
    throws IOException, ClientProtocolException
  {
    Args.notNull(responseHandler, "Response handler");
    
    HttpResponse response = execute(target, request, context);
    T result;
    try
    {
      result = responseHandler.handleResponse(response);
    }
    catch (Exception t)
    {
      HttpEntity entity = response.getEntity();
      try
      {
        EntityUtils.consume(entity);
      }
      catch (Exception t2)
      {
        log.warn("Error consuming content after an exception.", t2);
      }
      if ((t instanceof RuntimeException)) {
        throw ((RuntimeException)t);
      }
      if ((t instanceof IOException)) {
        throw ((IOException)t);
      }
      throw new UndeclaredThrowableException(t);
    }
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    return result;
  }
}

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

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.FormattedHeader;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AuthOption;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.client.AuthCache;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.apache.http.util.CharArrayBuffer;

@Immutable
abstract class AuthenticationStrategyImpl
  implements AuthenticationStrategy
{
  private final Log log = LogFactory.getLog(getClass());
  private static final List<String> DEFAULT_SCHEME_PRIORITY = Collections.unmodifiableList(Arrays.asList(new String[] { "negotiate", "Kerberos", "NTLM", "Digest", "Basic" }));
  private final int challengeCode;
  private final String headerName;
  
  AuthenticationStrategyImpl(int challengeCode, String headerName)
  {
    this.challengeCode = challengeCode;
    this.headerName = headerName;
  }
  
  public boolean isAuthenticationRequested(HttpHost authhost, HttpResponse response, HttpContext context)
  {
    Args.notNull(response, "HTTP response");
    int status = response.getStatusLine().getStatusCode();
    return status == challengeCode;
  }
  
  public Map<String, Header> getChallenges(HttpHost authhost, HttpResponse response, HttpContext context)
    throws MalformedChallengeException
  {
    Args.notNull(response, "HTTP response");
    Header[] headers = response.getHeaders(headerName);
    Map<String, Header> map = new HashMap(headers.length);
    for (Header header : headers)
    {
      int pos;
      CharArrayBuffer buffer;
      int pos;
      if ((header instanceof FormattedHeader))
      {
        CharArrayBuffer buffer = ((FormattedHeader)header).getBuffer();
        pos = ((FormattedHeader)header).getValuePos();
      }
      else
      {
        String s = header.getValue();
        if (s == null) {
          throw new MalformedChallengeException("Header value is null");
        }
        buffer = new CharArrayBuffer(s.length());
        buffer.append(s);
        pos = 0;
      }
      while ((pos < buffer.length()) && (HTTP.isWhitespace(buffer.charAt(pos)))) {
        pos++;
      }
      int beginIndex = pos;
      while ((pos < buffer.length()) && (!HTTP.isWhitespace(buffer.charAt(pos)))) {
        pos++;
      }
      int endIndex = pos;
      String s = buffer.substring(beginIndex, endIndex);
      map.put(s.toLowerCase(Locale.ENGLISH), header);
    }
    return map;
  }
  
  abstract Collection<String> getPreferredAuthSchemes(RequestConfig paramRequestConfig);
  
  public Queue<AuthOption> select(Map<String, Header> challenges, HttpHost authhost, HttpResponse response, HttpContext context)
    throws MalformedChallengeException
  {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    
    Queue<AuthOption> options = new LinkedList();
    Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null)
    {
      log.debug("Auth scheme registry not set in the context");
      return options;
    }
    CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null)
    {
      log.debug("Credentials provider not set in the context");
      return options;
    }
    RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
      authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (log.isDebugEnabled()) {
      log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }
    for (String id : authPrefs)
    {
      Header challenge = (Header)challenges.get(id.toLowerCase(Locale.ENGLISH));
      if (challenge != null)
      {
        AuthSchemeProvider authSchemeProvider = (AuthSchemeProvider)registry.lookup(id);
        if (authSchemeProvider == null)
        {
          if (log.isWarnEnabled()) {
            log.warn("Authentication scheme " + id + " not supported");
          }
        }
       
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