Evaluate the cache control headers for the request to see if it can be served from
the cache.

@param request the request
@param servletResponse the servlet response
@param resource the fedora resource
@param session the session
4749
protected void checkCacheControlHeaders(final Request request,
                                                   final HttpServletResponse servletResponse,
                                                   final FedoraResource resource,
                                                   final HttpSession session) {
        evaluateRequestPreconditions(request, servletResponse, resource, session, true);
        addCacheControlHeaders(servletResponse, resource, session);
    }
838992
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String url = this.getURL(req);

        LOGGER.debug("Started processing request : {}", url);

        List<String> resourcesToMerge = findResourcesToMerge(req.getContextPath(), url);
        String extensionOrPath = detectExtension(url);//in case of non js/css files it null
        if (extensionOrPath.isEmpty()) {
            extensionOrPath = resourcesToMerge.get(0);//non grouped i.e. non css/js file, we refer it's path in that case
        }

        //If not modified, return 304 and stop
        ResourceStatus status = JSCSSMergeServlet.isNotModified(this.getServletContext(), req, resourcesToMerge, this.turnOffETag);
        if (status.isNotModified()) {
            LOGGER.trace("Resources Not Modified. Sending 304.");
            String ETag = !this.turnOffETag ? status.getActualETag() : null;
            JSCSSMergeServlet.sendNotModified(resp, extensionOrPath, ETag, this.expiresMinutes, this.cacheControl, this.overrideExistingHeaders);
            return;
        }


        //Add appropriate headers
        this.addAppropriateResponseHeaders(extensionOrPath, resourcesToMerge, status.getActualETag(), resp);

        OutputStream outputStream = resp.getOutputStream();
        String contextPathForCss = customContextPathForCSSUrls != null ?
                customContextPathForCSSUrls : req.getContextPath();
        ProcessedResult processedResult = this.processResources(contextPathForCss, outputStream, resourcesToMerge);
        int resourcesNotFound = processedResult.getNumberOfMissingResources();

        if (resourcesNotFound > 0 && resourcesNotFound == resourcesToMerge.size()) { //all resources not found
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            LOGGER.warn("All resources are not found. Sending 404.");
            return;
        }
        if (outputStream != null) {
            try {
                resp.setStatus(HttpServletResponse.SC_OK);
                outputStream.close();
            } catch (Exception e) {
                // ignore
            }
        }
        resp.setHeader("Content-Length", String.valueOf(processedResult.contentLength));
        LOGGER.debug("Finished processing Request : {}", url);
    }
64576
@Override
	public SecurityContext initializeAndExamineRequest(final HttpServletRequest request, final HttpServletResponse response) throws FrameworkException {

		logger.warn("KAI: RestAuthenticator.initializeAndExamineRequest");

		SecurityContext securityContext;

		Principal user = SessionHelper.checkSessionAuthentication(request);

		if (user == null) {

			user = getUser(request, true);

		}

		if (user == null) {

			// If no user could be determined, assume frontend access
			securityContext = SecurityContext.getInstance(user, request, AccessMode.Frontend);

		} else {


			if (user instanceof SuperUser) {

				securityContext = SecurityContext.getSuperUserInstance(request);

			} else {

				securityContext = SecurityContext.getInstance(user, request, AccessMode.Backend);

				SessionHelper.clearInvalidSessions(user);

			}

		}

		securityContext.setAuthenticator(this);

		// Check CORS settings (Cross-origin resource sharing, see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
		final String origin = request.getHeader("Origin");
		if (!StringUtils.isBlank(origin)) {

			final Services services = Services.getInstance();

			response.setHeader("Access-Control-Allow-Origin", origin);

			 // allow cross site resource sharing (read only)
			final String maxAge = Settings.AccessControlMaxAge.getValue();
			if (StringUtils.isNotBlank(maxAge)) {
				response.setHeader("Access-Control-Max-Age", maxAge);
			}

			final String allowMethods = Settings.AccessControlAllowMethods.getValue();
			if (StringUtils.isNotBlank(allowMethods)) {
				response.setHeader("Access-Control-Allow-Methods", allowMethods);
			}

			final String allowHeaders = Settings.AccessControlAllowHeaders.getValue();
			if (StringUtils.isNotBlank(allowHeaders)) {
				response.setHeader("Access-Control-Allow-Headers", allowHeaders);
			}

			final String allowCredentials = Settings.AccessControlAllowCredentials.getValue();
			if (StringUtils.isNotBlank(allowCredentials)) {
				response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
			}

			final String exposeHeaders = Settings.AccessControlExposeHeaders.getValue();
			if (StringUtils.isNotBlank(exposeHeaders)) {
				response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
			}
		 }

		examined = true;
		return securityContext;

	}
60696
public static boolean isTokenValid(final HttpServletRequest request, final String key) {
		String token = request.getParameter(key);
		if (StringUtils.isBlank(token)) {
			return false;
		}
		String session = (String) request.getSession(true).getAttribute(key);
		return token.equals(session);
	}
272367
protected void logRequest(String method, HttpServletRequest request) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Request started\n" +
                    "   Class: " + this.getClass().getName() + "\n" +
                    "   Method: " + method + "\n" +
                    "   User id: " + Session.getSessionBean().getUserId() + "\n" +
                    "   Session id: " + Session.getSessionBean().getId() + "\n" +
                    "   Remote address: " + request.getRemoteAddr() + "\n" +
                    "   User-Agent: " + request.getHeader("User-Agent"));
        }
    }
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
34448
private void setDateAndCacheHeaders(final HttpResponse response) {
    final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    final Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(startupTime)));
  }
1122232
private URI getHasMemberFromResource(final HttpServletRequest request) {
        final FedoraResource resource = resource(request);
        return getHasMemberFromResource(request, resource);
    }
786524
public PauseSessionResponse pauseSession(PauseSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION,
                request.getSessionId());
        internalRequest.addParameter(PAUSE, null);
        return invokeHttpClient(internalRequest, PauseSessionResponse.class);
    }
640515
public GetSessionResponse getSession(GetSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION,
                request.getSessionId());
        return invokeHttpClient(internalRequest, GetSessionResponse.class);
    }
546291
public static void setNoCacheHeader(final HttpServletResponse response) {
		// Http 1.0 header
		response.setDateHeader(HttpHeaders.EXPIRES, 1L);
		response.addHeader(HttpHeaders.PRAGMA, "no-cache");
		// Http 1.1 header
		response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
	}
194614
public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache,no-store");

        String url=request.getParameter("URL");
        if (url!=null && url.length()>0)
        {
            response.sendRedirect(url);
        }
        else
        {
            PrintWriter pout = response.getWriter();
            Page page=null;
            
            try{
                page = new Page();
                page.title("SendRedirect Servlet");     
                
                page.add(new Heading(1,"SendRedirect Servlet"));
                
                page.add(new Heading(1,"Form to generate Dump content"));
                TableForm tf = new TableForm
                    (response.encodeURL(URI.addPaths(request.getContextPath(),
                                                     request.getServletPath())+
                                        "/action"));
                tf.method("GET");
                tf.addTextField("URL","URL",40,request.getContextPath()+"/dump");
                tf.addButton("Redirect","Redirect");
                page.add(tf);
                page.write(pout);
                pout.close();
            }
            catch (Exception e)
            {
                log.warn(LogSupport.EXCEPTION,e);
            }
        }
    }
1243152
protected StringBuffer getHeaderSection(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer(mainScriptTemplate.toString());
		sb.append("JAWR.app_context_path='").append(request.getContextPath()).append("';\n");
		return sb;
	}
357628
protected void processNoCache( HttpServletRequest request, HttpServletResponse response )
    {
        //
        // Set the no-cache headers if:
        //    1) the module is configured for it, or
        //    2) netui-config.xml has an "always" value for <pageflow-config><prevent-cache>, or
        //    3) netui-config.xml has an "inDevMode" value for <pageflow-config><prevent-cache>, and we're not in
        //       production mode.
        //
        boolean noCache = moduleConfig.getControllerConfig().getNocache();

        if ( ! noCache )
        {
            PageFlowConfig pfConfig = ConfigUtil.getConfig().getPageFlowConfig();
            
            if ( pfConfig != null )
            {
                PreventCache preventCache = pfConfig.getPreventCache();
                
                if ( preventCache != null )
                {
                    switch ( preventCache.getValue() )
                    {
                        case PreventCache.INT_ALWAYS:
                            noCache = true;
                            break;
                        case PreventCache.INT_IN_DEV_MODE:
                            noCache = ! _servletContainerAdapter.isInProductionMode();
                            break;
                    }
                }
            }
        }
        
        if ( noCache )
        {
            //
            // The call to PageFlowPageFilter.preventCache() will cause caching to be prevented
            // even when we end up forwarding to a page.  Normally, no-cache headers are lost
            // when a server forward occurs.
            //
            ServletUtils.preventCache( response );
            PageFlowUtils.setPreventCache( request );
        }
    }
330027
public RefreshSessionResponse refreshSession(RefreshSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION,
                request.getSessionId());
        internalRequest.addParameter(REFRESH, null);
        return invokeHttpClient(internalRequest, RefreshSessionResponse.class);
    }
368034
@Override
    protected void doGet( final HttpServletRequest request, final HttpServletResponse response )
            throws ServletException, IOException {

        if ( "/favicon.ico".equals( request.getRequestURI() ) ) {
            super.doGet( request, response );
            return;
        }

        final String pathInfo = request.getPathInfo();
        LOG.info( " + starting at path " + pathInfo );

        if ( pathInfo.startsWith( "/readonly" ) ) {
            response.getWriter().println( "readonly" );
            return;
        }

        if ( pathInfo.startsWith( "/put" ) ) {
            final HttpSession session = request.getSession();
            final Cache cache = getOrCreateCache( session );
            final Enumeration<String> names = request.getParameterNames();
            while ( names.hasMoreElements() ) {
                final String name = names.nextElement();
                final String value = request.getParameter( name );
                cache.put( name, value );
            }
        }
        else if ( pathInfo.startsWith( "/list" ) ) {
            final HttpSession session = request.getSession(false);
            if(session == null)
            	return;
            
            final PrintWriter out = response.getWriter();
            final Cache cache = getOrCreateCache( session );
            for ( final Map.Entry<String, Object> entry : cache.entrySet() ) {
                out.println( entry.getKey() + "=" + entry.getValue() );
            }
        }
        else if ( pathInfo.startsWith( "/swapSessionId" ) ) {
            final HttpSession session = request.getSession();
            final Cache cache = getOrCreateCache( session );

            final PrintWriter out = response.getWriter();
            out.println( "old sessionId: " + session.getId() );
            session.invalidate();

            final HttpSession newSession = request.getSession();
            newSession.setAttribute( "cache", cache );
            out.println( "new sessionId: " + newSession.getId() );
        }

    }
300924
public static void handleStaticResourceRequest(final HttpServletRequest request,
			final HttpServletResponse response) {
		String staticRequest = request.getParameter(WServlet.STATIC_RESOURCE_PARAM_NAME);

		try {
			InternalResource staticResource = InternalResourceMap.getResource(staticRequest);
			boolean headersOnly = "HEAD".equals(request.getMethod());

			if (staticResource == null) {
				LOG.warn("Static resource [" + staticRequest + "] not found.");
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				return;
			}

			InputStream resourceStream = staticResource.getStream();
			if (resourceStream == null) {
				LOG.warn(
						"Static resource [" + staticRequest + "] not found. Stream for content is null.");
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				return;
			}

			int size = resourceStream.available();
			String fileName = WebUtilities.encodeForContentDispositionHeader(staticRequest.
					substring(staticRequest
							.lastIndexOf('/') + 1));

			if (size > 0) {
				response.setContentLength(size);
			}

			response.setContentType(WebUtilities.getContentType(staticRequest));
			response.setHeader("Cache-Control", CacheType.CONTENT_CACHE.getSettings());

			String param = request.getParameter(WContent.URL_CONTENT_MODE_PARAMETER_KEY);
			if ("inline".equals(param)) {
				response.setHeader("Content-Disposition", "inline; filename=" + fileName);
			} else if ("attach".equals(param)) {
				response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			} else {
				// added "filename=" to comply with https://tools.ietf.org/html/rfc6266
				response.setHeader("Content-Disposition", "filename=" + fileName);
			}

			if (!headersOnly) {
				StreamUtil.copy(resourceStream, response.getOutputStream());
			}
		} catch (IOException e) {
			LOG.warn("Could not process static resource [" + staticRequest + "]. ", e);
			response.reset();
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
	}