httpclient-cache-4.1.2

16:36:38.446 INFO  jd.cli.Main - Decompiling httpclient-cache-4.1.2.jar
package org.apache.http.impl.client.cache;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.Resource;

@Immutable
class ResourceReference
  extends PhantomReference<HttpCacheEntry>
{
  private final Resource resource;
  
  public ResourceReference(HttpCacheEntry entry, ReferenceQueue<HttpCacheEntry> q)
  {
    super(entry, q);
    if (entry.getResource() == null) {
      throw new IllegalArgumentException("Resource may not be null");
    }
    resource = entry.getResource();
  }
  
  public Resource getResource()
  {
    return resource;
  }
  
  public int hashCode()
  {
    return resource.hashCode();
  }
  
  public boolean equals(Object obj)
  {
    return resource.equals(obj);
  }
}

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

import java.util.Date;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.Resource;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;

@Immutable
class CacheValidityPolicy
{
  public static final long MAX_AGE = 2147483648L;
  
  public long getCurrentAgeSecs(HttpCacheEntry entry, Date now)
  {
    return getCorrectedInitialAgeSecs(entry) + getResidentTimeSecs(entry, now);
  }
  
  public long getFreshnessLifetimeSecs(HttpCacheEntry entry)
  {
    long maxage = getMaxAge(entry);
    if (maxage > -1L) {
      return maxage;
    }
    Date dateValue = getDateValue(entry);
    if (dateValue == null) {
      return 0L;
    }
    Date expiry = getExpirationDate(entry);
    if (expiry == null) {
      return 0L;
    }
    long diff = expiry.getTime() - dateValue.getTime();
    return diff / 1000L;
  }
  
  public boolean isResponseFresh(HttpCacheEntry entry, Date now)
  {
    return getCurrentAgeSecs(entry, now) < getFreshnessLifetimeSecs(entry);
  }
  
  public boolean isResponseHeuristicallyFresh(HttpCacheEntry entry, Date now, float coefficient, long defaultLifetime)
  {
    return getCurrentAgeSecs(entry, now) < getHeuristicFreshnessLifetimeSecs(entry, coefficient, defaultLifetime);
  }
  
  public long getHeuristicFreshnessLifetimeSecs(HttpCacheEntry entry, float coefficient, long defaultLifetime)
  {
    Date dateValue = getDateValue(entry);
    Date lastModifiedValue = getLastModifiedValue(entry);
    if ((dateValue != null) && (lastModifiedValue != null))
    {
      long diff = dateValue.getTime() - lastModifiedValue.getTime();
      if (diff < 0L) {
        return 0L;
      }
      return (coefficient * (float)(diff / 1000L));
    }
    return defaultLifetime;
  }
  
  public boolean isRevalidatable(HttpCacheEntry entry)
  {
    return (entry.getFirstHeader("ETag") != null) || (entry.getFirstHeader("Last-Modified") != null);
  }
  
  public boolean mustRevalidate(HttpCacheEntry entry)
  {
    return hasCacheControlDirective(entry, "must-revalidate");
  }
  
  public boolean proxyRevalidate(HttpCacheEntry entry)
  {
    return hasCacheControlDirective(entry, "proxy-revalidate");
  }
  
  public boolean mayReturnStaleWhileRevalidating(HttpCacheEntry entry, Date now)
  {
    for (Header h : entry.getHeaders("Cache-Control")) {
      for (HeaderElement elt : h.getElements()) {
        if ("stale-while-revalidate".equalsIgnoreCase(elt.getName())) {
          try
          {
            int allowedStalenessLifetime = Integer.parseInt(elt.getValue());
            if (getStalenessSecs(entry, now) <= allowedStalenessLifetime) {
              return true;
            }
          }
          catch (NumberFormatException nfe) {}
        }
      }
    }
    return false;
  }
  
  public boolean mayReturnStaleIfError(HttpRequest request, HttpCacheEntry entry, Date now)
  {
    long stalenessSecs = getStalenessSecs(entry, now);
    return (mayReturnStaleIfError(request.getHeaders("Cache-Control"), stalenessSecs)) || (mayReturnStaleIfError(entry.getHeaders("Cache-Control"), stalenessSecs));
  }
  
  private boolean mayReturnStaleIfError(Header[] headers, long stalenessSecs)
  {
    boolean result = false;
    for (Header h : headers) {
      for (HeaderElement elt : h.getElements()) {
        if ("stale-if-error".equals(elt.getName())) {
          try
          {
            int staleIfErrorSecs = Integer.parseInt(elt.getValue());
            if (stalenessSecs <= staleIfErrorSecs)
            {
              result = true;
              break;
            }
          }
          catch (NumberFormatException nfe) {}
        }
      }
    }
    return result;
  }
  
  protected Date getDateValue(HttpCacheEntry entry)
  {
    Header dateHdr = entry.getFirstHeader("Date");
    if (dateHdr == null) {
      return null;
    }
    try
    {
      return DateUtils.parseDate(dateHdr.getValue());
    }
    catch (DateParseException dpe) {}
    return null;
  }
  
  protected Date getLastModifiedValue(HttpCacheEntry entry)
  {
    Header dateHdr = entry.getFirstHeader("Last-Modified");
    if (dateHdr == null) {
      return null;
    }
    try
    {
      return DateUtils.parseDate(dateHdr.getValue());
    }
    catch (DateParseException dpe) {}
    return null;
  }
  
  protected long getContentLengthValue(HttpCacheEntry entry)
  {
    Header cl = entry.getFirstHeader("Content-Length");
    if (cl == null) {
      return -1L;
    }
    try
    {
      return Long.parseLong(cl.getValue());
    }
    catch (NumberFormatException ex) {}
    return -1L;
  }
  
  protected boolean hasContentLengthHeader(HttpCacheEntry entry)
  {
    return null != entry.getFirstHeader("Content-Length");
  }
  
  protected boolean contentLengthHeaderMatchesActualLength(HttpCacheEntry entry)
  {
    return (!hasContentLengthHeader(entry)) || (getContentLengthValue(entry) == entry.getResource().length());
  }
  
  protected long getApparentAgeSecs(HttpCacheEntry entry)
  {
    Date dateValue = getDateValue(entry);
    if (dateValue == null) {
      return 2147483648L;
    }
    long diff = entry.getResponseDate().getTime() - dateValue.getTime();
    if (diff < 0L) {
      return 0L;
    }
    return diff / 1000L;
  }
  
  protected long getAgeValue(HttpCacheEntry entry)
  {
    long ageValue = 0L;
    for (Header hdr : entry.getHeaders("Age"))
    {
      long hdrAge;
      try
      {
        hdrAge = Long.parseLong(hdr.getValue());
        if (hdrAge < 0L) {
          hdrAge = 2147483648L;
        }
      }
      catch (NumberFormatException nfe)
      {
        hdrAge = 2147483648L;
      }
      ageValue = hdrAge > ageValue ? hdrAge : ageValue;
    }
    return ageValue;
  }
  
  protected long getCorrectedReceivedAgeSecs(HttpCacheEntry entry)
  {
    long apparentAge = getApparentAgeSecs(entry);
    long ageValue = getAgeValue(entry);
    return apparentAge > ageValue ? apparentAge : ageValue;
  }
  
  protected long getResponseDelaySecs(HttpCacheEntry entry)
  {
    long diff = entry.getResponseDate().getTime() - entry.getRequestDate().getTime();
    return diff / 1000L;
  }
  
  protected long getCorrectedInitialAgeSecs(HttpCacheEntry entry)
  {
    return getCorrectedReceivedAgeSecs(entry) + getResponseDelaySecs(entry);
  }
  
  protected Date getCurrentDate()
  {
    return new Date();
  }
  
  protected long getResidentTimeSecs(HttpCacheEntry entry, Date now)
  {
    long diff = now.getTime() - entry.getResponseDate().getTime();
    return diff / 1000L;
  }
  
  protected long getMaxAge(HttpCacheEntry entry)
  {
    long maxage = -1L;
    for (Header hdr : entry.getHeaders("Cache-Control")) {
      for (HeaderElement elt : hdr.getElements()) {
        if (("max-age".equals(elt.getName())) || ("s-maxage".equals(elt.getName()))) {
          try
          {
            long currMaxAge = Long.parseLong(elt.getValue());
            if ((maxage == -1L) || (currMaxAge < maxage)) {
              maxage = currMaxAge;
            }
          }
          catch (NumberFormatException nfe)
          {
            maxage = 0L;
          }
        }
      }
    }
    return maxage;
  }
  
  protected Date getExpirationDate(HttpCacheEntry entry)
  {
    Header expiresHeader = entry.getFirstHeader("Expires");
    if (expiresHeader == null) {
      return null;
    }
    try
    {
      return DateUtils.parseDate(expiresHeader.getValue());
    }
    catch (DateParseException dpe) {}
    return null;
  }
  
  public boolean hasCacheControlDirective(HttpCacheEntry entry, String directive)
  {
    for (Header h : entry.getHeaders("Cache-Control")) {
      for (HeaderElement elt : h.getElements()) {
        if (directive.equalsIgnoreCase(elt.getName())) {
          return true;
        }
      }
    }
    return false;
  }
  
  public long getStalenessSecs(HttpCacheEntry entry, Date now)
  {
    long age = getCurrentAgeSecs(entry, now);
    long freshness = getFreshnessLifetimeSecs(entry);
    if (age <= freshness) {
      return 0L;
    }
    return age - freshness;
  }
}

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

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.cache.Resource;

@Immutable
public class HeapResource
  implements Resource
{
  private static final long serialVersionUID = -2078599905620463394L;
  private final byte[] b;
  
  public HeapResource(byte[] b)
  {
    this.b = b;
  }
  
  byte[] getByteArray()
  {
    return b;
  }
  
  public InputStream getInputStream()
  {
    return new ByteArrayInputStream(b);
  }
  
  public long length()
  {
    return b.length;
  }
  
  public void dispose() {}
}

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

import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;

@Immutable
class CachedResponseSuitabilityChecker
{
  private final Log log = LogFactory.getLog(getClass());
  private final boolean sharedCache;
  private final boolean useHeuristicCaching;
  private final float heuristicCoefficient;
  private final long heuristicDefaultLifetime;
  private final CacheValidityPolicy validityStrategy;
  
  CachedResponseSuitabilityChecker(CacheValidityPolicy validityStrategy, CacheConfig config)
  {
    this.validityStrategy = validityStrategy;
    sharedCache = config.isSharedCache();
    useHeuristicCaching = config.isHeuristicCachingEnabled();
    heuristicCoefficient = config.getHeuristicCoefficient();
    heuristicDefaultLifetime = config.getHeuristicDefaultLifetime();
  }
  
  CachedResponseSuitabilityChecker(CacheConfig config)
  {
    this(new CacheValidityPolicy(), config);
  }
  
  private boolean isFreshEnough(HttpCacheEntry entry, HttpRequest request, Date now)
  {
    if (validityStrategy.isResponseFresh(entry, now)) {
      return true;
    }
    if ((useHeuristicCaching) && (validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime))) {
      return true;
    }
    if (originInsistsOnFreshness(entry)) {
      return false;
    }
    long maxstale = getMaxStale(request);
    if (maxstale == -1L) {
      return false;
    }
    return maxstale > validityStrategy.getStalenessSecs(entry, now);
  }
  
  private boolean originInsistsOnFreshness(HttpCacheEntry entry)
  {
    if (validityStrategy.mustRevalidate(entry)) {
      return true;
    }
    if (!sharedCache) {
      return false;
    }
    return (validityStrategy.proxyRevalidate(entry)) || (validityStrategy.hasCacheControlDirective(entry, "s-maxage"));
  }
  
  private long getMaxStale(HttpRequest request)
  {
    long maxstale = -1L;
    for (Header h : request.getHeaders("Cache-Control")) {
      for (HeaderElement elt : h.getElements()) {
        if ("max-stale".equals(elt.getName())) {
          if (((elt.getValue() == null) || ("".equals(elt.getValue().trim()))) && (maxstale == -1L)) {
            maxstale = Long.MAX_VALUE;
          } else {
            try
            {
              long val = Long.parseLong(elt.getValue());
              if (val < 0L) {
                val = 0L;
              }
              if ((maxstale == -1L) || (val < maxstale)) {
                maxstale = val;
              }
            }
            catch (NumberFormatException nfe)
            {
              maxstale = 0L;
            }
          }
        }
      }
    }
    return maxstale;
  }
  
  public boolean canCachedResponseBeUsed(HttpHost host, HttpRequest request, HttpCacheEntry entry, Date now)
  {
    if (!isFreshEnough(entry, request, now))
    {
      log.trace("Cache entry was not fresh enough");
      return false;
    }
    if (!validityStrategy.contentLengthHeaderMatchesActualLength(entry))
    {
      log.debug("Cache entry Content-Length and header information do not match");
      return false;
    }
    if (hasUnsupportedConditionalHeaders(request))
    {
      log.debug("Request contained conditional headers we don't handle");
      return false;
    }
    if ((isConditional(request)) && (!allConditionalsMatch(request, entry, now))) {
      return false;
    }
    for (Header ccHdr : request.getHeaders("Cache-Control")) {
      for (HeaderElement elt : ccHdr.getElements())
      {
        if ("no-cache".equals(elt.getName()))
        {
          log.trace("Response contained NO CACHE directive, cache was not suitable");
          return false;
        }
        if ("no-store".equals(elt.getName()))
        {
          log.trace("Response contained NO STORE directive, cache was not suitable");
          return false;
        }
        if ("max-age".equals(elt.getName())) {
          try
          {
            int maxage = Integer.parseInt(elt.getValue());
            if (validityStrategy.getCurrentAgeSecs(entry, now) > maxage)
            {
              log.trace("Response from cache was NOT suitable due to max age");
              return false;
            }
          }
          catch (NumberFormatException ex)
          {
            log.debug("Response from cache was malformed" + ex.getMessage());
            return false;
          }
        }
        if ("max-stale".equals(elt.getName())) {
          try
          {
            int maxstale = Integer.parseInt(elt.getValue());
            if (validityStrategy.getFreshnessLifetimeSecs(entry) > maxstale)
            {
              log.trace("Response from cache was not suitable due to Max stale freshness");
              return false;
            }
          }
          catch (NumberFormatException ex)
          {
            log.debug("Response from cache was malformed: " + ex.getMessage());
            return false;
          }
        }
        if ("min-fresh".equals(elt.getName())) {
          try
          {
            long minfresh = Long.parseLong(elt.getValue());
            if (minfresh < 0L) {
              return false;
            }
            long age = validityStrategy.getCurrentAgeSecs(entry, now);
            long freshness = validityStrategy.getFreshnessLifetimeSecs(entry);
            if (freshness - age < minfresh)
            {
              log.trace("Response from cache was not suitable due to min fresh freshness requirement");
              
              return false;
            }
          }
          catch (NumberFormatException ex)
          {
            log.debug("Response from cache was malformed: " + ex.getMessage());
            return false;
          }
        }
      }
    }
    log.trace("Response from cache was suitable");
    return true;
  }
  
  public boolean isConditional(HttpRequest request)
  {
    return (hasSupportedEtagValidator(request)) || (hasSupportedLastModifiedValidator(request));
  }
  
  public boolean allConditionalsMatch(HttpRequest request, HttpCacheEntry entry, Date now)
  {
    boolean hasEtagValidator = hasSupportedEtagValidator(request);
    boolean hasLastModifiedValidator = hasSupportedLastModifiedValidator(request);
    
    boolean etagValidatorMatches = hasEtagValidator ? etagValidatorMatches(request, entry) : false;
    boolean lastModifiedValidatorMatches = hasLastModifiedValidator ? lastModifiedValidatorMatches(request, entry, now) : false;
    if ((hasEtagValidator) && (hasLastModifiedValidator) && ((!etagValidatorMatches) || (!lastModifiedValidatorMatches))) {
      return false;
    }
    if ((hasEtagValidator) && (!etagValidatorMatches)) {
      return false;
    }
    if ((hasLastModifiedValidator) && (!lastModifiedValidatorMatches)) {
      return false;
    }
    return true;
  }
  
  private boolean hasUnsupportedConditionalHeaders(HttpRequest request)
  {
    return (request.getFirstHeader("If-Range") != null) || (request.getFirstHeader("If-Match") != null) || (hasValidDateField(request, "If-Unmodified-Since"));
  }
  
  private boolean hasSupportedEtagValidator(HttpRequest request)
  {
    return request.containsHeader("If-None-Match");
  }
  
  private boolean hasSupportedLastModifiedValidator(HttpRequest request)
  {
    return hasValidDateField(request, "If-Modified-Since");
  }
  
  private boolean etagValidatorMatches(HttpRequest request, HttpCacheEntry entry)
  {
    Header etagHeader = entry.getFirstHeader("ETag");
    String etag = etagHeader != null ? etagHeader.getValue() : null;
    Header[] ifNoneMatch = request.getHeaders("If-None-Match");
    if (ifNoneMatch != null) {
      for (Header h : ifNoneMatch) {
        for (HeaderElement elt : h.getElements())
        {
          String reqEtag = elt.toString();
          if ((("*".equals(reqEtag)) && (etag != null)) || (reqEtag.equals(etag))) {
            return true;
          }
        }
      }
    }
    return false;
  }
  
  private boolean lastModifiedValidatorMatches(HttpRequest request, HttpCacheEntry entry, Date now)
  {
    Header lastModifiedHeader = entry.getFirstHeader("Last-Modified");
    Date lastModified = null;
    try
    {
      if (lastModifiedHeader != null) {
        lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
      }
    }
    catch (DateParseException dpe) {}
    if (lastModified == null) {
      return false;
    }
    for (Header h : request.getHeaders("If-Modified-Since")) {
      try
      {
        Date ifModifiedSince = DateUtils.parseDate(h.getValue());
        if ((ifModifiedSince.after(now)) || (lastModified.after(ifModifiedSince))) {
          return false;
        }
      }
      catch (DateParseException dpe) {}
    }
    return true;
  }
  
  private boolean hasValidDateField(HttpRequest request, String headerName)
  {
    for (Header h : request.getHeaders(headerName)) {
      try
      {
        DateUtils.parseDate(h.getValue());
        return true;
      }
      catch (DateParseException dpe) {}
    }
    return false;
  }
}

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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;

class WarningValue
{
  private int offs;
  private int init_offs;
  private String src;
  private int warnCode;
  private String warnAgent;
  private String warnText;
  private Date warnDate;
  private static final String TOPLABEL = "\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?";
  private static final String DOMAINLABEL = "\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?";
  private static final String HOSTNAME = "(\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?\\.)*\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?\\.?";
  private static final String IPV4ADDRESS = "\\d+\\.\\d+\\.\\d+\\.\\d+";
  private static final String HOST = "((\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?\\.)*\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?\\.?)|(\\d+\\.\\d+\\.\\d+\\.\\d+)";
  private static final String PORT = "\\d*";
  private static final String HOSTPORT = "(((\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?\\.)*\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?\\.?)|(\\d+\\.\\d+\\.\\d+\\.\\d+))(\\:\\d*)?";
  
  WarningValue(String s)
  {
    this(s, 0);
  }
  
  WarningValue(String s, int offs)
  {
    this.offs = (init_offs = offs);
    src = s;
    consumeWarnValue();
  }
  
  public static WarningValue[] getWarningValues(Header h)
  {
    List<WarningValue> out = new ArrayList();
    String src = h.getValue();
    int offs = 0;
    for (;;)
    {
      if (offs < src.length()) {
        try
        {
          WarningValue wv = new WarningValue(src, offs);
          out.add(wv);
          offs = offs;
        }
        catch (IllegalArgumentException e)
        {
          int nextComma = src.indexOf(',', offs);
          if (nextComma != -1) {
            offs = nextComma + 1;
          }
        }
      }
    }
    WarningValue[] wvs = new WarningValue[0];
    return (WarningValue[])out.toArray(wvs);
  }
  
  protected void consumeLinearWhitespace()
  {
    while (offs < src.length())
    {
      switch (src.charAt(offs))
      {
      case '\r': 
        if ((offs + 2 >= src.length()) || (src.charAt(offs + 1) != '\n') || ((src.charAt(offs + 2) != ' ') && (src.charAt(offs + 2) != '\t'))) {
          return;
        }
        offs += 2;
        break;
      case '\t': 
      case ' ': 
        break;
      default: 
        return;
      }
      offs += 1;
    }
  }
  
  private boolean isChar(char c)
  {
    int i = c;
    return (i >= 0) && (i <= 127);
  }
  
  private boolean isControl(char c)
  {
    int i = c;
    return (i == 127) || ((i >= 0) && (i <= 31));
  }
  
  private boolean isSeparator(char c)
  {
    return (c == '(') || (c == ')') || (c == '<') || (c == '>') || (c == '@') || (c == ',') || (c == ';') || (c == ':') || (c == '\\') || (c == '"') || (c == '/') || (c == '[') || (c == ']') || (c == '?') || (c == '=') || (c == '{') || (c == '}') || (c == ' ') || (c == '\t');
  }
  
  protected void consumeToken()
  {
    if (!isTokenChar(src.charAt(offs))) {
      parseError();
    }
    while ((offs < src.length()) && 
      (isTokenChar(src.charAt(offs)))) {
      offs += 1;
    }
  }
  
  private boolean isTokenChar(char c)
  {
    return (isChar(c)) && (!isControl(c)) && (!isSeparator(c));
  }
  
  private static final Pattern HOSTPORT_PATTERN = Pattern.compile("(((\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?\\.)*\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?\\.?)|(\\d+\\.\\d+\\.\\d+\\.\\d+))(\\:\\d*)?");
  private static final String MONTH = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
  private static final String WEEKDAY = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
  private static final String WKDAY = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
  private static final String TIME = "\\d{2}:\\d{2}:\\d{2}";
  private static final String DATE3 = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( |\\d)\\d";
  private static final String DATE2 = "\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{2}";
  private static final String DATE1 = "\\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4}";
  private static final String ASCTIME_DATE = "(Mon|Tue|Wed|Thu|Fri|Sat|Sun) ((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( |\\d)\\d) (\\d{2}:\\d{2}:\\d{2}) \\d{4}";
  private static final String RFC850_DATE = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{2}) (\\d{2}:\\d{2}:\\d{2}) GMT";
  private static final String RFC1123_DATE = "(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4}) (\\d{2}:\\d{2}:\\d{2}) GMT";
  private static final String HTTP_DATE = "((Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{2}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Mon|Tue|Wed|Thu|Fri|Sat|Sun) ((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( |\\d)\\d) (\\d{2}:\\d{2}:\\d{2}) \\d{4})";
  private static final String WARN_DATE = "\"(((Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{2}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Mon|Tue|Wed|Thu|Fri|Sat|Sun) ((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( |\\d)\\d) (\\d{2}:\\d{2}:\\d{2}) \\d{4}))\"";
  
  protected void consumeHostPort()
  {
    Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs));
    if (!m.find()) {
      parseError();
    }
    if (m.start() != 0) {
      parseError();
    }
    offs += m.end();
  }
  
  protected void consumeWarnAgent()
  {
    int curr_offs = offs;
    try
    {
      consumeHostPort();
      warnAgent = src.substring(curr_offs, offs);
      consumeCharacter(' ');
      return;
    }
    catch (IllegalArgumentException e)
    {
      offs = curr_offs;
      
      consumeToken();
      warnAgent = src.substring(curr_offs, offs);
      consumeCharacter(' ');
    }
  }
  
  protected void consumeQuotedString()
  {
    if (src.charAt(offs) != '"') {
      parseError();
    }
    offs += 1;
    boolean foundEnd = false;
    while ((offs < src.length()) && (!foundEnd))
    {
      char c = src.charAt(offs);
      if ((offs + 1 < src.length()) && (c == '\\') && (isChar(src.charAt(offs + 1))))
      {
        offs += 2;
      }
      else if (c == '"')
      {
        foundEnd = true;
        offs += 1;
      }
      else if ((c != '"') && (!isControl(c)))
      {
        offs += 1;
      }
      else
      {
        parseError();
      }
    }
    if (!foundEnd) {
      parseError();
    }
  }
  
  protected void consumeWarnText()
  {
    int curr = offs;
    consumeQuotedString();
    warnText = src.substring(curr, offs);
  }
  
  private static final Pattern WARN_DATE_PATTERN = Pattern.compile("\"(((Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{2}) (\\d{2}:\\d{2}:\\d{2}) GMT)|((Mon|Tue|Wed|Thu|Fri|Sat|Sun) ((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( |\\d)\\d) (\\d{2}:\\d{2}:\\d{2}) \\d{4}))\"");
  
  protected void consumeWarnDate()
  {
    int curr = offs;
    Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
    if (!m.lookingAt()) {
      parseError();
    }
    offs += m.end();
    try
    {
      warnDate = DateUtils.parseDate(src.substring(curr + 1, offs - 1));
    }
    catch (DateParseException e)
    {
      throw new IllegalStateException("couldn't parse a parseable date");
    }
  }
  
  protected void consumeWarnValue()
  {
    consumeLinearWhitespace();
    consumeWarnCode();
    consumeWarnAgent();
    consumeWarnText();
    if ((offs + 1 < src.length()) && (src.charAt(offs) == ' ') && (src.charAt(offs + 1) == '"'))
    {
      consumeCharacter(' ');
      consumeWarnDate();
    }
    consumeLinearWhitespace();
    if (offs != src.length()) {
      consumeCharacter(',');
    }
  }
  
  protected void consumeCharacter(char c)
  {
    if ((offs + 1 > src.length()) || (c != src.charAt(offs))) {
      parseError();
    }
    offs += 1;
  }
  
  protected void consumeWarnCode()
  {
    if ((offs + 4 > src.length()) || (!Character.isDigit(src.charAt(offs))) || (!Character.isDigit(src.charAt(offs + 1))) || (!Character.isDigit(src.charAt(offs + 2))) || (src.charAt(offs + 3) != ' ')) {
      parseError();
    }
    warnCode = Integer.parseInt(src.substring(offs, offs + 3));
    offs += 4;
  }
  
  private void parseError()
  {
    String s = src.substring(init_offs);
    throw new IllegalArgumentException("Bad warn code \"" + s + "\"");
  }
  
  public int getWarnCode()
  {
    return warnCode;
  }
  
  public String getWarnAgent()
  {
    return warnAgent;
  }
  
  public String getWarnText()
  {
    return warnText;
  }
  
  public Date getWarnDate()
  {
    return warnDate;
  }
  
  public String toString()
  {
    if (warnDate != null) {
      return String.format("%d %s %s \"%s\"", new Object[] { Integer.valueOf(warnCode), warnAgent, warnText, DateUtils.formatDate(warnDate) });
    }
    return String.format("%d %s %s", new Object[] { Integer.valueOf(warnCode), warnAgent, warnText });
  }
}

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

import java.io.IOException;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.HttpCacheStorage;
import org.apache.http.client.cache.HttpCacheUpdateCallback;

@ThreadSafe
public class BasicHttpCacheStorage
  implements HttpCacheStorage
{
  private final CacheMap entries;
  
  public BasicHttpCacheStorage(CacheConfig config)
  {
    entries = new CacheMap(config.getMaxCacheEntries());
  }
  
  public synchronized void putEntry(String url, HttpCacheEntry entry)
    throws IOException
  {
    entries.put(url, entry);
  }
  
  public synchronized HttpCacheEntry getEntry(String url)
    throws IOException
  {
    return (HttpCacheEntry)entries.get(url);
  }
  
  public synchronized void removeEntry(String url)
    throws IOException
  {
    entries.remove(url);
  }
  
  public synchronized void updateEntry(String url, HttpCacheUpdateCallback callback)
    throws IOException
  {
    HttpCacheEntry existingEntry = (HttpCacheEntry)entries.get(url);
    entries.put(url, callback.update(existingEntry));
  }
}

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

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.cache.Resource;
import org.apache.http.entity.AbstractHttpEntity;

@NotThreadSafe
class CombinedEntity
  extends AbstractHttpEntity
{
  private final Resource resource;
  private final InputStream combinedStream;
  
  CombinedEntity(Resource resource, InputStream instream)
    throws IOException
  {
    this.resource = resource;
    combinedStream = new SequenceInputStream(new ResourceStream(resource.getInputStream()), instream);
  }
  
  public long getContentLength()
  {
    return -1L;
  }
  
  public boolean isRepeatable()
  {
    return false;
  }
  
  public boolean isStreaming()
  {
    return true;
  }
  
  public InputStream getContent()
    throws IOException, IllegalStateException
  {
    return combinedStream;
  }
  
  public void writeTo(OutputStream outstream)
    throws IOException
  {
    if (outstream == null) {
      throw new IllegalArgumentException("Output stream may not be null");
    }
    InputStream instream = getContent();
    try
    {
      byte[] tmp = new byte['?'];
      int l;
      while ((l = instream.read(tmp)) != -1) {
        outstream.write(tmp, 0, l);
      }
    }
    finally
    {
      instream.close();
    }
  }
  
  private void dispose()
  {
    resource.dispose();
  }
  
  class ResourceStream
    extends FilterInputStream
  {
    protected ResourceStream(InputStream in)
    {
      super();
    }
    
    public void close()
      throws IOException
    {
      try
      {
        super.close();
      }
      finally
      {
        CombinedEntity.this.dispose();
      }
    }
  }
}

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

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.HttpCacheStorage;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;

@ThreadSafe
class CacheInvalidator
{
  private final HttpCacheStorage storage;
  private final CacheKeyGenerator cacheKeyGenerator;
  private final Log log = LogFactory.getLog(getClass());
  
  public CacheInvalidator(CacheKeyGenerator uriExtractor, HttpCacheStorage storage)
  {
    cacheKeyGenerator = uriExtractor;
    this.storage = storage;
  }
  
  public void flushInvalidatedCacheEntries(HttpHost host, HttpRequest req)
  {
    if (requestShouldNotBeCached(req))
    {
      log.debug("Request should not be cached");
      
      String theUri = cacheKeyGenerator.getURI(host, req);
      
      HttpCacheEntry parent = getEntry(theUri);
      
      log.debug("parent entry: " + parent);
      if (parent != null)
      {
        for (String variantURI : parent.getVariantMap().values()) {
          flushEntry(variantURI);
        }
        flushEntry(theUri);
      }
      URL reqURL = getAbsoluteURL(theUri);
      if (reqURL == null)
      {
        log.error("Couldn't transform request into valid URL");
        return;
      }
      Header clHdr = req.getFirstHeader("Content-Location");
      if (clHdr != null)
      {
        String contentLocation = clHdr.getValue();
        if (!flushAbsoluteUriFromSameHost(reqURL, contentLocation)) {
          flushRelativeUriFromSameHost(reqURL, contentLocation);
        }
      }
      Header lHdr = req.getFirstHeader("Location");
      if (lHdr != null) {
        flushAbsoluteUriFromSameHost(reqURL, lHdr.getValue());
      }
    }
  }
  
  private void flushEntry(String uri)
  {
    try
    {
      storage.removeEntry(uri);
    }
    catch (IOException ioe)
    {
      log.warn("unable to flush cache entry", ioe);
    }
  }
  
  private HttpCacheEntry getEntry(String theUri)
  {
    try
    {
      return storage.getEntry(theUri);
    }
    catch (IOException ioe)
    {
      log.warn("could not retrieve entry from storage", ioe);
    }
    return null;
  }
  
  protected void flushUriIfSameHost(URL requestURL, URL targetURL)
  {
    URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString()));
    if (canonicalTarget == null) {
      return;
    }
    if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) {
      flushEntry(canonicalTarget.toString());
    }
  }
  
  protected void flushRelativeUriFromSameHost(URL reqURL, String relUri)
  {
    URL relURL = getRelativeURL(reqURL, relUri);
    if (relURL == null) {
      return;
    }
    flushUriIfSameHost(reqURL, relURL);
  }
  
  protected boolean flushAbsoluteUriFromSameHost(URL reqURL, String uri)
  {
    URL absURL = getAbsoluteURL(uri);
    if (absURL == null) {
      return false;
    }
    flushUriIfSameHost(reqURL, absURL);
    return true;
  }
  
  private URL getAbsoluteURL(String uri)
  {
    URL absURL = null;
    try
    {
      absURL = new URL(uri);
    }
    catch (MalformedURLException mue) {}
    return absURL;
  }
  
  private URL getRelativeURL(URL reqURL, String relUri)
  {
    URL relURL = null;
    try
    {
      relURL = new URL(reqURL, relUri);
    }
    catch (MalformedURLException e) {}
    return relURL;
  }
  
  protected boolean requestShouldNotBeCached(HttpRequest req)
  {
    String method = req.getRequestLine().getMethod();
    return notGetOrHeadRequest(method);
  }
  
  private boolean notGetOrHeadRequest(String method)
  {
    return (!"GET".equals(method)) && (!"HEAD".equals(method));
  }
  
  public void flushInvalidatedCacheEntries(HttpHost host, HttpRequest request, HttpResponse response)
  {
    int status = response.getStatusLine().getStatusCode();
    if ((status < 200) || (status > 299)) {
      return;
    }
    URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request));
    if (reqURL == null) {
      return;
    }
    URL canonURL = getContentLocationURL(reqURL, response);
    if (canonURL == null) {
      return;
    }
    String cacheKey = cacheKeyGenerator.canonicalizeUri(canonURL.toString());
    HttpCacheEntry entry = getEntry(cacheKey);
    if (entry == null) {
      return;
    }
    if (!responseDateNewerThanEntryDate(response, entry)) {
      return;
    }
    if (!responseAndEntryEtagsDiffer(response, entry)) {
      return;
    }
    flushUriIfSameHost(reqURL, canonURL);
  }
  
  private URL getContentLocationURL(URL reqURL, HttpResponse response)
  {
    Header clHeader = response.getFirstHeader("Content-Location");
    if (clHeader == null) {
      return null;
    }
    String contentLocation = clHeader.getValue();
    URL canonURL = getAbsoluteURL(contentLocation);
    if (canonURL != null) {
      return canonURL;
    }
    return getRelativeURL(reqURL, contentLocation);
  }
  
  private boolean responseAndEntryEtagsDiffer(HttpResponse response, HttpCacheEntry entry)
  {
    Header entryEtag = entry.getFirstHeader("ETag");
    Header responseEtag = response.getFirstHeader("ETag");
    if ((entryEtag == null) || (responseEtag == null)) {
      return false;
    }
    return !entryEtag.getValue().equals(responseEtag.getValue());
  }
  
  private boolean responseDateNewerThanEntryDate(HttpResponse response, HttpCacheEntry entry)
  {
    Header entryDateHeader = entry.getFirstHeader("Date");
    Header responseDateHeader = response.getFirstHeader("Date");
    if ((entryDateHeader == null) || (responseDateHeader == null)) {
      return false;
    }
    try
    {
      Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
      Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
      return responseDate.after(entryDate);
    }
    catch (DateParseException e) {}
    return false;
  }
}

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.spy.memcached.CASResponse;
import net.spy.memcached.CASValue;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.MemcachedClientIF;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.HttpCacheEntrySerializer;
import org.apache.http.client.cache.HttpCacheStorage;
import org.apache.http.client.cache
1 2 3 4 5

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