Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

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

Introduction

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

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:fll.web.developer.ReplaceChallengeDescriptor.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }/*from ww w .  java  2s. co m*/

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final Document curDoc = ApplicationAttributes.getChallengeDocument(application);

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // create a new empty database from an XML descriptor
        final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldoc");

        final Document newDoc = ChallengeParser
                .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

        final String compareMessage = ChallengeParser.compareStructure(curDoc, newDoc);
        if (null == compareMessage) {
            GenerateDB.insertOrUpdateChallengeDocument(newDoc, connection);
            application.setAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT, newDoc);
            message.append("<p><i>Successfully replaced challenge descriptor</i></p>");
        } else {
            message.append("<p class='error'>");
            message.append(compareMessage);
            message.append("</p>");
        }
    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOGGER.error(fue, fue);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error talking to the database: " + sqle.getMessage() + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error talking to the database", sqle);
    } finally {
        SQLFunctions.close(connection);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));

}

From source file:org.josso.gateway.signon.LoginAction.java

/**
 * Logins the user in the SSO infrastructure
 *///from  w  ww. j  a v  a 2  s. c  o m
protected ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {
    try {

        SSOGateway gwy = getSSOGateway();

        Credential[] c = getCredentials(request);

        try {
            // 1 - Handle Outbound relaying by generating an assertion for the authentication request
            SSOContext ctx = SSOContext.getCurrent();
            AuthenticationAssertion authAssertion = gwy.assertIdentity(c, ctx.getScheme());

            String sessionId = authAssertion.getSSOSessionId();
            SSOSession session = gwy.findSession(sessionId);

            // Cookie ssoCookie = newJossoCookie(request.getContextPath(), session.getProcessId());
            // response.addCookie(ssoCookie);

            storeSSOInformation(request, response, session);

            if (logger.isDebugEnabled())
                logger.debug("[login()], authentication successfull.");

            // 2 - Restore BACK TO URL ...
            String back_to = this.getBackTo(request, session, authAssertion);
            if (back_to == null) {

                // Return to controller, if we do not have a back-to url, add more information to the context ;)
                SSOUser user = gwy.findUserInSession(sessionId);
                SSORole[] roles = gwy.findRolesByUsername(user.getName());

                // so that pages can access this bean
                request.setAttribute(KEY_JOSSO_SESSION, session);
                request.setAttribute(KEY_JOSSO_USER, user);
                request.setAttribute(KEY_JOSSO_USER_ROLES, roles);

                return mapping.findForward("login-result");
            }

            // If authentication succeds, remove al SSO session data.
            this.clearSSOParameters(request);

            // We're going back to the partner app.
            if (logger.isDebugEnabled())
                logger.debug("[login()], Redirecting user to : " + back_to);

            response.sendRedirect(response.encodeRedirectURL(back_to));

            return null; // No forward is needed, we perfomed a 'sendRedirect'.

        } catch (AuthenticationFailureException e) {

            if (logger.isDebugEnabled())
                logger.debug("[AuthenticationFailureException] " + e.getMessage(), e);

            // logs the error
            ActionErrors errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("sso.login.failed"));
            saveErrors(request, errors);

            // Invalid login attempt, redirect to ON ERROR URL, if any.
            boolean ok = this.onLoginAuthenticationException(e, request, response, c);
            if (ok) {
                return null; // No forward is needed, we perfomed a 'sendRedirect'.
            }

            SSOWebConfiguration cfg = SSOContext.getCurrent().getSecurityDomain().getSSOWebConfiguration();
            if (cfg.isBasicAuthenticationEnabled()) {
                return mapping.findForward("login-page");
            } else {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Expires", "0");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
        }

    } catch (Exception e) {
        if (this.onFatalError(e, request, response))
            return null;

        return mapping.findForward("error");
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void delete(HttpServletRequest req, HttpServletResponse resp) {

    String id;/*from   w ww  .ja v  a 2 s.  c  om*/
    String repositoryName;
    String type;

    try {
        id = getField(req, resp, "id");
        repositoryName = getField(req, resp, "repository");
        type = getField(req, resp, "type");
    } catch (FieldNotFoundException e) {
        return;
    }
    Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
    RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();

    try {
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);
        if (type.equals("node")) {
            Node node = repositoryService.findNode(ticket, id);
            Node parent = repositoryService.findNode(ticket, node.getParent());
            if (node.isDirectory() && node.getParent() != null) {
                repositoryService.removeDirectory(ticket, node.getId());
                statsService.incDeletedDirectories();
            } else if (node.isDocument()) {
                repositoryService.removeDocument(ticket, node.getId());
                statsService.incDeletedDocuments();
            }
            StringBuilder url = new StringBuilder(getRepositoryURL(req, repositoryName));
            url.append(parent.getPath());
            resp.sendRedirect(resp.encodeRedirectURL(url.toString()));
        } else if (type.equals("category")) {
            repositoryService.deleteCategory(ticket, id);
            statsService.incDeletedCategories();
            String url = getRepositoryURL(req, repositoryName);
            resp.sendRedirect(resp.encodeRedirectURL(url));
        } else {
            String error = "Invalid operation : " + type;
            logErrorAndForward(req, resp, repositoryName, new InvalidOperationException(error), error);
        }

        resp.getOutputStream().flush();
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to delete the object.");
    }
}

From source file:org.apache.click.ClickServlet.java

/**
 * Performs rendering of the specified page.
 *
 * @param page page to render//w ww .  ja  v  a2 s  . c om
 * @param context the request context
 * @param actionResult the action result
 * @throws java.lang.Exception if error occurs
 */
protected void performRender(Page page, Context context, ActionResult actionResult) throws Exception {

    // Process page interceptors, and abort rendering if specified
    for (PageInterceptor interceptor : getThreadLocalInterceptors()) {
        if (!interceptor.preResponse(page)) {
            return;
        }
    }

    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();

    if (StringUtils.isNotBlank(page.getRedirect())) {
        String url = page.getRedirect();

        url = response.encodeRedirectURL(url);

        if (logger.isTraceEnabled()) {
            logger.debug("   redirect: " + url);

        } else if (logger.isDebugEnabled()) {
            logger.debug("redirect: " + url);
        }

        response.sendRedirect(url);

    } else if (StringUtils.isNotBlank(page.getForward())) {
        // Indicates the request is forwarded
        request.setAttribute(CLICK_FORWARD, CLICK_FORWARD);

        if (logger.isTraceEnabled()) {
            logger.debug("   forward: " + page.getForward());

        } else if (logger.isDebugEnabled()) {
            logger.debug("forward: " + page.getForward());
        }

        if (page.getForward().endsWith(".jsp")) {
            renderJSP(page);

        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(page.getForward());

            dispatcher.forward(request, response);
        }

    } else if (actionResult != null) {
        renderActionResult(actionResult, page, context);

    } else if (page.getPath() != null) {
        // Render template unless the request was a page action. This check
        // guards against the scenario where the page action returns null
        // instead of a action result
        if (context.getRequestParameter(Page.PAGE_ACTION) == null) {
            String pagePath = page.getPath();

            // Check if request is a JSP page
            if (pagePath.endsWith(".jsp") || configService.isJspPage(pagePath)) {
                // CLK-141. Set pagePath as the forward value.
                page.setForward(StringUtils.replace(pagePath, ".htm", ".jsp"));

                // Indicates the request is forwarded
                request.setAttribute(CLICK_FORWARD, CLICK_FORWARD);
                renderJSP(page);

            } else {
                renderTemplate(page);
            }
        }

    } else {
        if (logger.isTraceEnabled()) {
            logger.debug("   path not defined for " + page.getClass().getName());

        } else if (logger.isDebugEnabled()) {
            logger.debug("path not defined for " + page.getClass().getName());
        }
    }
}

From source file:com.mindquarry.user.webapp.AuthenticationFilter.java

/**
 * Filter method that implements the actual logic and decides whether to
 * process by calling the next filter in the chain (another filter or the
 * servlet) or stopping here and sending a special response (authentication
 * request or redirect).//from  www . j a  va 2 s  .  c  o m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    // cast to http request and response due to read and set http headers
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    // always send an authentication request in order to avoid one round
    // trip
    response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm_ + "\"");

    // only do authentication for protected URIs, eg. excluded login page
    if (isProtected(request)) {
        // the request that checks if the credentials are ok by providing
        // them as request parameters instead of sending the HTTP basic
        // authorization header
        if (isCheckLoginRequest(request)) {
            // look for credentials in request parameter
            if (authenticateUserFromRequestParams(request)) {
                writeBUContinueResponse(response);
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }

        } else {
            // look for credentials in HTTP auth header
            Credentials authenticated = authenticateUser(request);

            // the special login request is done to actually perform the
            // authentication, this is typically the second step initiated by
            // the login page
            if (isLoginRequest(request)) {

                if (authenticated == null) {
                    // not authenticated. trigger auth. with username / password
                    // either by the HTTP auth dialog in the browser or
                    // automatically by Javascript XMLHttpRequest
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    // authenticated. redirect to original target
                    String originalUrl = request.getParameter(TARGET_URI_PARAM);
                    String redirectUrl = response.encodeRedirectURL((originalUrl != null ? originalUrl : "."));

                    if (isAJAXRequest(request)) {
                        // no redirect necessary, the AJAX client must do
                        // this himself (because redirects as answers to
                        // XHR requests, if supported by the browser, will
                        // redirect the XHR, but not notify the calling
                        // javascript about the new url)

                        // in ajax requests we have to send some valid XML
                        // as content, otherwise some browsers make problems
                        writeBUContinueResponse(response);
                        response.setStatus(HttpServletResponse.SC_OK);

                    } else {
                        response.sendRedirect(redirectUrl);
                    }
                }

                // no further servlet processing.
                return;

            } else {
                // 99 percent of all pages, not the special login request.

                // here we either have the first request to the server, ie.
                // not yet authenticated, or some client that does not send the
                // authorization data preemptively (although he already did
                // authenticate) -> see isGuiBrowserRequest()
                if (authenticated == null) {
                    // not authenticated.

                    // standard browser with preemptive sending auth data, thus
                    // it must be the first request -> go to login page
                    if (isGuiBrowserRequest(request)) {
                        String loginUrl = buildLoginUrlForRequest(request);
                        String redirectUrl = response.encodeRedirectURL(loginUrl);
                        response.sendRedirect(redirectUrl);
                    } else {
                        // trigger simple client auth. or re-authentication
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // no further servlet processing.
                    return;

                } else {
                    // authenticated. make username available as request
                    // attribute
                    request.setAttribute(USERNAME_ATTR, authenticated.username);
                    request.setAttribute(PASSWORD_ATTR, authenticated.password);
                    CurrentUser currentUser = lookupCurrentUserRequestBean();
                    currentUser.setId(authenticated.username);
                }
            }
        }
    }
    // access granted, proceed with the servlet
    chain.doFilter(servletRequest, servletResponse);
}

From source file:org.sakaiproject.login.tool.LoginTool.java

/**
 * Respond to data posting requests.//from   w  ww.ja  v  a  2  s .  co  m
 *
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // get the Sakai session
    Session session = SessionManager.getCurrentSession();

    // get my tool registration
    Tool tool = (Tool) req.getAttribute(Tool.TOOL);

    // here comes the data back from the form... these fields will be present, blank if not filled in
    String eid = req.getParameter("eid");
    String pw = req.getParameter("pw");

    // one of these will be there, one null, depending on how the submit was done
    String submit = req.getParameter("submit");
    String cancel = req.getParameter("cancel");

    // cancel
    if (cancel != null) {
        session.setAttribute(ATTR_MSG, rb.getString("log.canceled"));

        // get the session info complete needs, since the logout will invalidate and clear the session
        String returnUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);

        // TODO: send to the cancel URL, cleanup session
        complete(returnUrl, session, tool, res);
    }

    // submit
    else {
        // authenticate
        try {
            if ((eid == null) || (pw == null) || (eid.length() == 0) || (pw.length() == 0)) {
                throw new AuthenticationException("missing required fields");
            }

            // Do NOT trim the password, since many authentication systems allow whitespace.
            eid = eid.trim();

            Evidence e = new IdPwEvidence(eid, pw);

            Authentication a = AuthenticationManager.authenticate(e);

            // login the user
            if (UsageSessionService.login(a, req)) {
                // get the session info complete needs, since the logout will invalidate and clear the session
                String returnUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);

                complete(returnUrl, session, tool, res);
            } else {
                session.setAttribute(ATTR_MSG, rb.getString("log.tryagain"));
                res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, null)));
            }
        } catch (AuthenticationException ex) {
            session.setAttribute(ATTR_MSG, rb.getString("log.invalid"));

            // respond with a redirect back here
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, null)));
        }
    }
}

From source file:org.wso2.carbon.identity.authenticator.mobileconnect.MobileConnectAuthenticator.java

/**
 * Prompt for Mobile Number from the IS.
 *//*from  w w  w. j av  a  2  s  .  c o m*/
private void redirectToMobileNumberUI(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    //retrieve the url of the UI from the Configuration Files
    String loginEndpointUrl = getAuthenticatorConfig().getParameterMap()
            .get(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_UI_ENDPOINT_URL);

    String loginPage = "";
    if (StringUtils.isNotEmpty(loginEndpointUrl)) {
        loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL()
                .replace("authenticationendpoint/login.do", loginEndpointUrl);
    }
    //get query parameter from the context
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    //if the context is in retrying stage
    String retryParam = "";
    if (context.isRetrying()) {
        retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
    }

    try {
        //set this status to notify the controller that the UI stage is completed
        request.getSession().setAttribute(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_UI_STATUS,
                MobileConnectAuthenticatorConstants.MOBILE_CONNECT_UI_PROCESS_COMPLETE);
        //redirect to the UI page
        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&authenticators="
                + getName() + retryParam);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Authentication failed!", e);

    }
    context.setProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_FLOW_STATUS,
            MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_ENDPOINT);
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void update(HttpServletRequest req, HttpServletResponse resp) {

    String id;//from  w  ww  .j a  v  a 2  s.  c  om
    String repositoryName;
    String name;
    String description;
    String type;

    try {
        id = getField(req, resp, "id");
        repositoryName = getField(req, resp, "repository");
        name = getField(req, resp, "name");
        description = getField(req, resp, "description");
        type = getField(req, resp, "type");
    } catch (FieldNotFoundException e) {
        return;
    }
    Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
    RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();

    try {
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);
        if (type.equals("node")) {
            Node node = repositoryService.findNode(ticket, id);

            if (node.isDirectory() && node.getParent() != null) {
                node.setName(name);
                node.setDescription(description);
                DirectoryProperties properties = ((Directory) node).dumpProperties();
                node = repositoryService.updateDirectory(ticket, properties);
                statsService.incUpdatedDirectories();
                StringBuilder url = new StringBuilder(getRepositoryURL(req, repositoryName));
                url.append(node.getPath());
                resp.sendRedirect(resp.encodeRedirectURL(url.toString()));
            } else if (node.isDocument()) {
                Document document = (Document) node;
                document.setName(name);
                document.setDescription(description);
                String content = req.getParameter("content");
                byte[] dataContent = null;
                if (content != null && !"".equals(content)) {
                    dataContent = content.getBytes();
                }
                DocumentProperties properties = document.dumpProperties();
                document = repositoryService.updateDocument(ticket, properties);
                if (dataContent != null) {
                    repositoryService.updateContent(ticket, document.getId(), dataContent);
                }
                statsService.incUpdatedDocuments();
                String url = getRootURL(req) + "/forward?method=documentcategories&repository=" + repositoryName
                        + "&id=" + document.getId();
                resp.sendRedirect(resp.encodeRedirectURL(url));

            }
        } else if (type.equals("category")) {
            Category category = repositoryService.findCategoryById(ticket, id);
            category.setName(name);
            category.setDescription(description);

            CategoryProperties properties = category.dumpProperties();
            category = repositoryService.updateCategory(ticket, id, properties);
            statsService.incUpdatedCategories();
            String url = getRepositoryURL(req, repositoryName) + "/categories/" + category.getName();
            resp.sendRedirect(resp.encodeRedirectURL(url));
        } else {
            String error = "Invalid operation : " + type;
            logErrorAndForward(req, resp, repositoryName, new InvalidOperationException(error), error);
        }

        resp.getOutputStream().flush();
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to updating the object.");
    }
}

From source file:org.josso.wls10.agent.WLSSessionEnforcementServletFilter.java

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

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    HttpSession session = hreq.getSession(true);

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    String contextPath = hreq.getContextPath();
    String vhost = hreq.getServerName();
    SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);

    // ------------------------------------------------------------------
    // Check for the single sign on cookie
    // ------------------------------------------------------------------
    if (log.isDebugEnabled())
        log.debug("Checking for SSO cookie");
    Cookie cookie = null;/*from  w w  w  .  j  av  a  2 s  .  c o  m*/
    Cookie cookies[] = hreq.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    for (int i = 0; i < cookies.length; i++) {
        if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
            cookie = cookies[i];
            break;
        }
    }
    if (cookie != null && !cookie.getValue().equals("-")) {
        String jossoSessionId = cookie.getValue();

        if (log.isDebugEnabled())
            log.debug("asserting SSO session for : " + jossoSessionId);

        SSOAgentRequest sessionAssertionRequest;

        sessionAssertionRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ASSERT_SESSION,
                jossoSessionId, null, null, hreq, hres);

        // TODO: Agents should be able to pass back responses corresponding to the submitted request.
        try {
            _agent.processRequest(sessionAssertionRequest);
            if (log.isDebugEnabled())
                log.debug("asserted successfully SSO session for : " + jossoSessionId);
        } catch (FatalSSOSessionException e) {
            if (log.isDebugEnabled())
                log.debug("error asserting SSO session : " + jossoSessionId);

            String requestedResourceUrl;

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);
            session.invalidate();
            requestedResourceUrl = _agent.buildBackToURL(hreq, "");
            hres.sendRedirect(hres.encodeRedirectURL(requestedResourceUrl));
            return;
        }

    }

    filterChain.doFilter(hreq, hres);

}

From source file:org.josso.wls92.agent.WLSSessionEnforcementServletFilter.java

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

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    HttpSession session = hreq.getSession(true);

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    String contextPath = hreq.getContextPath();
    String vhost = hreq.getServerName();
    SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);

    // ------------------------------------------------------------------
    // Check for the single sign on cookie
    // ------------------------------------------------------------------
    if (log.isDebugEnabled())
        log.debug("Checking for SSO cookie");
    Cookie cookie = null;/*w  w  w. j  av  a 2 s .c  om*/
    Cookie cookies[] = hreq.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    for (int i = 0; i < cookies.length; i++) {
        if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
            cookie = cookies[i];
            break;
        }
    }
    if (cookie != null && !cookie.getValue().equals("-")) {

        String jossoSessionId = cookie.getValue();

        if (log.isDebugEnabled())
            log.debug("asserting SSO session for : " + jossoSessionId);

        SSOAgentRequest sessionAssertionRequest;

        sessionAssertionRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ASSERT_SESSION,
                jossoSessionId, null, null, hreq, hres);

        // TODO: Agents should be able to pass back responses corresponding to the submitted request.
        try {
            _agent.processRequest(sessionAssertionRequest);
            if (log.isDebugEnabled())
                log.debug("asserted successfully SSO session for : " + jossoSessionId);
        } catch (FatalSSOSessionException e) {
            if (log.isDebugEnabled())
                log.debug("error asserting SSO session : " + jossoSessionId);

            String requestedResourceUrl;

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);
            session.invalidate();
            requestedResourceUrl = _agent.buildBackToURL(hreq, "");
            hres.sendRedirect(hres.encodeRedirectURL(requestedResourceUrl));
            return;
        }

    }

    filterChain.doFilter(hreq, hres);

}