Example usage for javax.servlet.http HttpServletResponse isCommitted

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

Introduction

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

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:com.alfaariss.oa.ManagerServlet.java

/**
 * Handles requests send by the system manager.
 * //from w ww  .j a v  a  2 s. c om
 * The following requests are supported at this moment:
 * <ul>
 * <li>do=restart</li>
 * <li>do=stop</li>
 * <li>do=start</li>
 * </ul>
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        Properties pConfig = cloneConfigurationFromRequest(oRequest);
        String sDo = oRequest.getParameter("do");
        if (sDo == null) //No 'do' paramater
        {
            String sGet = oRequest.getParameter("get");
            if (sGet == null) //No 'get' and no 'do' paramater
            {
                _logger.error("Invalid request sent from IP: " + oRequest.getRemoteAddr());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {
                StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
                sbWarning.append(sGet);
                sbWarning.append(", sent from IP: ");
                sbWarning.append(oRequest.getRemoteAddr());
                _logger.error(sbWarning.toString());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

        } else if (sDo.equals("restart")) {
            _logger.info("Performing restart request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.restart(pConfig);
        } else if (sDo.equals("stop")) {
            _logger.info("Performing stop request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.stop();
        } else if (sDo.equals("start")) {
            _logger.info("Performing start request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.start(pConfig);
        } else {
            StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
            sbWarning.append(sDo);
            sbWarning.append(", sent from IP: ");
            sbWarning.append(oRequest.getRemoteAddr());
            _logger.error(sbWarning.toString());
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Error processing request", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Internal error", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * Get the requested resource and copy it to the ServletOutputStream, bit by bit.
 *
 * @param req HttpServletRequest as given by the servlet container
 * @param res HttpServletResponse as given by the servlet container
 * @throws IOException standard servlet exception
 *///www.ja  v  a2 s . co m
private void handleResourceRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String resourceHandle = (String) req.getAttribute(Aggregator.HANDLE);
    if (log.isDebugEnabled()) {
        log.debug("handleResourceRequest, resourceHandle=\"" + resourceHandle + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (StringUtils.isNotEmpty(resourceHandle)) {
        HierarchyManager hm = (HierarchyManager) req.getAttribute(Aggregator.HIERARCHY_MANAGER);
        InputStream is = null;
        try {
            is = getNodedataAstream(resourceHandle, hm, res);
            if (null != is) {
                // todo find better way to discover if resource could be compressed, implement as in "cache"
                // browsers will always send header saying either it can decompress or not, but
                // resources like jpeg which is already compressed should be not be written on
                // zipped stream otherwise some browsers takes a long time to render
                sendUnCompressed(is, res);
                IOUtils.closeQuietly(is);
                return;
            }
        } catch (IOException e) {
            // don't log at error level since tomcat tipically throws a
            // org.apache.catalina.connector.ClientAbortException if the user stops loading the page
            if (log.isDebugEnabled())
                log.debug("Exception while dispatching resource  " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$
                        + e.getMessage(), e);
        } catch (Exception e) {
            log.error("Exception while dispatching resource  " + e.getClass().getName() + ": " + e.getMessage(), //$NON-NLS-1$//$NON-NLS-2$
                    e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Resource not found, redirecting request for [" + req.getRequestURI() + "] to 404 URI"); //$NON-NLS-1$
    }

    if (!res.isCommitted()) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        log.info("Unable to redirect to 404 page, response is already committed"); //$NON-NLS-1$
    }

}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.sp.sso.SPSingleLogout.java

/**
 * @see com.alfaariss.oa.util.saml2.profile.ISAML2Profile#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from ww w.  jav  a  2 s .  c  o m*/
public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    ISession session = null;
    try {
        String sSessionId = servletRequest.getParameter(ISession.ID_NAME);
        if (sSessionId != null) {
            if (!SessionValidator.validateDefaultSessionId(sSessionId)) {
                _logger.warn("Invalid session id in request: " + sSessionId);
                throw new UserException(UserEvent.REQUEST_INVALID);
            }
            session = _sessionFactory.retrieve(sSessionId);

            processResponse(servletRequest, servletResponse, session);
        } else
            processSAMLRequest(servletRequest, servletResponse);
    } catch (UserException e) //User error
    {
        UserEventLogItem logItem = null;
        if (session != null)
            logItem = new UserEventLogItem(session, servletRequest.getRemoteAddr(), e.getEvent(), this, null);
        else
            logItem = new UserEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(),
                    null, this, null);
        _eventLogger.info(logItem);

        if (!servletResponse.isCommitted()) {
            try {
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _logger.warn("Could not send response", e1);
            }
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not process request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

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

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

    HttpServletRequest hreq = (HttpServletRequest) request;
    HttpServletResponse hres = (HttpServletResponse) response;

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

    try {/*  ww  w  .j a  v  a  2s .c  om*/
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(request.getServerName(), contextPath)) {
            filterChain.doFilter(hreq, hres);
            log.warn("JOSSO WLS 9.2 Filter is running on a non-JOSSO Partner application!");
            return;
        }

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

        HttpSession session = hreq.getSession(true);

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

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("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, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

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

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

        }

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

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

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

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

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

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

            // logout user (remove data from the session and webserver)
            // (The LoginModule.logout method is never called 
            // for the WebLogic Authentication providers or custom Authentication providers. 
            // This is simply because once the principals are created and placed into a subject, 
            // the WebLogic Security Framework no longer controls the lifecycle of the subject)
            _agent.prepareNonCacheResponse(hres);
            ServletAuthentication.logout(hreq);

            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        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;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);
        LocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);
            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

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

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

            // We have no cookie and a security check without assertion was received ...
            // This means that the user could not be identified during a login optional process ...
            // go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

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

            }

            // 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 (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

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

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

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

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

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

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...

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

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

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

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

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            SSOAgentRequest relayRequest;

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

            relayRequest = doMakeSSOAgentRequest(cfg.getId(), 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(
                        "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(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("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, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                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 (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _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 (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r;
        log.debug("Creating Security Context for Session [" + session + "]");
        r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                jossoSessionId, localSession, null, hreq, hres);

        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            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.
            // TODO : Not supported ... session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

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

        if (entry != null) {
            if (log.isDebugEnabled())
                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(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

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

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

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

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

                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // 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);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }
}

From source file:org.josso.wls81.agent.WLSAgentServletFilter.java

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

    HttpServletRequest hreq = (HttpServletRequest) request;
    HttpServletResponse hres = (HttpServletResponse) response;

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

    try {/*from   ww w . ja  va2  s .c  o m*/
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(request.getServerName(), contextPath)) {
            filterChain.doFilter(hreq, hres);
            log.warn("JOSSO WLS 8.1 Filter is running on a non-JOSSO Partner application!");
            return;
        }

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

        HttpSession session = hreq.getSession(true);

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

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("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, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

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

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

        }

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

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

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

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

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

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

            // logout user (remove data from the session and webserver)
            // (The LoginModule.logout method is never called 
            // for the WebLogic Authentication providers or custom Authentication providers. 
            // This is simply because once the principals are created and placed into a subject, 
            // the WebLogic Security Framework no longer controls the lifecycle of the subject)
            _agent.prepareNonCacheResponse(hres);
            ServletAuthentication.logout(hreq);

            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        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;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);
        LocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);
            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

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

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

            // We have no cookie and a security check without assertion was received ...
            // This means that the user could not be identified during a login optional process ...
            // go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

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

            }

            // 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 (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

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

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

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

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

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

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...

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

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

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

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

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            SSOAgentRequest relayRequest;

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

            relayRequest = doMakeSSOAgentRequest(cfg.getId(), 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(
                        "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(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("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, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)

            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                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 (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _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 (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r;
        log.debug("Creating Security Context for Session [" + session + "]");
        r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                jossoSessionId, localSession, null, hreq, hres);

        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            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.
            // TODO : Not supported ... session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

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

        if (entry != null) {
            if (log.isDebugEnabled())
                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(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

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

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

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

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

                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // 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);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private void fromHome(HttpServletRequest request, HttpServletResponse response) {
    String target = request.getParameter("TARGET");
    AuthenticationResponse eduGAINresponse = null;
    try {//ww w .j  a va2 s .  co  m
        eduGAINresponse = getSAMLResponse(request.getParameter("SAMLResponse").getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse eduGAIN response");
            return;
        } catch (IOException e1) {
            this.log.error("Invalid eduGAIN response; unable to forward user to error page");
        }
    }

    if ((eduGAINresponse != null)
            && eduGAINresponse.getResult().equals(AuthenticationResponse.EDUGAIN_NAMESPACE_RESULT_ACCEPTED)) {
        try {
            Cookie lcook = getCookie(request, response, "statecook");
            HashMap attrs = validateCookie(lcook, "statecook");
            if ((attrs != null) && (attrs.containsKey("KEY"))) {
                String key = (String) attrs.get("KEY");
                HashMap<String, String> oldRequest = (HashMap<String, String>) this.loadRequest(key);
                String oldURL = reconstructRequest(oldRequest, response);

                attrs = parseAttrs(eduGAINresponse);

                request.getSession().setAttribute("SAMLResponse", eduGAINresponse.toSAML());
                attachCookies("lcook", attrs, response, false);
                attachCookies("statecook", null, response, true);
                //addAttributes(attrs,request.getSession());
                if (!(oldURL.equals("")) && (oldRequest != null) && !(response.isCommitted()))
                    response.sendRedirect(oldURL);
                else
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unable to load old request");

            } else
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Connection timed out");
        } catch (IOException ioe) {
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "State cookie not found");
            } catch (IOException e) {
                this.log.error("State cookie not found");
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            try {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, "Process timed out");
            } catch (IOException e1) {
                this.log.error("Process timed out");
                e1.printStackTrace();
            }
        }

    } else
        try {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication at home domain");
        } catch (IOException e) {
            this.log.error("Invalid authentication at home domain");
            e.printStackTrace();
        } catch (IllegalStateException ex) {
            this.log.error("Unable to forward user to error page");
            ex.printStackTrace();
        }

}

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

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

    HttpServletResponse hres = (HttpServletResponse) response;

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

    try {//from   ww  w .  j  ava 2s  .  c o  m
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        // ------------------------------------------------------------------
        // 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());
        }

        HttpSession session = hreq.getSession(true);

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

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("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, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

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

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

            return;

        }

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

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

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

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

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

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

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

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

            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        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;
            }
        }

        // Get our session ...

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        GenericServletLocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

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

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

            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

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

            if (log.isDebugEnabled())
                log.debug("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 (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _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, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

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

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

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

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

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

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("Session is: " + session);

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

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

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

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

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            GenericServletSSOAgentRequest relayRequest;

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

            relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    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(
                        "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 (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("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, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                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 (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _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 (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            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 (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                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(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

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

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

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

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

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

        }

        // 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);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:com.siberhus.web.ckeditor.servlet.BaseActionServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI != null && requestURI.lastIndexOf("/") != -1) {
        String actionName = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length());
        int paramIdx = actionName.indexOf("?");
        if (paramIdx != -1) {
            actionName = actionName.substring(0, actionName.indexOf("?"));
        }/*from   ww w .j  a  v a2  s. c  om*/
        Method method = null;
        try {
            method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Action=" + actionName + " not found for servlet=" + this.getClass());
            return;
        }
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                request = new MultipartServletRequest(request);
                log.debug("Files *********************");
                MultipartServletRequest mrequest = (MultipartServletRequest) request;
                for (FileItem fileItem : mrequest.getFileItems()) {
                    log.debug("File[fieldName={}, fileName={}, fileSize={}]",
                            new Object[] { fileItem.getFieldName(), fileItem.getName(), fileItem.getSize() });
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Parameters **************************");
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    log.debug("Param[name={},value(s)={}]",
                            new Object[] { paramName, Arrays.toString(request.getParameterValues(paramName)) });
                }
            }

            Object result = method.invoke(this, request, response);

            if (result instanceof StreamingResult) {
                if (!response.isCommitted()) {
                    ((StreamingResult) result).execute(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvocationTargetException) {
                throw new ServletException(((InvocationTargetException) e).getTargetException());
            }
            throw new ServletException(e);
        }
    }
}

From source file:se.unlogic.hierarchy.core.servlets.CoreServlet.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res, User user, URIParser uriParser)
        throws TransformerException, IOException {

    ForegroundModuleResponse moduleResponse = null;
    RequestException exception = null;/*from  ww  w  .  j a v a2s. c  om*/

    try {
        try {
            moduleResponse = this.rootSection.processRequest(req, res, user, uriParser,
                    rootSection.getSectionDescriptor().getRequiredProtocol());

        } catch (AccessDeniedException e) {

            if (user == null) {

                loginHandler.processLoginRequest(req, res, uriParser, true);
            }

            if (!res.isCommitted()) {
                throw e;
            }
        }

    } catch (RequestException e) {

        log.log(e.getPriority(),
                e.toString() + " Requested by user " + user + " accessing from " + req.getRemoteAddr(),
                e.getThrowable());
        exception = e;
    }

    // Check if the response has been committed
    if (!res.isCommitted()) {

        // Set request attribute to tell the URLFilter to ignore this response
        req.setAttribute("processed", true);

        // Response has not been committed create xml document
        Document doc = XMLUtils.createDomDocument();

        // Create root element
        Element document = doc.createElement("document");
        doc.appendChild(document);

        if (exception != null) {

            // Append exception
            Element errors = doc.createElement("errors");
            doc.getDocumentElement().appendChild(errors);
            errors.appendChild(exception.toXML(doc));

            if (exception.getStatusCode() != null) {
                res.setStatus(exception.getStatusCode());
            }

            this.appendLinks(doc, exception.getBackgroundModuleResponses());
            this.appendScripts(doc, exception.getBackgroundModuleResponses());

            this.addBackgroundModuleResponses(exception.getBackgroundModuleResponses(), doc, user, req);

        } else {

            // Check if the user has changed
            if (moduleResponse.isUserChanged()) {

                try {
                    HttpSession session = req.getSession(false);

                    if (session != null) {
                        user = (User) session.getAttribute("user");
                    }

                } catch (IllegalStateException e) {

                    user = null;
                }
            }

            if (moduleResponse.isExcludeSystemTransformation()) {
                doc = moduleResponse.getDocument();
                document = doc.getDocumentElement();
            }

            this.appendLinks(doc, moduleResponse);
            this.appendScripts(doc, moduleResponse);

            if (isValidResponse(moduleResponse)) {

                if (moduleResponse.getResponseType() == ResponseType.HTML) {

                    // Append module html response
                    Element moduleres = doc.createElement("moduleHTMLResponse");
                    document.appendChild(moduleres);
                    moduleres.appendChild(doc.createCDATASection(moduleResponse.getHtml()));

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_CORE_TRANSFORMATION) {

                    // Append module response
                    Element moduleres = doc.createElement("moduleXMLResponse");
                    document.appendChild(moduleres);
                    moduleres.appendChild(doc.adoptNode(moduleResponse.getElement()));

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_SEPARATE_TRANSFORMATION) {

                    if (moduleResponse.getTransformer() != null) {

                        // Write xml to debug file if xml debug output is enabled
                        if (moduleXMLDebug && !StringUtils.isEmpty(moduleXMLDebugFile)) {
                            this.log.debug("XML debug mode enabled, writing module XML to " + moduleXMLDebugFile
                                    + " for module " + moduleResponse.getModuleDescriptor());

                            try {
                                XMLUtils.writeXMLFile(moduleResponse.getDocument(),
                                        this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile, true,
                                        encoding);

                                this.log.debug("Finished writing module XML to "
                                        + this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile);

                            } catch (Exception e) {

                                this.log.error("Error writing module XML to " + this.applicationFileSystemPath
                                        + "WEB-INF/" + moduleXMLDebugFile, e);
                            }
                        }

                        // Transform output
                        try {

                            this.log.debug("Module XML transformation starting");

                            if (moduleResponse.isExcludeSystemTransformation()) {

                                // Set response parameters
                                res.setContentType("text/html");

                                // Set standard HTTP/1.1 no-cache headers.
                                res.setHeader("Cache-Control",
                                        "no-store, no-cache, must-revalidate, proxy-revalidate");

                                XMLTransformer.transformToWriter(moduleResponse.getTransformer(), doc,
                                        res.getWriter(), encoding);

                                return;

                            } else {

                                StringWriter stringWriter = new StringWriter();

                                XMLTransformer.transformToWriter(moduleResponse.getTransformer(),
                                        moduleResponse.getDocument(), stringWriter, encoding);

                                // Append module response
                                Element moduleres = doc.createElement("moduleTransformedResponse");
                                document.appendChild(moduleres);

                                this.log.debug("Module XML transformation finished, appending result...");

                                moduleres.appendChild(doc.createCDATASection(stringWriter.toString()));

                                this.log.debug("Result appended");

                            }

                        } catch (Exception e) {

                            this.log.error("Tranformation of module response from module"
                                    + moduleResponse.getModuleDescriptor() + " failed, requested by user "
                                    + user + " accesing from " + req.getRemoteAddr(), e);

                            Element errors = doc.createElement("errors");
                            document.appendChild(errors);

                            Element separateTransformationFailedElement = doc
                                    .createElement("separateTransformationFailed");
                            errors.appendChild(separateTransformationFailedElement);
                            separateTransformationFailedElement
                                    .appendChild(XMLUtils.createCDATAElement("exception", e.toString(), doc));
                            separateTransformationFailedElement
                                    .appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
                        }
                    } else {
                        this.log.error(
                                "Module response for separate transformation without attached stylesheet returned by module "
                                        + moduleResponse.getModuleDescriptor() + " requested by user " + user
                                        + " accesing from " + req.getRemoteAddr());
                        Element errors = doc.createElement("errors");
                        document.appendChild(errors);
                        Element separateTransformationWithoutStylesheetElement = doc
                                .createElement("separateTransformationWithoutStylesheet");
                        errors.appendChild(separateTransformationWithoutStylesheetElement);
                        separateTransformationWithoutStylesheetElement
                                .appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
                    }
                }
            } else {
                // No response, append error
                this.log.error("Invalid module response from module" + moduleResponse.getModuleDescriptor()
                        + ", requested by user " + user + " accesing from " + req.getRemoteAddr());
                Element errors = doc.createElement("errors");
                document.appendChild(errors);
                Element invalidModuleResonseElement = doc.createElement("invalidModuleResonse");
                errors.appendChild(invalidModuleResonseElement);
                invalidModuleResonseElement.appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
            }

            this.addBackgroundModuleResponses(moduleResponse.getBackgroundModuleResponses(), doc, user, req);
        }

        XMLUtils.appendNewCDATAElement(doc, document, "version", VERSION);

        document.appendChild(RequestUtils.getRequestInfoAsXML(doc, req, uriParser, false, true));

        // Append root section
        document.appendChild(this.rootSection.getSectionDescriptor().toXML(doc));

        // Append userinfo and menuitems
        if (user != null) {
            document.appendChild(user.toXML(doc));
        }

        //Get style sheet so that the correct menu type can be added
        CachedXSLTDescriptor xslDescriptor;

        if (this.xsltCacheHandler.getXslDescriptorCount() == 1) {

            //Only default stylesheet loaded, skip i18n support.

            xslDescriptor = this.xsltCacheHandler.getDefaultXsltDescriptor();

        } else {

            Language language = this.getLanguage(req, user);

            String preferedDesign = this.getPreferedDesign(req, user);

            xslDescriptor = this.xsltCacheHandler.getBestMatchingXSLTDescriptor(language, preferedDesign);
        }

        Element menus = doc.createElement("menus");
        document.appendChild(menus);

        if (moduleResponse != null) {

            if (moduleResponse.getTitle() != null) {
                document.appendChild(XMLUtils.createCDATAElement("title", moduleResponse.getTitle(), doc));
            }

            if (xslDescriptor.usesFullMenu()) {

                menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc));

            } else {

                if (moduleResponse.getMenu() != null) {

                    menus.appendChild(moduleResponse.getMenu().toXML(doc));
                }
            }

            if (!moduleResponse.getBreadcrumbs().isEmpty()) {

                Element breadcrumbsElement = doc.createElement("breadcrumbs");
                document.appendChild(breadcrumbsElement);

                for (Breadcrumb breadcrumb : moduleResponse.getBreadcrumbs()) {

                    if (breadcrumb != null) {

                        breadcrumbsElement.appendChild(breadcrumb.toXML(doc));
                    }
                }
            }

        } else if (exception != null) {

            if (xslDescriptor.usesFullMenu()) {

                menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc));

            } else {

                if (exception.getMenu() != null) {

                    menus.appendChild(exception.getMenu().toXML(doc));
                }
            }

            //TODO add breadcrumbs to exceptions
        }

        // Write xml to debug file if xml debug output is enabled
        if (systemXMLDebug && !StringUtils.isEmpty(systemXMLDebugFile)) {
            this.log.debug("XML debug mode enabled, writing system XML to " + systemXMLDebugFile);

            try {
                FileWriter xmldebugstream = new FileWriter(
                        new File(this.applicationFileSystemPath + "WEB-INF/" + systemXMLDebugFile));
                XMLUtils.toString(doc, encoding, xmldebugstream, false);
                xmldebugstream.close();

                this.log.debug("Finished writing system XML to " + this.applicationFileSystemPath + "WEB-INF/"
                        + systemXMLDebugFile);

            } catch (Exception e) {

                this.log.error("Error writing system XML to " + this.applicationFileSystemPath + "WEB-INF/"
                        + systemXMLDebugFile, e);
            }
        }

        // Set encoding
        res.setCharacterEncoding(encoding);

        // Set response parameters
        res.setContentType("text/html");

        // Set standard HTTP/1.1 no-cache headers.
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");

        // Transform output
        try {
            this.log.debug("System XML transformation starting");

            XMLTransformer.transformToWriter(xslDescriptor.getTransformer(), doc, res.getWriter(), encoding);

            this.log.debug("System XML transformation finished, response transformed and committed");

        } catch (TransformerException e) {

            this.log.error("System XML transformation failed, " + e);
            throw e;

        } catch (IOException e) {

            if (!res.isCommitted()) {

                log.error("Error writing response", e);
                throw e;

            } else {

                this.log.debug("Response already committed");
            }
        } catch (IllegalStateException e) {

            this.log.debug("Response already committed");
        }

    } else {
        if (exception != null) {
            this.log.warn("Error " + exception + " after response has been committed");
        } else {
            this.log.debug("Response already committed");
        }
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PreviewThemeImageServlet.java

/**
 * Handles requests for user uploaded resources.
 *///  w w w . ja va2s  . c o m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String theme = request.getParameter("theme");

    log.debug("Theme requested [" + theme + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;
    String previewImagePath = null;

    // try looking up selected theme
    try {
        ThemeManager tmgr = WebloggerFactory.getWeblogger().getThemeManager();
        SharedTheme previewTheme = tmgr.getTheme(theme);
        ThemeResource previewImage = previewTheme.getPreviewImage();
        if (previewImage != null) {
            previewImagePath = previewImage.getPath();
            resourceLastMod = previewImage.getLastModified();
            resourceStream = previewImage.getInputStream();
        }
    } catch (Exception ex) {
        log.debug("error looking up preview image", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // if we don't have a stream to the file then we can't continue
    if (resourceStream == null) {
        log.debug("Unable to get theme preview for theme - " + theme);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    log.debug("Everything is cool, sending image");

    // set the content type based on whatever is in our web.xml mime defs
    response.setContentType(this.context.getMimeType(previewImagePath));

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // cleanup
        out.close();
        resourceStream.close();

    } catch (Exception ex) {
        log.error("Error writing resource file", ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}