Checks the ETag and sends a cache match response if it matches.
976375
def check_cache(self, e_tag, match):
        """"""
        if e_tag != match:
            return False
        self.send_response(304)
        self.send_header("ETag", e_tag)
        self.send_header("Cache-Control",
                         "max-age={0}".format(self.server.max_age))
        self.end_headers()
        thread_local.size = 0
        return True
704765
def etag(func):
    
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        """Call the view function and generate an ETag value, checking the
        headers to determine what response to send."""
        # only for HEAD and GET requests
        assert request.method in ['HEAD', 'GET'],\
            '@etag is only supported for GET requests'
        response = func(*args, **kwargs)
        response = make_response(response)
        etag_value = '"' + hashlib.md5(response.get_data()).hexdigest() + '"'
        response.headers['ETag'] = etag_value
        if_match = request.headers.get('If-Match')
        if_none_match = request.headers.get('If-None-Match')
        if if_match:
            etag_list = [tag.strip() for tag in if_match.split(',')]
            if etag_value not in etag_list and '*' not in etag_list:
                response = precondition_failed()
        elif if_none_match:
            etag_list = [tag.strip() for tag in if_none_match.split(',')]
            if etag_value in etag_list or '*' in etag_list:
                response = not_modified()
        return response
    return wrapped
924108
function Request_isHeaderCacheUnModified() {

        var etagMatches = true,
            notModified = true,
            modifiedSince = this.getRequestHeader('if-modified-since'),
            noneMatch = this.getRequestHeader('if-none-match'),
            cc = this.getRequestHeader('cache-control'),
            lastModified = this.getHeader('last-modified'),
            etag = this.getHeader('etag');


        // unconditional request
        if (!modifiedSince && !noneMatch) {
            return false;
            // check for no-cache cache request directive
        } else if (cc && cc.indexOf('no-cache') !== -1) {
            return false;
        }

        // parse if-none-match
        if (noneMatch) {
            noneMatch = noneMatch.split(/ *, */);
        }
        // if-none-match
        if (noneMatch) {
            etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0];
        }
        // if-modified-since
        if (modifiedSince) {
            modifiedSince = Date.parse(modifiedSince);
            lastModified = Date.parse(lastModified);
            notModified = lastModified <= modifiedSince;
        }

        return !!(etagMatches && notModified);
    }
159324
def get_matches(self, text, cache=None, conflict_resolver=resolve_using_maximal_coverage):
        """"""
        is_root_node = False
        if cache is None:
            cache = {}
            is_root_node = True
        if id(self) in cache:
            return cache[id(self)]
        matches = self.get_matches_without_cache(text, cache=cache)
        cache[id(self)] = matches

        # if this is the root node, resolve the matches
        if is_root_node and conflict_resolver is not None:
            return conflict_resolver(matches)
        return matches
435720
public XcapResponse putIfMatch(URI uri, String eTag, String mimetype,
			String content, Header[] additionalRequestHeaders,
			Credentials credentials) throws IOException {

		if (log.isDebugEnabled()) {
			log.debug("putIfMatch(uri=" + uri + ", eTag=" + eTag
					+ ", mimetype=" + mimetype + ", content=" + content
					+ " , additionalRequestHeaders = ( "
					+ Arrays.toString(additionalRequestHeaders) + " ) )");
		}

		final HttpPut request = new HttpPut(uri);
		setRequestEntity(request, content, mimetype);
		request.setHeader(XcapConstant.HEADER_IF_MATCH, eTag);
		return execute(request, additionalRequestHeaders, credentials);

	}
571545
def build_etag(self, response, include_etag=True, **kwargs):
        
        if not include_etag:
            return

        if not spooky:
            # use built-in md5
            response.add_etag()
            return

        # use spooky
        response.headers["ETag"] = quote_etag(
            hexlify(
                spooky.hash128(
                    response.get_data(),
                ).to_bytes(16, "little"),
            ).decode("utf-8"),
        )
1116210
def get_match(self, match_id):
        """"""
        return self._make_req(endpoints.MATCH, dict(
            k=self.key,
            mp=match_id), Match)
694209
function onlineExist(pattern, opts, callback) {
  var args = verify(pattern, opts, callback);
  opts = args.opts;
  callback = args.callback;

  var refs = 'refs/heads/' + cache.branch;
  request(refs, opts, function cb(err, res) {
    if (res === false) {
      refs = 'refs/tags/' + cache.branch;
      request(refs, opts, callback);
      return;
    }
    callback(null, true);
  });
}
34931
def build_response(
        self, request, response, from_cache=False, cacheable_methods=None
    ):
        
        cacheable = cacheable_methods or self.cacheable_methods
        if not from_cache and request.method in cacheable:
            # Check for any heuristics that might update headers
            # before trying to cache.
            if self.heuristic:
                response = self.heuristic.apply(response)

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response

            # We always cache the 301 responses
            elif response.status == 301:
                self.controller.cache_response(request, response)
            else:
                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response, request, response
                    ),
                )
                if response.chunked:
                    super_update_chunk_length = response._update_chunk_length

                    def _update_chunk_length(self):
                        super_update_chunk_length()
                        if self.chunk_left == 0:
                            self._fp._close()

                    response._update_chunk_length = types.MethodType(
                        _update_chunk_length, response
                    )

        resp = super(CacheControlAdapter, self).build_response(request, response)

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp
1353251
def _handle_response(self, transaction):
        
        code = transaction.response.code
        utils.check_code(code)
        """
        VALID response:
        change the current cache value by switching the option set with the one provided
        also resets the timestamp
        if the request etag is different from the response, send the cached response
        """
        if code == Codes.VALID.number:
            logger.debug("received VALID")
            self.cache.validate(transaction.request, transaction.response)
            if transaction.request.etag != transaction.response.etag:
                element = self.cache.search_response(transaction.request)
                transaction.response = element.cached_response
            return transaction

        """
        CHANGED, CREATED or DELETED response:
        mark the requested resource as not fresh
        """
        if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number:
            target = self.cache.search_related(transaction.request)
            if target is not None:
                for element in target:
                    self.cache.mark(element)
            return transaction

        """
        any other response code can be cached normally
        """
        self.cache.cache_add(transaction.request, transaction.response)
        return transaction
1119900
def _uncached_match(self, text, pos, cache, error):
        """"""
        m = self.re.match(text, pos)
        if m is not None:
            span = m.span()
            node = RegexNode(self, text, pos, pos + span[1] - span[0])
            node.match = m  # TODO: A terrible idea for cache size?
            return node
231362
def clean_etag(self, etag):
        
        if etag:
            etag = etag.replace('"', '')
            extension = None
            for ext, mime in self.EXTENSION_MAP:
                if mime == self.type:
                    extension = ext[1:]
                    break
            if extension:
                etag += '_' + extension
            self.response.etag = etag
595544
protected function matchCache()
    {
        // check if we can find a match in cache
        // check if a cache exists
        if ($this->cache instanceof Cache) {
            // check if we have any routes saved in cache
            if ($cachedRoutes = $this->cache->get('routeMiddlewareRoutes')) {
                // check if the requested uri can be found in the cache
                if (isset($cachedRoutes[$this->requestUri])) {

                    // check if endpoint class exists
                    if (!$this->endpointExists($cachedRoutes[$this->requestUri]['matchedEndpoint'])) {
                        throw new NotFound();
                    }

                    if (!$this->endpointMethodExists(
                        $cachedRoutes[$this->requestUri]['matchedEndpoint'],
                        $this->requestMethod
                    )) {
                        // route found but method can't be found
                        throw new MethodNotAllowed();
                    }

                    // match found, set info
                    $this->matchedRoute = $cachedRoutes[$this->requestUri]['matchedRoute'];
                    $this->matchedEndpoint = $cachedRoutes[$this->requestUri]['matchedEndpoint'];
                    $this->matchedMethod  = $this->requestMethod;
                    $this->params  = (isset($cachedRoutes[$this->requestUri]['params'])) ?
                        $cachedRoutes[$this->requestUri]['params'] : [];

                    // no need to look for more
                    return true;
                }
            }
        }

        return false;
    }
1063384
public static boolean handleIfMatch(final HttpServerExchange exchange, final List<ETag> etags, boolean allowWeak) {
        return handleIfMatch(exchange.getRequestHeaders().getFirst(Headers.IF_MATCH), etags, allowWeak);
    }
736447
function checkCacheResponse(key, err, result, type, cacheIndex){
    if(err){
      log(true, 'Error when getting key ' + key + ' from cache of type ' + type + ':', err);

      if(cacheIndex < self.caches.length - 1){
        return {status:'continue'};
      }
    }
    //THIS ALLOWS false AS A VALID CACHE VALUE, BUT DO I WANT null TO BE VALID AS WELL?
    if(result !== null && typeof result !== 'undefined'){
      log(false, 'Key found:', {key: key, value: result});
      return {status: 'break', result: result};
    }
    var curCache = self.caches[cacheIndex];
    for(var i = cacheIndex + 1; i < self.cachesLength; i++) {
      var nextCache = self.caches[i];
      if(nextCache.checkOnPreviousEmpty || nextCache.expiration > curCache.expiration){
        return {status:'continue', toIndex: i};
      }
    }
    return {status: 'else'};
  }
186332
def check(self, pattern):
        
        if self.eos:
            raise EndOfText()
        if pattern not in self._re_cache:
            self._re_cache[pattern] = re.compile(pattern, self.flags)
        return self._re_cache[pattern].match(self.data, self.pos)
784693
function checkIfMatch(req, res, next) {
    var clientETags;
    var cur;
    var etag = res.etag || res.getHeader('etag') || '';
    var ifMatch;
    var matched = false;

    if ((ifMatch = req.headers['if-match'])) {

        clientETags = ifMatch.split(/\s*,\s*/);

        for (var i = 0; i < clientETags.length; i++) {
            cur = clientETags[i];

            // only strong comparison

            cur = cur.replace(/^W\//, '');
            cur = cur.replace(/^"(\w*)"$/, '$1');

            if (cur === '*' || cur === etag) {
                matched = true;
                break;
            }
        }

        if (!matched) {
            var err = new PreconditionFailedError(IF_MATCH_FAIL,
                ifMatch,
                etag);
            return (next(err));
        }
    }

    return (next());
}