/*
NOTE: This class defers determining if a response is cacheable until the
output stream is needed.
This it the reason for the somewhat complicated logic in the add/setHeader
methods below.
167471
private void init() {
        cacheable = null;
        status = SC_OK;
        streamDelegate = new ServletResponseStreamDelegate(this) {
            protected OutputStream createOutputStream() throws IOException {
                // Test if this request is really cacheable, otherwise,
                // just write through to underlying response, and don't cache
                if (isCacheable()) {
                    return cacheResponse.getOutputStream();
                }
                else {
                    // TODO: We need to tell the cache about this, somehow...
                    writeHeaders(cacheResponse, (HttpServletResponse) getResponse());
                    return super.getOutputStream();
                }
            }
        };
    }
947933
async function oneBehindFetch(input, init) {
  let cachedResponse = cache.get(input);
  if (!cachedResponse) {
    cachedResponse = {
      maxAge: Promise.resolve(MaxAge.zero()),
    };
    cache.set(input, cachedResponse);
  }
  const maxAge = await cachedResponse.maxAge;
  if (!maxAge.isExpired()) {
    // we have to clone the response to enable multiple reads
    const response = await cachedResponse.responsePromise;
    return response.clone();
  }
  const staleResponsePromise = cachedResponse.responsePromise;
  const newResponsePromise = fetch(input, init);
  cachedResponse = {
    responsePromise: newResponsePromise,
    maxAge: newResponsePromise.then(
        (response) => MaxAge.parse(response.headers.get('cache-control'))
    ),
  };
  cache.set(input, cachedResponse);
  const result = staleResponsePromise || newResponsePromise;
  // we have to clone the response to enable multiple reads
  const response = await result;
  return response.clone();
}
1285284
private void writeCachedResultToStream(HttpServletResponse res) throws IOException {

        List<Object> elements = m_cachedEntry.elements();
        int count = 0;
        if (elements != null) {
            for (int i = 0; i < elements.size(); i++) {
                Object o = elements.get(i);
                if (o instanceof byte[]) {
                    res.getOutputStream().write((byte[])o);
                } else {
                    if ((m_includeResults != null) && (m_includeResults.size() > count)) {
                        // make sure that we don't run behind end of list (should never happen, though)
                        res.getOutputStream().write(m_includeResults.get(count));
                        count++;
                    }
                    // skip next entry, which is the parameter map for this include call
                    i++;
                    // skip next entry, which is the attribute map for this include call
                    i++;
                }
            }
        }
584668
public byte[] getWriterBytes() {

        if (isSuspended()) {
            // No output whatsoever if the response is suspended
            return new byte[0];
        }
        if (m_cacheBytes != null) {
            // Optimization for cached "leaf" nodes, here I re-use the array from the cache
            return m_cacheBytes;
        }
        if (m_out == null) {
            // No output was written so far, just return an empty array
            return new byte[0];
        }
        if (m_writer != null) {
            // Flush the writer in case something was written on it
            m_writer.flush();
        }
        return m_out.getBytes();
    }
747198
def output(self, stream, disabletransferencoding = None):
        
        if self._sendHeaders:
            raise HttpProtocolException('Cannot modify response, headers already sent')
        self.outputstream = stream
        try:
            content_length = len(stream)
        except Exception:
            pass
        else:
            self.header(b'Content-Length', str(content_length).encode('ascii'))
        if disabletransferencoding is not None:
            self.disabledeflate = disabletransferencoding
        self._startResponse()
1363340
public static void disableCaching(HttpServletResponse response) {
        response.addHeader(PRAGMA_HEADER_NAME, "no-cache");
        response.addHeader(CACHE_CONTROL_HEADER_NAME, "no-cache, no-store, max-age=0");
        response.addDateHeader(EXPIRES_HEADER_NAME, 1L);
    }
81954
public InputStream getInputStream() throws IOException {
        if (null == inputStream) {
            if (readFromCache) {
                inputStream = new FileInputStream(cacheFile.toFile());
            } else {
                WriteCacheFileInputStream wis = new WriteCacheFileInputStream(delegate.getInputStream(),
                        new FileOutputStream(cacheFile.toFile()));
                wis.onInputStreamClose(() -> {
                    try {
                        final int responseCode = delegate.getResponseCode();
                        if (responseCode == HTTP_OK) {
                            cache.saveCachedDataInfo(cacheFile, cachedDataInfo);
                        } else {
                            if (logger.isWarnEnabled()) {
                                logger.warn("not caching because of response code {}: {}", responseCode, getURL());
                            }
                        }
                    } catch (final IOException e) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("cannot retrieve response code");
                        }
                    }
                });
                inputStream = wis;
            }
        }
        return inputStream;
    }
438029
@Override
	protected void processRequest(String requestedPath, HttpServletRequest request, HttpServletResponse response,
			BundleHashcodeType bundleHashcodeType) throws IOException {

		boolean responseHeaderWritten = false;
		boolean validBundle = true;
		if (!jawrConfig.isDebugModeOn() && jawrConfig.isStrictMode()
				&& bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
			validBundle = false;
		}

		// If debug mode is off, check for If-Modified-Since and
		// If-none-match headers and set response caching headers.
		if (!this.jawrConfig.isDebugModeOn()) {
			// If a browser checks for changes, always respond 'no changes'.
			if (validBundle && (null != request.getHeader(IF_MODIFIED_SINCE_HEADER)
					|| null != request.getHeader(IF_NONE_MATCH_HEADER))) {
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("Returning 'not modified' header. ");
				return;
			}

			if (validBundle) {
				// Add caching headers
				setResponseHeaders(response);
			} else {

				responseHeaderWritten = illegalBundleRequestHandler.writeResponseHeader(requestedPath, request,
						response);
				if (!responseHeaderWritten) {
					// Add caching headers
					setResponseHeaders(response);
				}
			}
		}

		// Returns the real file path
		String filePath = getRealFilePath(requestedPath, bundleHashcodeType);

		try {
			if (isValidRequestedPath(filePath)
					&& (validBundle || illegalBundleRequestHandler.canWriteContent(requestedPath, request))) {

				// Set the content type
				response.setContentType(getContentType(requestedPath, request));
				writeContent(filePath, request, response);

			} else {
				if (!responseHeaderWritten) {
					LOGGER.error("Unable to load the image for the request URI : " + request.getRequestURI());
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
				}
			}
		} catch (EOFException eofex) {
			LOGGER.info("Browser cut off response", eofex);
		} catch (ResourceNotFoundException e) {
			LOGGER.info("Unable to write resource " + request.getRequestURI(), e);
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		} catch (IOException ex) {
			LOGGER.error("Unable to write resource " + request.getRequestURI(), ex);
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}

		if (LOGGER.isDebugEnabled())
			LOGGER.debug("request succesfully attended");
	}
801409
public static void setHeader(HttpServletResponse response, String name, Object value) {
		if (value instanceof String) {
			response.setHeader(name, (String) value);
		} else if (Date.class.isAssignableFrom(value.getClass())) {
			response.setDateHeader(name, ((Date) value).getTime());
		} else if (value instanceof Integer || "int".equals(value.getClass().getSimpleName().toLowerCase())) {
			response.setIntHeader(name, (Integer) value);
		} else {
			response.setHeader(name, value.toString());
		}
	}
1018017
public static void setNoCache(HttpServletRequest request,
								  HttpServletResponse response)
	{
		//get rid of unwanted whitespace
		String protocol = request.getProtocol().trim();

//		if ("HTTP/1.0".equals(protocol))
		{
			response.setHeader("Pragma", "no-cache");
		}
//		else if ("HTTP/1.1".equals(protocol))
		{
			response.setHeader("Cache-Control", "no-cache, max-age=0, revalidate");//no-store only disables archiving
		}

		//get browser type
//		String userAgent = request.getHeader("User-Agent");

//		if ((userAgent != null) && (userAgent.indexOf("MSIE") != -1))
		{
			//Internet Explorer:
			//date and timestamp will be set to jan 1st 1970, so no caching is performed.
//			response.setDateHeader("Expires", 0);
		}
		long now = System.currentTimeMillis();
		response.setDateHeader("Date", now);
		response.setDateHeader("Expires", now);
		response.setDateHeader("Last-Modified", now);


	}
1029979
def should_cache(self, request, response):
        

        if not getattr(request, '_cache_update_cache', False):
            return False
        if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS):
            return False
        if getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False) and self.session_accessed and request.user.is_authenticated:
            return False
        if self.has_uncacheable_headers(response):
            return False
        return True
632126
@SuppressWarnings({ "unchecked" })
    /* package */<T> HystrixCachedObservable<T> putIfAbsent(String cacheKey, HystrixCachedObservable<T> f) {
        ValueCacheKey key = getRequestCacheKey(cacheKey);
        if (key != null) {
            /* look for the stored value */
            ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> cacheInstance = requestVariableForCache.get(concurrencyStrategy);
            if (cacheInstance == null) {
                throw new IllegalStateException("Request caching is not available. Maybe you need to initialize the HystrixRequestContext?");
            }
            HystrixCachedObservable<T> alreadySet = (HystrixCachedObservable<T>) cacheInstance.putIfAbsent(key, f);
            if (alreadySet != null) {
                // someone beat us so we didn't cache this
                return alreadySet;
            }
        }
        // we either set it in the cache or do not have a cache key
        return null;
    }
1037313
public static boolean isCacheable(Response response, Request request) {
    // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
    // This implementation doesn't support caching partial content.
    switch (response.code()) {
      case HTTP_OK:
      case HTTP_NOT_AUTHORITATIVE:
      case HTTP_NO_CONTENT:
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_NOT_FOUND:
      case HTTP_BAD_METHOD:
      case HTTP_GONE:
      case HTTP_REQ_TOO_LONG:
      case HTTP_NOT_IMPLEMENTED:
      case StatusLine.HTTP_PERM_REDIRECT:
        // These codes can be cached unless headers forbid it.
        break;

      case HTTP_MOVED_TEMP:
      case StatusLine.HTTP_TEMP_REDIRECT:
        // These codes can only be cached with the right response headers.
        // http://tools.ietf.org/html/rfc7234#section-3
        // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.
        if (response.header("Expires") != null
            || response.cacheControl().maxAgeSeconds() != -1
            || response.cacheControl().isPublic()
            || response.cacheControl().isPrivate()) {
          break;
        }
        // Fall-through.

      default:
        // All other codes cannot be cached.
        return false;
    }

    // A 'no-store' directive on request or response prevents the response from being cached.
    return !response.cacheControl().noStore() && !request.cacheControl().noStore();
  }
337127
@SuppressWarnings("unchecked")
  private void handleResponseOk(long requestId, Object response) {
    ContextualFuture future = futures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.complete(response));
    }
  }
1200587
@PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public Response put(@PathParam("cacheName") String cacheName, Cache cache) {

        if (!cacheService.isPresent(cacheName)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        cacheService.update(cacheName, cache);

        return Response.ok().build();
    }
498958
@Override
    public final CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response) {
        final Resource stylesheetResource = this.getStylesheetResource(request);
        final Serializable stylesheetCacheKey;
        try {
            stylesheetCacheKey = this.xmlUtilities.getStylesheetCacheKey(stylesheetResource);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(
                    "Failed to get Transformer for stylesheet: " + stylesheetResource, e);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load stylesheet: " + stylesheetResource, e);
        }

        return CacheKey.build(stylesheetResource.getDescription(), stylesheetCacheKey);
    }
302899
protected void preventCaching(final HttpServletResponse response) {
        response.setHeader("Pragma", NO_CACHE);
        response.setDateHeader("Expires", 1L);
        response.setHeader(CACHE_CONTROL, NO_CACHE);
        response.addHeader(CACHE_CONTROL, "no-store");
    }