Return true if setRedirect(true) was called on the previous request.
Precondition: doPrePhaseActions() must have been called on restore view phase.
@param facesContext
@return
963727
private boolean _isRedirectTrueOnPreviousRequest(FacesContext facesContext)
    {
        ExternalContext externalContext = facesContext.getExternalContext();
        Map<String, Object> requestMap = externalContext.getRequestMap();
        Boolean redirect = (Boolean) requestMap.get(FLASH_PREVIOUS_REQUEST_REDIRECT);
        
        return Boolean.TRUE.equals(redirect);
    }
996893
@Override
    public Result call(final Route route, final RequestContext context) throws Exception {
        URI redirectedURI = rewriteURI(context.request());
        logger.debug("Redirecting request - rewriting {} to {}", context.request().uri(), redirectedURI);
        if (redirectedURI == null) {
            return onRewriteFailed(context);
        }
        return Results.redirect(redirectedURI.toString());
    }
801507
static boolean isRedirect(int status) {
	return status == STATUS_REDIRECT_FOUND || status == STATUS_REDIRECT_MOVED_PERMANENTLY || status == STATUS_REDIRECT_SEE_OTHER
		|| status == STATUS_REDIRECT_TEMPORARY_REDIRECT;

    }
1375030
private boolean isDelegatedFacesServlet(String className)
    {
        if (className == null)
        {
            // The class name can be null if this is e.g., a JSP mapped to
            // a servlet.

            return false;
        }
        try
        {
            Class<?> clazz = Class.forName(className);
            return DELEGATED_FACES_SERVLET_CLASS.isAssignableFrom(clazz);
        }
        catch (ClassNotFoundException cnfe)
        {
            return false;
        }
    }
486946
private void _saveRedirectValue(FacesContext facesContext)
    {
        ExternalContext externalContext = facesContext.getExternalContext();
        
        // This request contains a redirect. This condition is in general 
        // triggered by a NavigationHandler. After a redirect all request scope
        // values get lost, so in order to preserve this value we need to
        // pass it between request. One strategy is use a cookie that is never sent
        // to the client. Other alternative is use the session map.
        // See _restoreRedirectValue() for restoring this value.
        HttpServletResponse httpResponse = ExternalContextUtils
                .getHttpServletResponse(externalContext);
        if (httpResponse != null)
        {
            Cookie cookie = _createFlashCookie(FLASH_REDIRECT, "true", externalContext);
            httpResponse.addCookie(cookie);
        }
        else
        {
            externalContext.getSessionMap().put(FLASH_REDIRECT, true);
        }
    }
660169
private void redirectToLoginPage(FacesContext context, UIViewRoot viewRoot) {
        Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
        preLoginEvent.fire(new PreLoginEvent(context, sessionMap));
        LoginView loginView = viewConfigStore.getAnnotationData(viewRoot.getViewId(), LoginView.class);
        if (loginView == null || loginView.value() == null || loginView.value().isEmpty()) {
            log.debug("Returning 401 response (login required)");
            context.getExternalContext().setResponseStatus(401);
            context.responseComplete();
            return;
        }
        String loginViewId = loginView.value();
        log.debugf("Redirecting to configured LoginView %s", loginViewId);
        NavigationHandler navHandler = context.getApplication().getNavigationHandler();
        navHandler.handleNavigation(context, "", loginViewId);
        context.renderResponse();
    }
918458
private boolean processRedirectResponse(final HttpMethod method)
     throws RedirectException {
		//get the location header to find out where to redirect to
		Header locationHeader = method.getResponseHeader("location");
		if (locationHeader == null) {
			// got a redirect response, but no location header
			LOG.error("Received redirect response " + method.getStatusCode()
					+ " but no location header");
			return false;
		}
		String location = locationHeader.getValue();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Redirect requested to location '" + location + "'");
		}
        
		//rfc2616 demands the location value be a complete URI
		//Location       = "Location" ":" absoluteURI
		URI redirectUri = null;
		URI currentUri = null;

		try {
			currentUri = new URI(
				this.conn.getProtocol().getScheme(),
				null,
                this.conn.getHost(), 
                this.conn.getPort(), 
				method.getPath()
			);
			
            String charset = method.getParams().getUriCharset();
            redirectUri = new URI(location, true, charset);
			
            if (redirectUri.isRelativeURI()) {
				if (this.params.isParameterTrue(HttpClientParams.REJECT_RELATIVE_REDIRECT)) {
					LOG.warn("Relative redirect location '" + location + "' not allowed");
					return false;
				} else { 
					//location is incomplete, use current values for defaults
					LOG.debug("Redirect URI is not absolute - parsing as relative");
					redirectUri = new URI(currentUri, redirectUri);
				}
			} else {
                // Reset the default params
                method.getParams().setDefaults(this.params);
            }
            method.setURI(redirectUri);
            hostConfiguration.setHost(redirectUri);
		} catch (URIException ex) {
            throw new InvalidRedirectLocationException(
                    "Invalid redirect location: " + location, location, ex);
		}

        if (this.params.isParameterFalse(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS)) {
            if (this.redirectLocations == null) {
                this.redirectLocations = new HashSet<URI>();
            }
            this.redirectLocations.add(currentUri);
            try {
                if(redirectUri.hasQuery()) {
                    redirectUri.setQuery(null);
                }
            } catch (URIException e) {
                // Should never happen
                return false;
            }

            if (this.redirectLocations.contains(redirectUri)) {
                throw new CircularRedirectException("Circular redirect to '" +
                    redirectUri + "'");
            }
        }

		if (LOG.isDebugEnabled()) {
			LOG.debug("Redirecting from '" + currentUri.getEscapedURI()
				+ "' to '" + redirectUri.getEscapedURI());
		}
        //And finally invalidate the actual authentication scheme
                method.getHostAuthState().invalidate(); 
                method.getProxyAuthState().invalidate(); 
		return true;
	}
602020
@Override
    public Response before(FilterChain chain, Context context) {
        SessionFacade session = context.getSession(false);//true?
        
        if (context.httpMethod() == HttpMethod.GET) {
            String path = context.path();
            if (path.equals(notLoggedInRedirect)) {
                // redirect to a known location if the user is actually logged in
                if (session != null && createSubject(context).hasRole(role))
                    return ResponseBuilder.redirect("/");
                
                // fall through as the user is not logged in
                return chain.before(context);
            } else if (path.equals(logout)) {
                if (session != null) {
                    Subject subject = session.get(SESSION_USER, Subject.class);
                    if (subject != null) {
                        subject.logout();
                        session.remove(SESSION_USER);
                    }
                }
                return chain.before(context);
            }
        }
        // is a session already active?
        // - if not -> surely an user cannot already have logged in (disregarding cookies at this time)
        // does the session have a subject associated?
        //  - if not -> an user is of course not authenticated
        // the subject exists
        // - (should we ask if authenticated, or is this auth enough?)
        // does the subject have the required role?
        // - if not -> return not authorized response
        
        String username = context.getParameter("username");
        String password = context.getParameter("password");
        String remember = context.getParameter("rememberMe"); //TODO handle cookie independently with framework
        
        System.out.println(MessageFormat.format("username {0} + pass {1} + remember {2} --  ip {3},{4},{5}", username, password, remember, context.ipAddress(), context.remoteAddress(), context.remoteHost()));

        // get the current user
        // if not already existing, create and save user
        if (session == null) {
            session = context.getSession(true);
            
//            context.finalizeResponse(ResponseBuilder.redirect(notLoggedInRedirect));
//            return null;//TODO Response with login html
        }
        
        
        
        //according to AbstractShiroFilter:
        //get request + response (meaning Context)
        //create a subject
        //updateSessionLastAccessTime
        Subject sub = createSubject(context);
        updateSessionLastAccessTime(sub);
        session.put(SESSION_USER, sub);
        
        //Only trust cookies for a period of time
        //Perhaps have the date as a part of the principal (or an extra DatePrincipal)
        //When date is exceeded re-login
        //The IP<->Cookie relationship also has to be taken into consideration
        //Perhaps this also ought to be a principal (IpPrincipal)
        System.out.println("is remembered? " + sub.isRemembered());
//        System.out.println(sub.getPrincipals().getPrimaryPrincipal());
        
        Subject subject = sub;
/*        Subject subject = session.get(SESSION_USER, Subject.class);
        if (subject == null) {
            ContextImpl c = (ContextImpl)context;
            subject = new WebSubject.Builder(c.getOriginalRequest(), c.getOriginalResponse())
//                            .sessionId(session.getId())
                            .host(context.ipAddress())
                            .sessionCreationEnabled(false)
                            .buildSubject();
//            ThreadContext.bind(subject);
            session.put(SESSION_USER, subject);
//            context.finalizeResponse(ResponseBuilder.redirect(notLoggedInRedirect));
//            return null;
        }*/
        
        if (!subject.isAuthenticated()) {
            
            System.out.println("not AUTH");
            
            if (context.httpMethod() == HttpMethod.POST) {
            
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setHost(context.host());
                token.setRememberMe(context.getParameter("rememberMe") != null); //TODO rememberme needs to be implemented manually
                try {
    //                SecurityUtils.getSecurityManager().login(subject, token);
                    subject.login(token);
                    
                } catch ( UnknownAccountException | IncorrectCredentialsException ice ) {
                    //UnknownAccountException:       username wasn't in the system, show them an error message?
                    //IncorrectCredentialsException: password didn't match, try again?
                    context.setFlash("credentials", "not match");
                    return  ResponseBuilder.redirect(notLoggedInRedirect + "?credentials");//add flash telling the credentials were not correct
                } catch ( LockedAccountException lae ) {
                    //account for that username is locked - can't login.  Show them a message?
                    lae.printStackTrace();
                } catch ( AuthenticationException ae ) {
                    //unexpected condition - error?
                    ae.printStackTrace();
                }
            //context.finalizeResponse(ResponseBuilder.noBody(401));// README could actually throw an exception instead
            } else {
                //save the path for later use
                session.put(SESSION_REQUESTED_PATH, context.path());
                return ResponseBuilder.redirect(notLoggedInRedirect);
            }
        }
        
        System.out.println(subject.getPrincipal() + " is AUTH ("+role+") " + subject.hasRole(role));
        
        
        //login was successful (whether the subject is authenticated or not)
        
        if (subject.hasRole(role)) {
            String location = session.get(SESSION_REQUESTED_PATH, String.class);
            session.remove(SESSION_REQUESTED_PATH);
            if (location != null)
                return ResponseBuilder.redirect(location);
            else
                return chain.before(context);
                //README Redirect to a 'defaultLoginWhenLocationNotFound'?
                //return ResponseBuilder.redirect("/");
        }
            //if not auth
        return ResponseBuilder.redirect(notAuthRedirect);
            
    }
563328
protected boolean needsToBeRefreshed(DefaultFacelet facelet)
    {
        // if set to 0, constantly reload-- nocache
        if (_refreshPeriod == NO_CACHE_DELAY)
        {
            return true;
        }

        // if set to -1, never reload
        if (_refreshPeriod == INFINITE_DELAY)
        {
            return false;
        }

        long target = facelet.getCreateTime() + _refreshPeriod;
        if (System.currentTimeMillis() > target)
        {
            // Should check for file modification

            URLConnection conn = null;
            try
            {
                conn = facelet.getSource().openConnection();
                long lastModified = ResourceLoaderUtils.getResourceLastModified(conn);

                return lastModified == 0 || lastModified > target;
            }
            catch (IOException e)
            {
                throw new FaceletException("Error Checking Last Modified for " + facelet.getAlias(), e);
            }
            finally
            {
                // finally close input stream when finished, if fails just continue.
                if (conn != null)
                {
                    try 
                    {
                        InputStream is = conn.getInputStream();
                        if (is != null)
                        {
                            is.close();
                        }
                    }
                    catch (IOException e)
                    {
                        // Ignore 
                    }
                }
            }
        }

        return false;
    }
525393
public boolean isActive()
    {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null)
        {
            return facesContext.getViewRoot() != null;
        }
        else
        {
            // No FacesContext means no view scope active.
            return false;
        }
    }
791238
private function mustRedirect(ServerRequestInterface $request): bool
    {
        if ($this->redirect === false) {
            return false;
        }

        return !$this->checkHttpsForward || (
            $request->getHeaderLine('X-Forwarded-Proto') !== 'https' &&
            $request->getHeaderLine('X-Forwarded-Port') !== '443'
        );
    }
1292862
protected boolean isRedrawNecessary() {
        if (this.redrawNeeded || this.prevMapPosition == null) {
            return true;
        }

        MapPosition currentMapPosition = this.mapViewPosition.getMapPosition();
        if (currentMapPosition.zoomLevel != this.prevMapPosition.zoomLevel) {
            return true;
        }

        double latitudeDiff = Math.abs(currentMapPosition.latLong.latitude - this.prevMapPosition.latLong.latitude);
        return latitudeDiff > LATITUDE_REDRAW_THRESHOLD;
    }
504756
public static boolean isAllowed(ServletContext servletContext, ServletRequest request) {
		return
			Boolean.parseBoolean(servletContext.getInitParameter(ENABLE_INIT_PARAM))
			&& isAllowedAddr(request.getRemoteAddr())
		;
	}
675469
public FacesConfigRedirectRedirectParamType<FacesConfigRedirectType<T>> getOrCreateRedirectParam()
   {
      List<Node> nodeList = childNode.get("redirect-param");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new FacesConfigRedirectRedirectParamTypeImpl<FacesConfigRedirectType<T>>(this, "redirect-param", childNode, nodeList.get(0));
      }
      return createRedirectParam();
   }
1038948
private boolean isFacesConfigPresent(ServletContext servletContext)
    {
        try
        {
            // 1. A faces-config.xml file is found in WEB-INF
            if (servletContext.getResource(FACES_CONFIG_RESOURCE) != null)
            {
                return true;
            }

            // 4. The javax.faces.CONFIG_FILES context param is declared in web.xml or web-fragment.xml.
            // check for alternate faces-config files specified by javax.faces.CONFIG_FILES
            String configFilesAttrValue = servletContext.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
            if (configFilesAttrValue != null)
            {
                String[] configFiles = configFilesAttrValue.split(",");
                for (String file : configFiles)
                {
                    if (servletContext.getResource(file.trim()) != null)
                    {
                        return true;
                    }
                }
            }

            // 2. A faces-config.xml file is found in the META-INF directory of a jar in the 
            //    application's classpath.
            // 3. A filename ending in .faces-config.xml is found in the META-INF directory of a jar in 
            //    the application's classpath.
            // To do this properly it is necessary to use some SPI interfaces MyFaces already has, to 
            // deal with OSGi and other
            // environments properly.
            ExternalContext externalContext = new StartupServletExternalContextImpl(servletContext, true);
            FacesConfigResourceProviderFactory factory = FacesConfigResourceProviderFactory.
                getFacesConfigResourceProviderFactory(externalContext);
            FacesConfigResourceProvider provider = factory.createFacesConfigResourceProvider(externalContext);
            Collection<URL> metaInfFacesConfigUrls =  provider.getMetaInfConfigurationResources(externalContext);
            
            if (metaInfFacesConfigUrls != null && !metaInfFacesConfigUrls.isEmpty())
            {
                return true;
            }
            
            return false;
        }
        catch (Exception e)
        {
            return false;
        }
    }
1189149
private boolean isFresh(final YokeRequest request) {
        // defaults
        boolean etagMatches = true;
        boolean notModified = true;

        // fields
        String modifiedSince = request.getHeader("if-modified-since");
        String noneMatch = request.getHeader("if-none-match");
        String[] noneMatchTokens = null;
        String lastModified = request.response().getHeader("last-modified");
        String etag = request.response().getHeader("etag");

        // unconditional request
        if (modifiedSince == null && noneMatch == null) {
            return false;
        }

        // parse if-none-match
        if (noneMatch != null) {
            noneMatchTokens = noneMatch.split(" *, *");
        }

        // if-none-match
        if (noneMatchTokens != null) {
            etagMatches = false;
            for (String s : noneMatchTokens) {
                if (etag.equals(s) || "*".equals(noneMatchTokens[0])) {
                    etagMatches = true;
                    break;
                }
            }
        }

        // if-modified-since
        if (modifiedSince != null) {
            try {
                Date modifiedSinceDate = parse(modifiedSince);
                Date lastModifiedDate = parse(lastModified);
                notModified = lastModifiedDate.getTime() <= modifiedSinceDate.getTime();
            } catch (ParseException e) {
                notModified = false;
            }
        }

        return etagMatches && notModified;
    }
600314
@Override
    public void doPrePhaseActions(FacesContext facesContext)
    {
        if (!_flashScopeDisabled)
        {
            final PhaseId currentPhaseId = facesContext.getCurrentPhaseId();
        
            if (PhaseId.RESTORE_VIEW.equals(currentPhaseId))
            {
                // restore the redirect value
                // note that the result of this method is used in many places, 
                // thus it has to be the first thing to do
                _restoreRedirectValue(facesContext);
            
                // restore the FlashMap token from the previous request
                // and create a new token for this request
                _manageFlashMapTokens(facesContext);
            
                // try to restore any saved messages
                _restoreMessages(facesContext);
            }
        }
    }