Example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

List of usage examples for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Prototype

int SC_MOVED_TEMPORARILY

To view the source code for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Click Source Link

Document

Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.

Usage

From source file:org.josso.gl2.agent.SSOAgentValve.java

/**
 * Perform single-sign-on support processing for this request.
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet error occurs
 *//*from   www . ja v a2 s  .  c om*/
public int invoke(Request request, Response response) throws IOException, ServletException {

    // If this is not an HTTP request and response, just pass them on
    int ret = 0;
    if (!(request instanceof HttpRequest) || !(response instanceof HttpResponse)) {
        //context.invokeNext(request, response);
        ret = Valve.INVOKE_NEXT;
        return ret;
    }

    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();

    if (debug >= 1)
        log("***Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] path="
                + hreq.getPathInfo());
    try {
        container = (Container) request.getContext();
    } catch (Exception e) {
        log("Erreur sur cast container", e);
    }
    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        _agent.setCatalinaContainer(container);

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";
        // T1 si l'appli n'est pas partenaire alors pas de SSO on continue
        if (!_agent.isPartnerApp(vhost, contextPath)) {
            if (debug >= 1)
                log("T1 Context is not a josso partner app : " + hreq.getContextPath());
            hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte");
            ret = Valve.END_PIPELINE;
            return ret;
        } else {
            log("T1 Context IS a josso partner app =" + hreq.getContextPath());
        }

        // T2 ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        //T9
        if (isResourceIgnored(cfg, request)) {
            log("T9 ressource non ssois (accs libre)");
            ret = Valve.INVOKE_NEXT;
            return ret;
        }

        // Get our session ...
        session = getSession(((HttpRequest) request), true);
        testCookieSession(hreq);

        //T3 on revient aprs authentification russie et pour finalisation
        if (_agent.isSSOIDloged(jossoSessionId)) {
            iBoucle++;
            log("T3 SSOAgentValve Info retour authentifi pour " + jossoSessionId + " faire retour vers "
                    + theOriginal);
            //**********************************************************************************************
            localSession = new CatalinaLocalSession(session);
            //T4 on revrifie ma prsence d'une entre SSOID
            SSOAgentRequest r = new CatalinaSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                    jossoSessionId, localSession);
            SingleSignOnEntry entry = _agent.processRequest(r);

            if (debug == 1)
                log("T3 Executed agent acction ACTION_ESTABLISH_SECURITY_CONTEXT");
            // ------------------------------------------------------------------
            // Has a valid user already been authenticated?
            // ------------------------------------------------------------------
            //T3-1
            if (entry != null) {
                if (debug == 1)
                    log("T3-1 Principal '" + entry.principal + "' has already been authenticated");
                // TODO : Not supported
                // (request).setAuthType(entry.authType);
                // (request).setUserPrincipal(entry.principal);
                //T3-2
            } else {
                log("T3-2 No Valid SSO Session, attempt an optional login?");
                // This is a standard anonymous request!

                if (cookie != null) {
                    // cookie is not valid
                    cookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
                    hres.addCookie(cookie);
                }
                //T3-2-1
                if (cookie != null
                        || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) {

                    if (debug == 1)
                        log("T3-2-1 SSO Session is not valid, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    log("T3-2-1 ***On sauve la requte 2 ***");
                    saveRequest((HttpRequest) request, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log("T3-2-1 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    ret = Valve.INVOKE_NEXT;
                    return ret;
                } else {
                    if (debug == 1)
                        log("T3-2-1 SSO cookie is not present, but login optional process is not required");
                }

            }

            try {
                log("Avant sur webProgrammaticLogin -------------" + iBoucle);

                if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) {
                    log("Erreur sur webProgrammaticLogin");
                } else {
                    log("Russite sur webProgrammaticLogin");
                }
                log("Aprs sur webProgrammaticLogin-------------" + iBoucle);
            } catch (Exception err) {
                log("SSOAgentValve Erreur2 finalisation contexte securit", err);
                throw err;
            }
            // propagate the login and logout URLs to
            // partner applications.
            hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
            hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
            hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

            //hres.sendRedirect(theOriginal);
            System.out.println("**********************Termin**********************");
            ret = Valve.INVOKE_NEXT;
            return ret;
        } else {
            log("T3 SSOAgentValve Info retour pas authentifi pour " + jossoSessionId);
            iBoucle = 0;
        }
        String username = processAuthorizationToken(hreq);
        //TA2
        //equivalent  la page de login si pas autoris on passe par l'authent
        if (username == null && getSavedRequestURL(session) == null
                && !hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                && !hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {
            log("TA2 Il faut une authentification pralable (premire URL)! session=" + session.getId());
            //return sendAuthenticateChallenge(msgInfo);
            //return sendAuthenticateChallenge2(msgInfo);
            saveRequest((HttpRequest) request, session);
            theOriginal = getSavedRequestURL(session);
            hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            //response.setHeader("Location", jeVeux);
            hres.sendRedirect(hreq.getContextPath() + "/josso_login/");
            ret = Valve.END_PIPELINE;
            return ret;
        }
        //T4
        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        // /josso_login/ ou /josso_user_login/ c'est pas la page de login qui fait cela ?
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {

            if (debug >= 1)
                log("T4 josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {
                saveLoginBackToURL(hreq, session, true);
            } else {
                saveLoginBackToURL(hreq, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (debug >= 1)
                log("T4 Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
            //question on termine ou on continue
            ret = Valve.END_PIPELINE;
            return ret;

        }
        //T5
        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) {

            if (debug >= 1)
                log("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (debug >= 1)
                log("T5 Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
            hres.addCookie(ssoCookie);

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            ret = Valve.END_PIPELINE;
            return ret;

        }
        //T6
        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        testCookieSession(hreq);
        if (debug >= 1)
            log("T6 Session is: " + session);
        //localSession = new CatalinaLocalSession(session);
        //T7
        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------
        // /josso_authentication/
        if (debug >= 1) {
            log("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) {

            if (debug >= 1)
                log("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            HttpSSOAgentRequest customAuthRequest = new HttpSSOAgentRequest(
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession);

            customAuthRequest.setRequest(hreq);
            customAuthRequest.setResponse(hres);
            customAuthRequest.setContext(request.getContext());

            _agent.processRequest(customAuthRequest);

            ret = Valve.INVOKE_NEXT;
            return ret;
        }
        //T8
        // si pas de cookie de session SSO
        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (debug >= 1)
                log("T8 SSO cookie is not present, verifying optional login process ");
            //T8-1  /josso_security_check
            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (debug >= 1)
                    log("T8-1 " + _agent.getJOSSOSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = this.getSavedRequestURL(session);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                ret = Valve.INVOKE_NEXT;
                return ret;

            }
            //T8-2
            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())) {

                // If saved request is NOT null, we're in the middle of another process ...
                if (!isResourceIgnored(cfg, request) && _agent.isAutomaticLoginRequired(hreq)) {

                    if (debug >= 1)
                        log("T8-2 SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequest((HttpRequest) request, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug >= 1)
                        log("T8-2 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    ret = Valve.END_PIPELINE;
                    return ret;
                } else {
                    if (debug >= 1)
                        log("T8-2 SSO cookie is not present, but login optional process is not required");
                }
            }
            //T8-3
            if (debug >= 1)
                log("T8-3 SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log("T8-3 SSO cookie not present and relaying was not requested, skipping");
                //context.invokeNext(request, response);
                ret = Valve.INVOKE_NEXT;
                return ret;
            }

        }

        // This URI should be protected by SSO, go on ...
        if (debug >= 1)
            log("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("Executing agent...");

        _agent.setCatalinaContainer((Container) request.getContext());
        //T10  /josso_security_check
        // ------------------------------------------------------------------
        // Check if a user has been authenticated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (debug >= 1)
                log("T10 josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            HttpSSOAgentRequest relayRequest;

            relayRequest = new HttpSSOAgentRequest(SSOAgentRequest.ACTION_RELAY, null, localSession,
                    assertionId);
            if (debug >= 1)
                log("T10 Outbound relaying requested for assertion id=" + assertionId + " sessionID="
                        + relayRequest.getSessionId());

            relayRequest.setRequest(hreq);
            relayRequest.setResponse(hres);
            relayRequest.setContext(request.getContext());

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            //T10-1
            if (entry == null) {
                // This is wrong! We should have an entry here!
                if (debug >= 1)
                    log("T10-1 Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }
            //T10-2
            if (debug >= 1)
                log("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (debug >= 1)
                log("T10-2 Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            securityCheck(hreq, hres, entry, cfg, "T10");
            /*try {
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId);
            hres.addCookie(cookie);
            } catch (Exception e) {
            log("Pas de bras pas de chocolat !", e);
            }
            jossoSessionId = entry.ssoId;
            //T10-3
            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(session.getSession());
            if(requestURI == null) {
            requestURI = getSavedRequestURL(session);
            if (requestURI == null) {
                    
            if (cfg.getDefaultResource() != null) {
            requestURI = cfg.getDefaultResource();
            } else {
            // If no saved request is found, redirect to the partner app root :
            requestURI = hreq.getRequestURI().substring(
            0, (hreq.getRequestURI().length() - _agent.getJOSSOSecurityCheckUri().length()));
            }
                    
            // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
            String singlePointOfAccess = _agent.getSinglePointOfAccess();
            if (singlePointOfAccess != null) {
            requestURI = singlePointOfAccess + requestURI;
            } else {
            String reverseProxyHost = hreq.getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
            if (reverseProxyHost != null) {
            requestURI = reverseProxyHost + requestURI;
            }
            }
                    
            if (debug >= 1)
            log("T10-3 No saved request found, using : '" + requestURI + "'");
            }
            }
                    
            clearSavedRequestURLs(session);
            _agent.clearAutomaticLoginReferer(hreq);
            _agent.prepareNonCacheResponse(hres);
            //T10-4
            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
            String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
            if (debug >= 1)
            log("T10-4 Redirecting to post-auth-resource '" + postAuthURL  + "'");
            hres.sendRedirect(postAuthURL);
            } else {
            if (debug >= 1)
            log("T10-4 Redirecting to original '" + requestURI + "'");
            hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            //on garde des fois que ...
            theOriginal = hres.encodeRedirectURL(requestURI);
            }
            _agent.addEntrySSOIDsuccessed(entry.ssoId);
            log("T10 Fin josso_check jossoSessionId="+jossoSessionId);*/
            //c'est pas fini et pas en erreur pourtant ...
            ret = Valve.END_PIPELINE;
            return ret;
        }
        //T11
        // si on arrive la c'est une erreur!
        log("T11 Fin de la boucle validate donc tout va bien");
        ret = Valve.INVOKE_NEXT;
        return ret;
    } catch (Throwable t) {
        //  This is a 'hack' : Because this valve exectues before the ErrorReportingValve, we need to preapare
        // some stuff and invoke the next valve in the chain always ...

        // Store this error, it will be checked by the ErrorReportingValve
        hreq.setAttribute(Globals.EXCEPTION_ATTR, t);

        // Mark this response as error!
        response.setError();

        // Let the next valves work on this
        //context.invokeNext(request, response);
        ret = Valve.END_PIPELINE;

    } finally {
        if (debug >= 1)
            log("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] ret=" + ret);
        //return ret;
    }
    log("retourne ret=" + ret);
    return ret;

}

From source file:org.josso.servlet.agent.JossoFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;
    debug = 1;//  w  ww .ja  v  a 2 s.com
    if (debug == 1)
        log.debug("Processing : " + hreq.getContextPath());

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        //_agent.setCatalinaContainer(container);
        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        // T1 si l'appli n'est pas partenaire alors pas de SSO on continue
        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            logg("T1 Context is not a josso partner app : " + hreq.getContextPath());
            hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte");
            return;
        } else {
            logg("T1 Context IS a josso partner app =" + hreq.getContextPath());
        }

        //T2
        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        //T9
        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            logg("T9 ressource non ssois (accs libre)");
            filterChain.doFilter(hreq, hres);
            return;
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        testCookieSession(hreq);
        //TA1 pas de cookie et on trouve la page de login attendue dans la dclaration du contexte agent
        logg("TA1 uri=" + hreq.getRequestURI() + " se termine par " + cfg.getLoginPage() + " rep="
                + hreq.getRequestURI().endsWith(cfg.getLoginPage()) + " test cookie="
                + testCookie2Session(hreq, session.getId()));
        if (!testCookie2Session(hreq, session.getId()) && hreq.getRequestURI().endsWith(cfg.getLoginPage())) {
            logg("TA1 on demande l'authentification locale on switche vers Josso");
            Cookie gato = newJossoCookie2(hreq.getContextPath(), session.getId(), COOKIE_LOGIN);
            hres.addCookie(gato);
            String loginUrl = _agent.buildLoginUrl(hreq);
            hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            //response.setHeader("Location", jeVeux);
            hres.sendRedirect(loginUrl);
            return;
        }
        //T3 on revient aprs authentification russie et pour finalisation
        if (_agent.isSSOIDloged(jossoSessionId)) {
            iBoucle++;
            logg("T3 Info retour authentifi pour " + jossoSessionId + " faire retour vers " + theOriginal);
            SSOAgentRequest r = doMakeSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                    jossoSessionId, localSession, null, hreq, hres);
            SingleSignOnEntry entry = _agent.processRequest(r);

            if (debug == 1)
                log.debug("Executed agent.");

            // Get session map for this servlet context.
            Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
            if (sessionMap.get(localSession.getWrapped()) == null) {
                // the local session is new so, make the valve listen for its events so that it can
                // map them to local session events.
                // Not supported : session.addSessionListener(this);
                sessionMap.put(session, localSession);
            }

            // ------------------------------------------------------------------
            // Has a valid user already been authenticated?
            // ------------------------------------------------------------------
            if (debug == 1)
                log.debug("Process request for '" + hreq.getRequestURI() + "'");

            if (entry != null) {
                if (debug == 1)
                    log.debug("Principal '" + entry.principal + "' has already been authenticated");
                // TODO : Not supported
                // (request).setAuthType(entry.authType);
                // (request).setUserPrincipal(entry.principal);
            } else {
                log.info("No Valid SSO Session, attempt an optional login?");
                // This is a standard anonymous request!

                if (cookie != null) {
                    // cookie is not valid
                    cookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
                    hres.addCookie(cookie);
                }

                if (cookie != null
                        || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) {

                    if (debug == 1)
                        log.debug("SSO Session is not valid, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (debug == 1)
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }

            }
            try {
                logg("Avant sur webProgrammaticLogin -------------" + iBoucle);

                if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) {
                    logg("Erreur sur webProgrammaticLogin");
                } else {
                    logg("Russite sur webProgrammaticLogin");
                }
                logg("Aprs sur webProgrammaticLogin-------------" + iBoucle);
            } catch (Exception err) {
                logg("SSOAgentValve Erreur2 finalisation contexte securit", err);
                throw new ServletException(err);
            }

            // propagate the login and logout URLs to
            // partner applications.
            hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
            hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
            hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

            // ------------------------------------------------------------------
            // Invoke the next Valve in our pipeline
            // ------------------------------------------------------------------
            filterChain.doFilter(hreq, hres);
        }

        //T4
        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {

            if (debug == 1)
                log.debug("T4 josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {
                saveLoginBackToURL(hreq, session, true);
            } else {
                saveLoginBackToURL(hreq, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (debug == 1)
                log.debug("T4 Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;

        }

        //T5
        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) {

            if (debug == 1)
                log.debug("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (debug == 1)
                log.debug("T5 Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;

        }

        //T6
        testCookieSession(hreq);
        //T7
        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (debug == 1) {
            log.debug("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) {

            if (debug == 1) {
                log.debug("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);

            _agent.processRequest(customAuthRequest);

            return;
        }
        //T8
        // si pas de cookie de session SSO
        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (debug == 1)
                log.debug("T8 SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (debug == 1)
                    log.debug("T8-1 " + _agent.getJOSSOSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(session);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq)) {

                    if (debug == 1)
                        log.debug("T8-2 SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log.debug("T8-2 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (debug == 1)
                        log.debug("T8-2 SSO cookie is not present, but login optional process is not required");
                }
            }

            if (debug == 1)
                log.debug("T8-3 SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("T8-3 SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // This URI should be protected by SSO, go on ...
        if (debug == 1)
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("Executing agent...");
        //T10  /josso_security_check
        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (debug == 1)
                log.debug("T10 josso_security_check received for uri '" + hreq.getRequestURI()
                        + "' assertion id '" + hreq.getParameter("josso_assertion_id"));

            assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            GenericServletSSOAgentRequest relayRequest;

            if (debug == 1)
                log.debug("T10 Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(SSOAgentRequest.ACTION_RELAY,
                    null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error("T10-1 Outbound relaying failed for assertion id [" + assertionId
                        + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (debug == 1)
                log.debug("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (debug == 1)
                log.debug("T10-2 Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId
                        + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId);
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(session);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(session);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJOSSOSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (debug == 1)
                        log.debug("T10 No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(session);
            _agent.clearAutomaticLoginReferer(hreq);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (debug == 1)
                    log.debug("T10 Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (debug == 1)
                    log.debug("T10 Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }
            _agent.addEntrySSOIDsuccessed(entry.ssoId, entry.getPrincipal().getName());
            return;
        }

    } finally {
        if (debug == 1)
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:org.kuali.test.utils.Utils.java

public static boolean isRedirectResponse(int status) {
    return ((status == HttpServletResponse.SC_MOVED_TEMPORARILY)
            || (status == HttpServletResponse.SC_MOVED_PERMANENTLY)
            || (status == HttpServletResponse.SC_SEE_OTHER));

}

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to
 * be made/*from  ww w .  j  av a  2s .c o  m*/
 * @param httpServletResponse An object by which we can send the proxied
 * response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has
 * occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }

    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /*
            * 300
            */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /*
                                                                              * 304
                                                                              */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                    httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                            nameValue[1]);
                    debug("redirecting: store jsessionid: " + nameValue[1]);
                } else {
                    Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                    cookie.setPath("/");
                    //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                    httpServletResponse.addCookie(cookie);
                }
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else if (header.getName().equals("Set-Cookie")) {
            String[] cookieDetails = header.getValue().split(";");
            String[] nameValue = cookieDetails[0].split("=");
            if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                        nameValue[1]);
                debug("redirecting: store jsessionid: " + nameValue[1]);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:org.sakaiproject.entitybroker.util.request.RequestUtils.java

/**
 * Handles the redirect to a URL from the current location,
 * the URL should be relative for a forward, otherwise it will be a redirect <br/>
 * NOTE: You should perform no actions after call this method,
 * you should simply pass control back to the handler
 * @param redirectURL the URL to redirect to (relative or absolute)
 * @param forward if false, use redirect (this should be the default), 
 * if true use forward, note that we can only forward from your webapp back to your servlets and
 * a check will be performed to see if this is the case, if it is not
 * (anything with a "http", a non-matching prefix, and anything with a query string) will be switched to redirect automatically
 * @param req the current request//  ww  w  . j  a  va 2  s. c  o m
 * @param res the current response
 * @throws IllegalArgumentException is the params are invalid
 */
public static void handleURLRedirect(String redirectURL, boolean forward, HttpServletRequest req,
        HttpServletResponse res) {
    if (redirectURL == null || "".equals(redirectURL)) {
        throw new IllegalArgumentException("The redirect URL must be set and cannot be null");
    }
    if (req == null || res == null) {
        throw new IllegalArgumentException("The request and response must be set and cannot be null");
    }
    if (redirectURL.startsWith("http:") || redirectURL.startsWith("https:")
            || RequestUtils.containsQueryString(redirectURL)) {
        forward = false;
    } else {
        // we allow forwarding ONLY if the current webapp path matches the redirect path
        String webapp = req.getContextPath();
        if (webapp != null && webapp.length() > 0) {
            if (redirectURL.startsWith(webapp + "/")) {
                redirectURL = redirectURL.substring(webapp.length());
                forward = true;
            } else if (redirectURL.length() > 1 && redirectURL.startsWith(webapp.substring(1) + "/")) {
                redirectURL = redirectURL.substring(webapp.length() - 1);
                forward = true;
            } else {
                forward = false;
            }
        }
    }

    if (forward) {
        // check for infinite forwarding
        String curRedirect = DIVIDER + redirectURL + DIVIDER;
        if (req.getAttribute(ENTITY_REDIRECT_CHECK) != null) {
            String redirectCheck = (String) req.getAttribute(ENTITY_REDIRECT_CHECK);
            if (redirectCheck.contains(curRedirect)) {
                throw new IllegalStateException("Infinite forwarding loop detected with attempted redirect to ("
                        + redirectURL + "), path to failure: "
                        + redirectCheck.replace(DIVIDER + DIVIDER, " => ").replace(DIVIDER, "") + " => "
                        + redirectURL);
            }
            redirectCheck += curRedirect;
            req.setAttribute(ENTITY_REDIRECT_CHECK, redirectCheck);
        } else {
            req.setAttribute(ENTITY_REDIRECT_CHECK, curRedirect);
        }

        RequestDispatcher rd = req.getRequestDispatcher(redirectURL);
        try {
            rd.forward(req, res);
        } catch (ServletException e) {
            throw new RuntimeException(
                    "Failure with servlet while forwarding to '" + redirectURL + "': " + e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(
                    "Failure with encoding while forwarding to '" + redirectURL + "': " + e.getMessage(), e);
        }
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        try {
            res.sendRedirect(redirectURL);
        } catch (IOException e) {
            throw new RuntimeException(
                    "Failure with encoding while redirecting to '" + redirectURL + "': " + e.getMessage(), e);
        }
    }
}

From source file:org.tobarsegais.webapp.RedirectFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (StringUtils.isEmpty(domain) || !(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
    } else {/*  w ww . j  ava 2s. co  m*/
        final HttpServletRequest req = (HttpServletRequest) request;
        final HttpServletResponse resp = (HttpServletResponse) response;
        final String serverName = req.getServerName();
        if (domain.equalsIgnoreCase(serverName)) {
            chain.doFilter(request, response);
        } else {
            StringBuffer requestURL = req.getRequestURL();
            int index = requestURL.indexOf(serverName);
            requestURL.replace(index, index + serverName.length(), domain);
            final String queryString = req.getQueryString();
            if (queryString != null) {
                requestURL.append('?').append(queryString);
            }
            resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            resp.setHeader("Location", requestURL.toString());
        }
    }
}

From source file:org.uc.sidgrid.oauth.AuthorizationServlet.java

private void returnToConsumer(HttpServletRequest request, HttpServletResponse response, OAuthAccessor accessor)
        throws IOException, ServletException {
    // send the user back to site's callBackUrl
    String callback = request.getParameter("oauth_callback");
    log.info("callback is:" + callback);
    if ("none".equals(callback) && accessor.consumer.callbackURL != null
            && accessor.consumer.callbackURL.length() > 0) {
        // first check if we have something in our properties file
        callback = accessor.consumer.callbackURL;
    }//from   ww  w. ja va 2s . co m
    if ("none".equals(callback)) {
        // no call back it must be a client
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("You have successfully authorized '" + accessor.consumer.getProperty("description")
                + "'. Please close this browser window and click continue" + " in the client.");
        out.close();
    } else {
        // if callback is not passed in, use the callback from config
        if (callback == null || callback.length() <= 0)
            callback = accessor.consumer.callbackURL;
        String token = accessor.requestToken;
        if (token != null) {
            callback = OAuth.addParameters(callback, "oauth_token", token);
        }

        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        log.info("before setting location:" + callback);
        response.setHeader("Location", callback);
    }
}

From source file:org.webcurator.ui.tools.controller.BrowseController.java

/**
 * The handle method is the entry method into the browse controller.
 */// ww  w  .j a v a  2 s .  c  om
@Override
protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm,
        BindException errors) throws Exception {

    // Cast the command to the correct command type.
    BrowseCommand command = (BrowseCommand) comm;

    // Build a command with the items from the URL.
    String base = req.getContextPath() + req.getServletPath();

    String line = req.getRequestURI().substring(base.length());

    Matcher matcher = p.matcher(line);
    if (matcher.matches()) {
        command.setHrOid(Long.parseLong(matcher.group(1)));
        command.setResource(matcher.group(2));
    }

    if (req.getQueryString() != null) {
        command.setResource(command.getResource() + "?" + req.getQueryString());
    }

    // Check if the command is prefixed with a forward slash.
    if (command.getResource().startsWith("/")) {
        command.setResource(command.getResource().substring(1));
    }

    // Now make sure that the domain name is in lowercase.
    Pattern urlBreakerPattern = Pattern.compile("(.*?)://(.*?)/(.*)");
    Matcher urlBreakerMatcher = urlBreakerPattern.matcher(command.getResource());
    if (urlBreakerMatcher.matches()) {
        command.setResource(urlBreakerMatcher.group(1) + "://" + urlBreakerMatcher.group(2).toLowerCase() + "/"
                + urlBreakerMatcher.group(3));
    }

    // Load the HarvestResourceDTO from the quality review facade.
    HarvestResourceDTO dto = qualityReviewFacade.getHarvestResourceDTO(command.getHrOid(),
            command.getResource());

    // If the resource is not found, go to an error page.
    if (dto == null) {
        log.debug("Resource not found: " + command.getResource());
        return new ModelAndView("browse-tool-not-found", "resourceName", command.getResource());
    } else {
        Header[] headers = null;
        // catch any DigitalAssetStoreException and log assumptions
        try {
            headers = qualityReviewFacade.getHttpHeaders(dto);
        } catch (DigitalAssetStoreException e) {
            log.info("Failed to get header for ti " + dto.getTargetInstanceOid());
            // throw new DigitalAssetStoreException(e);
        } catch (Exception e) {
            log.error("Unexpected exception encountered when retrieving WARC headers for ti "
                    + dto.getTargetInstanceOid());
            throw new Exception(e);
        }

        // Send the headers for a redirect.
        if (dto.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY
                || dto.getStatusCode() == HttpServletResponse.SC_MOVED_PERMANENTLY) {
            res.setStatus(dto.getStatusCode());
            String location = getHeaderValue(headers, "Location");
            if (location != null) {
                String newUrl = browseHelper.convertUrl(command.getHrOid(), command.getResource(), location);
                res.setHeader("Location", newUrl);
            }
        }

        // Get the content type.
        String realContentType = getHeaderValue(headers, "Content-Type");
        String simpleContentType = this.getSimpleContentType(realContentType);

        String charset = null;
        if (realContentType != null) {
            Matcher charsetMatcher = CHARSET_PATTERN.matcher(realContentType);
            if (charsetMatcher.find()) {
                charset = charsetMatcher.group(1);
                log.debug("Desired charset: " + charset + " for " + command.getResource());
            } else {
                log.debug("No charset: " + charset + " (" + command.getResource());
            }
        }

        // If the content has been registered with the browseHelper to
        // require replacements, load the content and perform the
        // necessary replacements.
        if (browseHelper.isReplaceable(simpleContentType)) {
            StringBuilder content = null;

            try {
                content = readFile(dto, charset);
            } catch (DigitalAssetStoreException e) {
                if (log.isWarnEnabled()) {
                    log.warn(e.getMessage());
                }
            }
            ModelAndView mav = new ModelAndView("browse-tool-html");

            if (content != null) {
                // We might need to use a different base URL if a BASE HREF
                // tag
                // is used. We use the TagMagix class to perform the search.
                // Note that TagMagix leaves leading/trailing slashes on the
                // URL, so we need to do that
                String baseUrl = command.getResource();
                Pattern baseUrlGetter = BrowseHelper.getTagMagixPattern("BASE", "HREF");
                Matcher m = baseUrlGetter.matcher(content);
                if (m.find()) {
                    String u = m.group(1);
                    if (u.startsWith("\"") && u.endsWith("\"") || u.startsWith("'") && u.endsWith("'")) {

                        // Ensure the detected Base HREF is not commented
                        // out (unusual case, but we have seen it).
                        int lastEndComment = content.lastIndexOf("-->", m.start());
                        int lastStartComment = content.lastIndexOf("<!--", m.start());
                        if (lastStartComment < 0 || lastEndComment > lastStartComment) {
                            baseUrl = u.substring(1, u.length() - 1);
                        }
                    }

                }

                browseHelper.fix(content, simpleContentType, command.getHrOid(), baseUrl);
                mav.addObject("content", content.toString());
            } else {
                mav.addObject("content", "");
            }

            mav.addObject("Content-Type", realContentType);
            return mav;
        }

        // If there are no replacements, send the content back directly.
        else {
            if (dto.getLength() > MAX_MEMORY_SIZE) {
                Date dt = new Date();
                File f = qualityReviewFacade.getResource(dto);
                ModelAndView mav = new ModelAndView("browse-tool-other");
                mav.addObject("file", f);
                mav.addObject("contentType", realContentType);

                log.info("TIME TO GET RESOURCE(old): " + (new Date().getTime() - dt.getTime()));
                return mav;
            } else {
                Date dt = new Date();
                byte[] bytesBuffer = null;
                try {
                    bytesBuffer = qualityReviewFacade.getSmallResource(dto);
                } catch (org.webcurator.core.exceptions.DigitalAssetStoreException e) {
                    if (log.isWarnEnabled()) {
                        log.warn("Could not retrieve resource: " + dto.getName());
                    }
                }
                ModelAndView mav = new ModelAndView("browse-tool-other-small");
                mav.addObject("bytesBuffer", bytesBuffer);
                mav.addObject("contentType", realContentType);
                log.debug("TIME TO GET RESOURCE(new): " + (new Date().getTime() - dt.getTime()));
                return mav;
            }
        }
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.inbound.IdentityServlet.java

/**
 * Process the {@link HttpIdentityResponse} and {@link HttpServletResponse}.
 *
 * @param httpIdentityResponse {@link HttpIdentityResponse}
 * @param response {@link HttpServletResponse}
 *///from   www  . j ava2  s .  c o m
private void processHttpResponse(HttpIdentityResponse httpIdentityResponse, HttpServletResponse response) {

    for (Map.Entry<String, String> entry : httpIdentityResponse.getHeaders().entrySet()) {
        response.addHeader(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<String, Cookie> entry : httpIdentityResponse.getCookies().entrySet()) {
        response.addCookie(entry.getValue());
    }
    if (StringUtils.isNotBlank(httpIdentityResponse.getContentType())) {
        response.setContentType(httpIdentityResponse.getContentType());
    }
    if (httpIdentityResponse.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY) {
        try {
            sendRedirect(response, httpIdentityResponse);
        } catch (IOException e) {
            throw FrameworkRuntimeException.error("Error occurred while redirecting response", e);
        }
    } else {
        response.setStatus(httpIdentityResponse.getStatusCode());
        try {
            PrintWriter out = response.getWriter();
            if (StringUtils.isNotBlank(httpIdentityResponse.getBody())) {
                out.print(httpIdentityResponse.getBody());
            }
        } catch (IOException e) {
            throw FrameworkRuntimeException.error("Error occurred while getting Response writer object", e);
        }
    }
}

From source file:org.wso2.carbon.identity.sso.cas.request.SAMLIdentityRequestFactory.java

@Override
public HttpIdentityResponse.HttpIdentityResponseBuilder handleException(FrameworkClientException exception,
        HttpServletRequest request, HttpServletResponse response) {

    HttpIdentityResponse.HttpIdentityResponseBuilder builder = new HttpIdentityResponse.HttpIdentityResponseBuilder();
    String redirectURL = CASSSOUtil.getNotificationEndpoint();
    Map<String, String[]> queryParams = new HashMap();
    //TODO Send status codes rather than full messages in the GET request
    try {/*from  w w  w. j  av a 2 s.  com*/
        queryParams.put(CASSSOConstants.STATUS,
                new String[] { URLEncoder.encode(((SAML2ClientException) exception).getExceptionStatus(),
                        StandardCharsets.UTF_8.name()) });
        queryParams.put(CASSSOConstants.STATUS_MSG,
                new String[] { URLEncoder.encode(((SAML2ClientException) exception).getExceptionMessage(),
                        StandardCharsets.UTF_8.name()) });
        if (exception.getMessage() != null) {
            queryParams.put(CASSSOConstants.SAML_RESP,
                    new String[] { URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8.name()) });
        }
        if (((SAML2ClientException) exception).getACSUrl() != null) {
            queryParams.put(CASSSOConstants.SERVICE, new String[] { URLEncoder
                    .encode(((SAML2ClientException) exception).getACSUrl(), StandardCharsets.UTF_8.name()) });
        }
        builder.setParameters(queryParams);
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while encoding query parameters.", e);
        }
    }
    builder.setRedirectURL(redirectURL);
    builder.setStatusCode(HttpServletResponse.SC_MOVED_TEMPORARILY);
    return builder;
}