Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * ====================================================================
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  * ====================================================================
  *
  * This software consists of voluntary contributions made by many
  * individuals on behalf of the Apache Software Foundation.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  *
  */
 package org.apache.http.impl.client.cache;
 
 import java.util.Date;
 
Determines whether a given org.apache.http.client.cache.HttpCacheEntry is suitable to be used as a response for a given org.apache.http.HttpRequest.

Since:
4.1
 
 
     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(final CacheValidityPolicy validityStrategy,
             final CacheConfig config) {
         super();
         this. = validityStrategy;
         this. = config.isSharedCache();
         this. = config.isHeuristicCachingEnabled();
         this. = config.getHeuristicCoefficient();
         this. = config.getHeuristicDefaultLifetime();
     }
 
     CachedResponseSuitabilityChecker(final CacheConfig config) {
         this(new CacheValidityPolicy(), config);
     }
 
     private boolean isFreshEnough(final HttpCacheEntry entryfinal HttpRequest requestfinal Date now) {
         if (.isResponseFresh(entrynow)) {
             return true;
         }
         if ( &&
             return true;
         }
         if (originInsistsOnFreshness(entry)) {
             return false;
         }
         final long maxstale = getMaxStale(request);
         if (maxstale == -1) {
             return false;
         }
         return (maxstale > .getStalenessSecs(entrynow));
     }
 
     private boolean originInsistsOnFreshness(final HttpCacheEntry entry) {
         if (.mustRevalidate(entry)) {
             return true;
         }
         if (!) {
             return false;
         }
         return .proxyRevalidate(entry) ||
            .hasCacheControlDirective(entry"s-maxage");
    }
    private long getMaxStale(final HttpRequest request) {
        long maxstale = -1;
        for(final Header h : request.getHeaders(.)) {
            for(final HeaderElement elt : h.getElements()) {
                if (..equals(elt.getName())) {
                    if ((elt.getValue() == null || "".equals(elt.getValue().trim()))
                            && maxstale == -1) {
                        maxstale = .;
                    } else {
                        try {
                            long val = Long.parseLong(elt.getValue());
                            if (val < 0) {
                                val = 0;
                            }
                            if (maxstale == -1 || val < maxstale) {
                                maxstale = val;
                            }
                        } catch (final NumberFormatException nfe) {
                            // err on the side of preserving semantic transparency
                            maxstale = 0;
                        }
                    }
                }
            }
        }
        return maxstale;
    }

    
Determine if I can utilize a org.apache.http.client.cache.HttpCacheEntry to respond to the given org.apache.http.HttpRequest

Parameters:
host org.apache.http.HttpHost
request org.apache.http.HttpRequest
entry org.apache.http.client.cache.HttpCacheEntry
now Right now in time
Returns:
boolean yes/no answer
    public boolean canCachedResponseBeUsed(final HttpHost hostfinal HttpRequest requestfinal HttpCacheEntry entryfinal Date now) {
        if (!isFreshEnough(entryrequestnow)) {
            .trace("Cache entry was not fresh enough");
            return false;
        }
        if (isGet(request) && !.contentLengthHeaderMatchesActualLength(entry)) {
            .debug("Cache entry Content-Length and header information do not match");
            return false;
        }
        if (hasUnsupportedConditionalHeaders(request)) {
            .debug("Request contained conditional headers we don't handle");
            return false;
        }
        if (!isConditional(request) && entry.getStatusCode() == .) {
            return false;
        }
        if (isConditional(request) && !allConditionalsMatch(requestentrynow)) {
            return false;
        }
        if (hasUnsupportedCacheEntryForGet(requestentry)) {
            .debug("HEAD response caching enabled but the cache entry does not contain a " +
                      "request method, entity or a 204 response");
            return false;
        }
        for (final Header ccHdr : request.getHeaders(.)) {
            for (final HeaderElement elt : ccHdr.getElements()) {
                if (..equals(elt.getName())) {
                    .trace("Response contained NO CACHE directive, cache was not suitable");
                    return false;
                }
                if (..equals(elt.getName())) {
                    .trace("Response contained NO STORE directive, cache was not suitable");
                    return false;
                }
                if (..equals(elt.getName())) {
                    try {
                        final int maxage = Integer.parseInt(elt.getValue());
                        if (.getCurrentAgeSecs(entrynow) > maxage) {
                            .trace("Response from cache was NOT suitable due to max age");
                            return false;
                        }
                    } catch (final NumberFormatException ex) {
                        // err conservatively
                        .debug("Response from cache was malformed" + ex.getMessage());
                        return false;
                    }
                }
                if (..equals(elt.getName())) {
                    try {
                        final int maxstale = Integer.parseInt(elt.getValue());
                        if (.getFreshnessLifetimeSecs(entry) > maxstale) {
                            .trace("Response from cache was not suitable due to Max stale freshness");
                            return false;
                        }
                    } catch (final NumberFormatException ex) {
                        // err conservatively
                        .debug("Response from cache was malformed: " + ex.getMessage());
                        return false;
                    }
                }
                if (..equals(elt.getName())) {
                    try {
                        final long minfresh = Long.parseLong(elt.getValue());
                        if (minfresh < 0L) {
                            return false;
                        }
                        final long age = .getCurrentAgeSecs(entrynow);
                        final long freshness = .getFreshnessLifetimeSecs(entry);
                        if (freshness - age < minfresh) {
                            .trace("Response from cache was not suitable due to min fresh " +
                                    "freshness requirement");
                            return false;
                        }
                    } catch (final NumberFormatException ex) {
                        // err conservatively
                        .debug("Response from cache was malformed: " + ex.getMessage());
                        return false;
                    }
                }
            }
        }
        .trace("Response from cache was suitable");
        return true;
    }
    private boolean isGet(final HttpRequest request) {
        return request.getRequestLine().getMethod().equals(.);
    }
    private boolean entryIsNotA204Response(final HttpCacheEntry entry) {
        return entry.getStatusCode() != .;
    }
    private boolean cacheEntryDoesNotContainMethodAndEntity(final HttpCacheEntry entry) {
        return entry.getRequestMethod() == null && entry.getResource() == null;
    }
    private boolean hasUnsupportedCacheEntryForGet(final HttpRequest requestfinal HttpCacheEntry entry) {
        return isGet(request) && cacheEntryDoesNotContainMethodAndEntity(entry) && entryIsNotA204Response(entry);
    }

    
Is this request the type of conditional request we support?

Parameters:
request The current httpRequest being made
Returns:
true if the request is supported
    public boolean isConditional(final HttpRequest request) {
        return hasSupportedEtagValidator(request) || hasSupportedLastModifiedValidator(request);
    }

    
Check that conditionals that are part of this request match

Parameters:
request The current httpRequest being made
entry the cache entry
now right NOW in time
Returns:
true if the request matches all conditionals
    public boolean allConditionalsMatch(final HttpRequest requestfinal HttpCacheEntry entryfinal Date now) {
        final boolean hasEtagValidator = hasSupportedEtagValidator(request);
        final boolean hasLastModifiedValidator = hasSupportedLastModifiedValidator(request);
        final boolean etagValidatorMatches = (hasEtagValidator) && etagValidatorMatches(requestentry);
        final boolean lastModifiedValidatorMatches = (hasLastModifiedValidator) && lastModifiedValidatorMatches(requestentrynow);
        if ((hasEtagValidator && hasLastModifiedValidator)
            && !(etagValidatorMatches && lastModifiedValidatorMatches)) {
            return false;
        } else if (hasEtagValidator && !etagValidatorMatches) {
            return false;
        }
        if (hasLastModifiedValidator && !lastModifiedValidatorMatches) {
            return false;
        }
        return true;
    }
    private boolean hasUnsupportedConditionalHeaders(final HttpRequest request) {
        return (request.getFirstHeader(.) != null
                || request.getFirstHeader(.) != null
                || hasValidDateField(request.));
    }
    private boolean hasSupportedEtagValidator(final HttpRequest request) {
        return request.containsHeader(.);
    }
    private boolean hasSupportedLastModifiedValidator(final HttpRequest request) {
        return hasValidDateField(request.);
    }

    
Check entry against If-None-Match

Parameters:
request The current httpRequest being made
entry the cache entry
Returns:
boolean does the etag validator match
    private boolean etagValidatorMatches(final HttpRequest requestfinal HttpCacheEntry entry) {
        final Header etagHeader = entry.getFirstHeader(.);
        final String etag = (etagHeader != null) ? etagHeader.getValue() : null;
        final Header[] ifNoneMatch = request.getHeaders(.);
        if (ifNoneMatch != null) {
            for (final Header h : ifNoneMatch) {
                for (final HeaderElement elt : h.getElements()) {
                    final String reqEtag = elt.toString();
                    if (("*".equals(reqEtag) && etag != null)
                            || reqEtag.equals(etag)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    
Check entry against If-Modified-Since, if If-Modified-Since is in the future it is invalid as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Parameters:
request The current httpRequest being made
entry the cache entry
now right NOW in time
Returns:
boolean Does the last modified header match
    private boolean lastModifiedValidatorMatches(final HttpRequest requestfinal HttpCacheEntry entryfinal Date now) {
        final Header lastModifiedHeader = entry.getFirstHeader(.);
        Date lastModified = null;
        if (lastModifiedHeader != null) {
            lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
        }
        if (lastModified == null) {
            return false;
        }
        for (final Header h : request.getHeaders(.)) {
            final Date ifModifiedSince = DateUtils.parseDate(h.getValue());
            if (ifModifiedSince != null) {
                if (ifModifiedSince.after(now) || lastModified.after(ifModifiedSince)) {
                    return false;
                }
            }
        }
        return true;
    }
    private boolean hasValidDateField(final HttpRequest requestfinal String headerName) {
        for(final Header h : request.getHeaders(headerName)) {
            final Date date = DateUtils.parseDate(h.getValue());
            return date != null;
        }
        return false;
    }
New to GrepCode? Check out our FAQ X