Determines whether a response should get a 304 response and empty body,
according to etags and if-modified-since headers.

@param request
@param scriptEtag
@return
358861
private boolean useNotModifiedHeader(HttpServletRequest request, String scriptEtag) {
		long modifiedHeader = -1;
		try {
			modifiedHeader = request.getDateHeader(HEADER_IF_MODIFIED);
			if (modifiedHeader != -1)
				modifiedHeader -= modifiedHeader % 1000;
		} catch (RuntimeException ex) {
		}
		String eTag = request.getHeader(HEADER_IF_NONE);
		if (modifiedHeader == -1) {
			return scriptEtag.equals(eTag);
		} else if (null == eTag) {
			return modifiedHeader <= START_TIME;
		} else {
			return scriptEtag.equals(eTag) && modifiedHeader <= START_TIME;
		}
	}
50138
public static void setEtag(final HttpServletResponse response, final String etag) {
		response.setHeader(HttpHeaders.ETAG, etag);
	}
177903
protected String executeRequest(HttpRequestBase request) throws IOException {
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(entity, "utf-8");
        } else {
            EntityUtils.consumeQuietly(entity);
            throw new IOException(response.getStatusLine().toString());
        }
    }
1154673
private String executeScriptExecuteRequest(String rScript) throws IOException {
    URI uri = getScriptExecutionUri();
    HttpPost httpPost = new HttpPost(uri);
    NameValuePair nameValuePair = new BasicNameValuePair("x", rScript);
    httpPost.setEntity(new UrlEncodedFormEntity(singletonList(nameValuePair)));

    String openCpuSessionKey;
    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode >= 200 && statusCode < 300) {
        Header openCpuSessionKeyHeader = response.getFirstHeader("X-ocpu-session");
        if (openCpuSessionKeyHeader == null) {
          throw new IOException("Missing 'X-ocpu-session' header");
        }
        openCpuSessionKey = openCpuSessionKeyHeader.getValue();
        EntityUtils.consume(response.getEntity());
      } else if (statusCode == 400) {
        HttpEntity entity = response.getEntity();
        String rErrorMessage = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        throw new ScriptException(rErrorMessage);
      } else {
        throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode));
      }
    }
    return openCpuSessionKey;
  }
601368
public GetCacheQuotaResponse getCacheQuota(GetCacheQuotaRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, CACHE, "quota");
        return this.invokeHttpClient(internalRequest, GetCacheQuotaResponse.class);
    }
600821
@Nonnull
  public final UnifiedResponse setETag (@Nonnull @Nonempty final String sETag)
  {
    ValueEnforcer.notEmpty (sETag, "ETag");
    ValueEnforcer.isTrue (sETag.startsWith ("\"") || sETag.startsWith ("W/\""),
                          () -> "Etag must start with a '\"' character or with 'W/\"': " + sETag);
    ValueEnforcer.isTrue (sETag.endsWith ("\""), () -> "Etag must end with a '\"' character: " + sETag);
    if (m_eHttpMethod != EHttpMethod.GET && m_eHttpMethod != EHttpMethod.HEAD)
      logWarn ("Setting an ETag on a non-GET/HEAD request may have no impact!");

    m_aResponseHeaderMap.setHeader (CHttpHeader.ETAG, sETag);
    return this;
  }
1259553
Object executeScript(String jsScript, Map<String, Object> parameters) {
    EntityType entityType = entityTypeFactory.create("entity");
    Set<String> attributeNames = parameters.keySet();
    attributeNames.forEach(key -> entityType.addAttribute(attributeFactory.create().setName(key)));
    if (attributeNames.iterator().hasNext()) {
      entityType.getAttribute(attributeNames.iterator().next()).setIdAttribute(true);
    }
    Entity entity = new DynamicEntity(entityType);
    parameters.forEach(entity::set);
    return jsMagmaScriptEvaluator.eval(jsScript, entity);
  }
78078
@Override
    public void doTag() throws JspException, IOException {
        PageContext         pageContext = (PageContext) getJspContext();
        HttpServletRequest  request     = (HttpServletRequest) pageContext.getRequest();
        HttpServletResponse response    = (HttpServletResponse) pageContext.getResponse();
        HttpSession         session     = request.getSession();


        if (TagUtils.isELValue(getValue())) {
            Object var = TagUtils.getElValue(getJspContext(), TagUtils.getElName(getValue()));
            if (var != null) {
                setValue(var);
            }
        }

        if (StringUtils.equalsIgnoreCase(getScope(), "request")) {
            request.setAttribute(getName(), getValue());
        } else if (StringUtils.equalsIgnoreCase(getScope(), "session")) {
            session.setAttribute(getName(), getValue());
        } else if (StringUtils.equalsIgnoreCase(getScope(), "cookie")) {
            Cookie cookie = new Cookie(getName(), TagUtils.getCookieValue(getValue()));

            // TODO support "Comment" // rfc2019, "Discard" // 2019++, "Expires" // (old cookies), "Secure", "Version"
            if (dynamicAttrMap.containsKey("domain")) {
                cookie.setDomain(ObjectUtils.toString(dynamicAttrMap.get("domain")));
            }
            if (dynamicAttrMap.containsKey("path")) {
                cookie.setPath(ObjectUtils.toString(dynamicAttrMap.get("path")));
            }
            if (dynamicAttrMap.containsKey("maxAge")) {
                int maxAge = NumberUtils.toInt(ObjectUtils.toString(dynamicAttrMap.get("maxAge")), (60*60*24*7)); // default value 1 week(60*60*24*7)
                cookie.setMaxAge(maxAge); //seconds
            }
            response.addCookie(cookie);
        } else {
            throw new IllegalArgumentException(String.format("[%s] is undefined scope value", this.getScope()));
        }
    }
1190973
@Override
    public String etag(Locale locale) {
        String etag = etags.get(locale);
        if (etag == null) {
            // We don't have a stored etag, that means we don't have messages. We returns 0.
            // There is a potential race condition here:
            // We retrieve the etag get 0, but when we retrieve the messages, we get messages. The browser receives 0
            // as etag, which will not match the next request. It's should not be too critical as it will just send
            // the same content a second time.
            return "0";
        } else {
            return etag;
        }
    }
14452
public static boolean isExplodeRequires(HttpServletRequest request) {
		if (isIncludeRequireDeps(request)) {
			// don't expand require deps if we're including them in the response.
			return false;
		}
		boolean result = false;
		IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
		IOptions options = aggr.getOptions();
		IConfig config = aggr.getConfig();
		Boolean reqattr = TypeUtil.asBoolean(request.getAttribute(IHttpTransport.EXPANDREQUIRELISTS_REQATTRNAME));
		result = (options == null || !options.isDisableRequireListExpansion())
				&& (config == null || !isServerExpandedLayers(request))
				&& reqattr != null && reqattr;
		return result;
	}
162779
public GetDomainStatisticsResponse getDomainStatistics(GetDomainStatisticsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS,
                LIVE_DOMAIN, request.getDomain());
        if (request.getStartDate() != null) {
            internalRequest.addParameter("startDate", request.getStartDate());
        }
        if (request.getEndDate() != null) {
            internalRequest.addParameter("endDate", request.getEndDate());
        }
        if (request.getAggregate() != null) {
            internalRequest.addParameter("aggregate", request.getAggregate().toString());
        }
        return invokeHttpClient(internalRequest, GetDomainStatisticsResponse.class);
    }
638530
public static Response.ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) {
        return getRequest().evaluatePreconditions(lastModified, eTag);
    }
1099524
function handleScriptValidation(url) {
        if (!url) {
          return;
        }
        url = url.split('#')[0];
        var scripts = document.getElementsByTagName('script');
        for (var i = scripts.length; i--;) {
          if (scripts[i].src === url) {
            return true;
          }
        }
        return false;
      }
642140
function( xhr, url ) {
		var lastModified = xhr.getResponseHeader("Last-Modified"),
			etag = xhr.getResponseHeader("Etag");

		if ( lastModified ) {
			jQuery.lastModified[url] = lastModified;
		}

		if ( etag ) {
			jQuery.etag[url] = etag;
		}

		// Opera returns 0 when status is 304
		return xhr.status === 304 || xhr.status === 0;
	}
604029
public static String getAuthority(SlingHttpServletRequest request) {
        String host = request.getServerName();
        int port = request.getServerPort();
        return port > 0 && (port != getDefaultPort(request)) ? (host + ":" + port) : host;
    }
544059
def should_return_304(self) -> bool:
        
        # If client sent If-None-Match, use it, ignore If-Modified-Since
        if self.request.headers.get("If-None-Match"):
            return self.check_etag_header()

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if date_tuple is not None:
                if_since = datetime.datetime(*date_tuple[:6])
                assert self.modified is not None
                if if_since >= self.modified:
                    return True

        return False
639771
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Get the script path from the request - include aware (GROOVY-815)
        final String scriptUri = getScriptUri(request);

        // Set it to HTML by default
        response.setContentType("text/html; charset="+encoding);

        // Set up the script context
        final ServletBinding binding = new ServletBinding(request, response, servletContext);
        setVariables(binding);

        // Run the script
        try {
            Closure closure = new Closure(gse) {

                public Object call() {
                    try {
                        return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding);
                    } catch (ResourceException | ScriptException e) {
                        throw new RuntimeException(e);
                    }
                }

            };
            GroovyCategorySupport.use(ServletCategory.class, closure);
        } catch (RuntimeException runtimeException) {
            StringBuilder error = new StringBuilder("GroovyServlet Error: ");
            error.append(" script: '");
            error.append(scriptUri);
            error.append("': ");
            Throwable e = runtimeException.getCause();
            /*
             * Null cause?!
             */
            if (e == null) {
                error.append(" Script processing failed.\n");
                error.append(runtimeException.getMessage());
                if (runtimeException.getStackTrace().length > 0)
                    error.append(runtimeException.getStackTrace()[0].toString());
                servletContext.log(error.toString());
                System.err.println(error.toString());
                runtimeException.printStackTrace(System.err);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error.toString());
                return;
            }
            /*
             * Resource not found.
             */
            if (e instanceof ResourceException) {
                error.append(" Script not found, sending 404.");
                servletContext.log(error.toString());
                System.err.println(error.toString());
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            /*
             * Other internal error. Perhaps syntax?!
             */
            servletContext.log("An error occurred processing the request", runtimeException);
            error.append(e.getMessage());
            if (e.getStackTrace().length > 0)
                error.append(e.getStackTrace()[0].toString());
            servletContext.log(e.toString());
            System.err.println(e.toString());
            runtimeException.printStackTrace(System.err);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        }
    }