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:org.apache.hadoop.security.authentication.server.AuthenticationFilter.java

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object./*from w  w w .j a  v a 2 s.  co  m*/
 * @param response the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
        boolean newToken = false;
        AuthenticationToken token = getToken(httpRequest);
        if (token == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} triggering authentication",
                        getRequestURL(httpRequest)));
            }
            token = authHandler.authenticate(httpRequest, httpResponse);
            if (token != null && token != AuthenticationToken.ANONYMOUS) {
                token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
            }
            newToken = true;
        }
        if (token != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} user {1} authenticated", getRequestURL(httpRequest),
                        token.getUserName()));
            }
            final AuthenticationToken authToken = token;
            httpRequest = new HttpServletRequestWrapper(httpRequest) {
                @Override
                public String getAuthType() {
                    return authToken.getType();
                }

                @Override
                public String getRemoteUser() {
                    return authToken.getUserName();
                }

                @Override
                public Principal getUserPrincipal() {
                    return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                }
            };
            if (newToken && token != AuthenticationToken.ANONYMOUS) {
                String signedToken = signer.sign(token.toString());
                Cookie cookie = createCookie(signedToken);
                httpResponse.addCookie(cookie);
            }
            filterChain.doFilter(httpRequest, httpResponse);
        }
    } catch (AuthenticationException ex) {
        if (!httpResponse.isCommitted()) {
            Cookie cookie = createCookie("");
            cookie.setMaxAge(0);
            httpResponse.addCookie(cookie);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        }
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
}

From source file:com.alfaariss.oa.sso.web.profile.web.WebProfile.java

private void handleError(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
        Throwable t, int iErrorCode) {
    if (oSession != null) {
        _systemLogger.error(/* w w  w  . j  ava  2 s  .  c  o m*/
                new SystemLogItem(oSession.getId(), iErrorCode, "Internal error while processing request"), t);

        try {
            //Set request attributes if available
            oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale());

            oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());

            String sRequestorID = oSession.getRequestorId();
            if (sRequestorID != null) {
                IRequestor oRequestor = _ssoService.getRequestor(oSession);
                if (oRequestor != null)
                    oRequest.setAttribute(IRequestor.REQUESTOR_ATTRIBUTE_NAME, oRequestor);
            }
        } catch (Exception e) {
            _systemLogger.error("could not set request attributes", e);
        }

        oSession.expire();
        try {
            oSession.persist();
        } catch (PersistenceException e1) {
            _systemLogger.error("Could not persist session", e1);
        }
    } else {
        _systemLogger.error("Internal error while processing request", t);
    }

    if (!oResponse.isCommitted()) {
        try {
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
            _systemLogger.warn("Could not send response", e1);
        }
    }
}

From source file:com.alfaariss.oa.sso.web.profile.user.UserProfile.java

/**
 * @see com.alfaariss.oa.api.IService#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  ww  w  .j  ava2s. c  o  m*/
@Override
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    ISession session = null;
    try {
        //Disable caching
        HttpUtils.setDisableCachingHttpHeaders(servletRequest, servletResponse);

        session = (ISession) servletRequest.getAttribute(ISession.ID_NAME);
        if (session == null) {
            String sId = servletRequest.getParameter(ISession.ID_NAME);
            if (sId != null) {
                if (!SessionValidator.validateDefaultSessionId(sId)) {
                    _logger.warn("Invalid session id in request: " + sId);
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
                session = _sessionFactory.retrieve(sId);
            }
        }

        String sTarget = resolveTarget(servletRequest);
        if (sTarget != null) {
            if (sTarget.equalsIgnoreCase(TARGET_AUTHN) && _bAuthNEnabled) {
                _logger.debug("Performing 'authn' request sent from IP: " + servletRequest.getRemoteAddr());
                processAuthN(servletRequest, servletResponse, session);
                return;
            } else if (sTarget.equalsIgnoreCase(TARGET_LOGOUT)) {
                _logger.debug("Performing 'logout' request sent from IP: " + servletRequest.getRemoteAddr());
                processLogout(servletRequest, servletResponse, session);
                return;
            }
        }

        _logger.debug("Performing 'info' request sent from IP: " + servletRequest.getRemoteAddr());
        processDefault(servletRequest, servletResponse, session);
    } catch (UserException e) {
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.debug("Could not respond", e1);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (OAException e) {
        if (session != null)
            _eventLogger.info(new RequestorEventLogItem(session, servletRequest.getRemoteAddr(),
                    RequestorEvent.INTERNAL_ERROR, this, null));
        else
            _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                    servletRequest.getRemoteAddr(), null, this, null));

        throw e;
    } catch (Exception e) {
        if (session != null)
            _eventLogger.info(new RequestorEventLogItem(session, servletRequest.getRemoteAddr(),
                    RequestorEvent.INTERNAL_ERROR, this, null));
        else
            _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                    servletRequest.getRemoteAddr(), null, this, null));

        _logger.fatal("Internal error during request processing", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

/**
 * Respond to navigation / access requests.
 *
 * @param req//from w w  w  .j  a  va 2s.  com
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws javax.servlet.ServletException.
 * @throws java.io.IOException.
 */
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    int stat = PortalHandler.NEXT;
    try {
        basicAuth.doLogin(req);
        if (!ToolRenderService.preprocess(this, req, res, getServletContext())) {
            return;
        }

        // Check to see if the pre-process step has redirected us - if so,
        // our work is done here - we will likely come back again to finish
        // our
        // work.
        if (res.isCommitted()) {
            return;
        }

        // get the Sakai session
        Session session = SessionManager.getCurrentSession();

        // recognize what to do from the path
        String option = URLUtils.getSafePathInfo(req);

        String[] parts = getParts(req);

        Map<String, PortalHandler> handlerMap = portalService.getHandlerMap(this);

        // begin SAK-19089
        // if not logged in and accessing "/", redirect to gatewaySiteUrl
        if ((gatewaySiteUrl != null) && (option == null || "/".equals(option))
                && (session.getUserId() == null)) {
            // redirect to gatewaySiteURL 
            res.sendRedirect(gatewaySiteUrl);
            return;
        }
        // end SAK-19089

        // Look up the handler and dispatch
        PortalHandler ph = handlerMap.get(parts[1]);
        if (ph != null) {
            stat = ph.doGet(parts, req, res, session);
            if (res.isCommitted()) {
                if (stat != PortalHandler.RESET_DONE) {
                    portalService.setResetState(null);
                }
                return;
            }
        }
        if (stat == PortalHandler.NEXT) {

            for (Iterator<PortalHandler> i = handlerMap.values().iterator(); i.hasNext();) {
                ph = i.next();
                stat = ph.doGet(parts, req, res, session);
                if (res.isCommitted()) {
                    if (stat != PortalHandler.RESET_DONE) {
                        portalService.setResetState(null);
                    }
                    return;
                }
                // this should be
                if (stat != PortalHandler.NEXT) {
                    break;
                }
            }
        }
        if (stat == PortalHandler.NEXT) {
            doError(req, res, session, Portal.ERROR_SITE);
        }

    } catch (Throwable t) {
        doThrowableError(req, res, t);
    }

    // Make sure to clear any reset State at the end of the request unless
    // we *just* set it
    if (stat != PortalHandler.RESET_DONE) {
        portalService.setResetState(null);
    }
}

From source file:org.opencms.main.OpenCmsCore.java

/**
 * This method performs the error handling for OpenCms.<p>
 *
 * @param cms the current cms context, might be null !
 * @param req the client request//w w w  .j  a  v a  2s .  co  m
 * @param res the client response
 * @param t the exception that occurred
 */
private void errorHandling(CmsObject cms, HttpServletRequest req, HttpServletResponse res, Throwable t) {

    // remove the controller attribute from the request
    CmsFlexController.removeController(req);

    boolean canWrite = (!res.isCommitted() && !res.containsHeader("Location"));
    int status = -1;
    boolean isGuest = true;

    if (t instanceof ServletException) {
        ServletException s = (ServletException) t;
        if (s.getRootCause() != null) {
            t = s.getRootCause();
        }
    } else if (t instanceof CmsSecurityException) {
        // access error - display login dialog
        if (canWrite) {
            try {
                m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
            } catch (IOException ioe) {
                // there is nothing we can do about this
            }
            return;
        }
    } else if (t instanceof CmsDbEntryNotFoundException) {
        // user or group does not exist
        status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        isGuest = false;
    } else if (t instanceof CmsVfsResourceNotFoundException) {
        // file not found - display 404 error.
        status = HttpServletResponse.SC_NOT_FOUND;
    } else if (t instanceof CmsException) {
        if (t.getCause() != null) {
            t = t.getCause();
        }
        LOG.error(t.getLocalizedMessage(), t);
    } else {
        LOG.error(t.getLocalizedMessage(), t);
    }

    if (status < 1) {
        // error code not set - set "internal server error" (500)
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    res.setStatus(status);

    try {
        if ((cms != null) && (cms.getRequestContext().getCurrentUser() != null)) {
            isGuest = isGuest && (cms.getRequestContext().getCurrentUser().isGuestUser()
                    || cms.userInGroup(cms.getRequestContext().getCurrentUser().getName(),
                            OpenCms.getDefaultUsers().getGroupGuests()));
        }
    } catch (CmsException e) {
        // result is false
        LOG.error(e.getLocalizedMessage(), e);
    }

    if (canWrite) {
        res.setContentType("text/html");
        CmsRequestUtil.setNoCacheHeaders(res);
        if (!isGuest && (cms != null) && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
            try {
                res.setStatus(HttpServletResponse.SC_OK);
                res.getWriter().print(createErrorBox(t, req, cms));
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        } else {
            try {
                res.sendError(status, t.toString());
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:com.jsmartframework.web.manager.FilterControl.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpRequest.setCharacterEncoding(ENCODING);
    httpResponse.setCharacterEncoding(ENCODING);

    // Initiate bean context based on current thread instance
    WebContext.initCurrentInstance(httpRequest, httpResponse);

    // Instantiate request scoped authentication bean
    HANDLER.instantiateAuthBean(httpRequest);

    // Instantiate web security for request extra validation
    HANDLER.instantiateWebSecurity(httpRequest);

    // Anonymous subclass to wrap HTTP response to print output
    WebFilterResponseWrapper responseWrapper = new WebFilterResponseWrapper(httpResponse);

    Throwable throwable = null;//from ww w .j  av a 2  s .co m
    try {
        filterChain.doFilter(request, responseWrapper);
    } catch (Throwable thrown) {
        throwable = thrown;
        thrown.printStackTrace();
    }

    // Finalize request scoped web and auth beans
    HANDLER.finalizeBeans(httpRequest, responseWrapper);

    // Check if response was written before closing the WebContext
    boolean responseWritten = WebContext.isResponseWritten();

    // Close bean context based on current thread instance
    WebContext.closeCurrentInstance();

    // Case AsyncBean or RequestPath process was started it cannot proceed because it will not provide HTML via framework
    if (httpRequest.isAsyncStarted() || responseWritten) {

        // Generate response value after flushing the response wrapper buffer
        responseWrapper.flushBuffer();
        String responseVal = responseWrapper.toString();

        // Close current outputStream on responseWrapper
        responseWrapper.close();

        // Write the response value on real response object
        if (!httpResponse.isCommitted()) {
            httpResponse.getWriter().write(responseVal);
        }

        // Case internal server error
        if (throwable != null) {
            if (throwable instanceof IOException) {
                throw new IOException(throwable);
            }
            throw new ServletException(throwable);
        }
        return;
    }

    // Add Ajax headers to control redirect and reset
    addAjaxHeaders(httpRequest, responseWrapper);

    // Generate HTML after flushing the response wrapper buffer
    responseWrapper.flushBuffer();
    String html = completeHtml(httpRequest, responseWrapper);

    // Close current outputStream on responseWrapper
    responseWrapper.close();

    // Case internal server error
    if (throwable != null) {
        responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        if (throwable instanceof IOException) {
            throw new IOException(throwable);
        }
        throw new ServletException(throwable);
    }

    if (StringUtils.isBlank(html)) {
        return;
    }

    if (CONFIG.getContent().isPrintHtml()) {
        LOGGER.log(Level.INFO, html);
    }

    // Compress html to better load performance
    HtmlCompress compressHtml = CONFIG.getContent().getCompressHtml();
    if (compressHtml.isCompressHtml()) {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setRemoveComments(!compressHtml.isSkipComments());
        html = compressor.compress(html);
    }

    // Write our modified text to the real response
    if (!httpResponse.isCommitted()) {
        httpResponse.setContentLength(html.getBytes().length);
        httpResponse.getWriter().write(html);
    }
}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

/**
 * Respond to data posting requests./*from  ww w. j  a  va2s . c om*/
 * 
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    int stat = PortalHandler.NEXT;
    try {
        basicAuth.doLogin(req);
        if (!ToolRenderService.preprocess(this, req, res, getServletContext())) {
            // System.err.println("POST FAILED, REDIRECT ?");
            return;
        }

        // Check to see if the pre-process step has redirected us - if so,
        // our work is done here - we will likely come back again to finish
        // our
        // work. T

        if (res.isCommitted()) {
            return;
        }

        // get the Sakai session
        Session session = SessionManager.getCurrentSession();

        // recognize what to do from the path
        String option = URLUtils.getSafePathInfo(req);

        // if missing, we have a stray post
        if ((option == null) || ("/".equals(option))) {
            doError(req, res, session, ERROR_SITE);
            return;
        }

        // get the parts (the first will be "")
        String[] parts = option.split("/");

        Map<String, PortalHandler> handlerMap = portalService.getHandlerMap(this);

        // Look up handler and dispatch
        PortalHandler ph = handlerMap.get(parts[1]);
        if (ph != null) {
            stat = ph.doPost(parts, req, res, session);
            if (res.isCommitted()) {
                return;
            }
        }
        if (stat == PortalHandler.NEXT) {

            List<PortalHandler> urlHandlers;
            for (Iterator<PortalHandler> i = handlerMap.values().iterator(); i.hasNext();) {
                ph = i.next();
                stat = ph.doPost(parts, req, res, session);
                if (res.isCommitted()) {
                    return;
                }
                // this should be
                if (stat != PortalHandler.NEXT) {
                    break;
                }

            }
        }
        if (stat == PortalHandler.NEXT) {
            doError(req, res, session, Portal.ERROR_SITE);
        }

    } catch (Throwable t) {
        doThrowableError(req, res, t);
    }
}

From source file:org.josso.jaspi.agent.JASPISSOAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    HttpServletRequest hreq = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse hres = (HttpServletResponse) messageInfo.getResponseMessage();

    if (log.isDebugEnabled()) {
        log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }/*  ww w . j a v a 2 s.  co m*/

    try {
        // ------------------------------------------------------------------
        // 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)) {
            if (log.isDebugEnabled()) {
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());
            }
            AuthStatus status = AuthStatus.SUCCESS;
            return status;
        }

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

        // Get our session ...
        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));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

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

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

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

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap == null) {
            synchronized (this) {
                sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
                if (sessionMap == null) {
                    sessionMap = Collections.synchronizedMap(new HashMap());
                    hreq.getSession().getServletContext().setAttribute(KEY_SESSION_MAP, sessionMap);
                }
            }
        }

        LocalSession localSession = (LocalSession) sessionMap.get(session.getId());
        if (localSession == null) {
            localSession = new JASPILocalSession(session);
            // 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.getId(), localSession);

        }

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

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

            _agent.processRequest(customAuthRequest);

            // Request is authorized
            return AuthStatus.SEND_CONTINUE;
        }

        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 = this.getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                AuthStatus status = AuthStatus.SEND_CONTINUE;
                return status;
            }

            // 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 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));
                    //hreq.getRequestDispatcher(loginUrl).forward(hreq, hres);
                    AuthStatus status = AuthStatus.SEND_CONTINUE;
                    return status;
                } 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");
                AuthStatus status = AuthStatus.SUCCESS;
                return status;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            // Ignored resources are authorized
            return AuthStatus.SUCCESS;
        }

        // This URI should be protected by SSO, go on ...
        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 authenticated 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);

            JASPISSOAgentRequest relayRequest;

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

            relayRequest = (JASPISSOAgentRequest) 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!
                if (log.isDebugEnabled()) {
                    log.debug("Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                }
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            } else {
                // Add the SSOUser as a Principal
                if (!clientSubject.getPrincipals().contains(entry.principal)) {
                    clientSubject.getPrincipals().add(entry.principal);
                }
                SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId,
                        relayRequest.getNodeId());
                List<String> rolesList = new ArrayList<String>();

                for (int i = 0; i < ssoRolePrincipals.length; i++) {
                    if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                        continue;
                    }
                    rolesList.add(ssoRolePrincipals[i].getName());

                    clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                    log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
                }

                registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                        rolesList.toArray(new String[rolesList.size()]));
            }

            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 + "'");
                }
            }

            _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));
            }

            AuthStatus status = AuthStatus.SEND_SUCCESS;
            return status;
        }

        if (log.isDebugEnabled()) {
            log.debug("Creating Security Context for Session [" + session + "]");
        }
        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.");
        }

        // ------------------------------------------------------------------
        // 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");
            }
            // Add the SSOUser as a Principal
            if (!clientSubject.getPrincipals().contains(entry.principal)) {
                clientSubject.getPrincipals().add(entry.principal);
            }
            SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, r.getNodeId());
            List<String> rolesList = new ArrayList<String>();
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                    continue;
                }
                rolesList.add(ssoRolePrincipals[i].getName());
                clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
            }
            registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                    rolesList.toArray(new String[rolesList.size()]));
        } else {
            log.debug("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));

                // Request is authorized for this URI
                return AuthStatus.SEND_CONTINUE;
            } 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);

        clearSavedRequestURLs(hreq, hres);

        AuthStatus status = AuthStatus.SUCCESS;
        return status;
    } catch (Throwable t) {
        log.warn(t.getMessage(), t);
        throw new AuthException(t.getMessage());
        //return AuthStatus.FAILURE;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
        }
    }
}

From source file:org.apache.roller.planet.ui.rendering.servlets.FeedServlet.java

/**
 * Handle GET requests for weblog feeds.
 *//*from   ww w .ja  v  a2s. c  om*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Planet planet = null;
    PlanetGroup group = null;

    PlanetGroupFeedRequest feedRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        feedRequest = new PlanetGroupFeedRequest(request);

        planet = feedRequest.getPlanet();
        if (planet == null) {
            throw new PlanetException("unable to lookup planet: " + feedRequest.getPlanetHandle());
        }

        group = feedRequest.getGroup();
        if (group == null) {
            throw new PlanetException("unable to lookup group: " + feedRequest.getGroupHandle());
        }

    } catch (Exception e) {
        // invalid feed request format or weblog doesn't exist
        log.debug("error creating weblog feed request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // set content type
    String accepts = request.getHeader("Accept");
    String userAgent = request.getHeader("User-Agent");
    if (accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null
            && userAgent.startsWith("Mozilla")) {
        // client is a browser and feed style is enabled so we want 
        // browsers to load the page rather than popping up the download 
        // dialog, so we provide a content-type that browsers will display
        response.setContentType("text/xml");
    } else if ("rss".equals(feedRequest.getFormat())) {
        response.setContentType("application/rss+xml; charset=utf-8");
    } else if ("atom".equals(feedRequest.getFormat())) {
        response.setContentType("application/atom+xml; charset=utf-8");
    }

    // looks like we need to render content
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();
        initData.put("planetRequest", feedRequest);

        // Load models for feeds
        String feedModels = PlanetConfig.getProperty("rendering.feedModels");
        ModelLoader.loadModels(feedModels, model, initData, true);

    } catch (PlanetException ex) {
        log.error("ERROR loading model for page", ex);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");

        String templateFile = null;
        if ("rss".equals(feedRequest.getFormat())) {
            templateFile = "group-rss.vm";
        } else if ("atom".equals(feedRequest.getFormat())) {
            templateFile = "group-atom.vm";
        }

        Template template = new StaticTemplate(templateFile, null, "velocity");
        renderer = RendererManager.getRenderer(template);
    } catch (Exception e) {
        // nobody wants to render my content :(

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content.  use default size of about 24K for a standard page
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for group-atom.vm", e);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process

    // flush rendered content to response
    log.debug("Flushing response output");
    //response.setContentLength(rendererOutput.getContent().length);
    //response.getOutputStream().write(rendererOutput.getContent());

    log.debug("Exiting");
}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc./*w w  w. ja v  a  2 s  .c  o m*/
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponse(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
            //String resp = Messages.getMessage("noData00");
            //res.setContentLength((int) resp.getBytes().length);
            //res.getWriter().print(resp);
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
            // log.debug("Returned Content-Length:" +
            //          responseMsg.getContentLength());
        }

        try {
            res.setContentType(contentType);

            /* My understand of Content-Length
             * HTTP 1.0
             *   -Required for requests, but optional for responses.
             * HTTP 1.1
             *  - Either Content-Length or HTTP Chunking is required.
             *   Most servlet engines will do chunking if content-length is not specified.
             *
             *
             */

            //if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary.
            //     res.setContentLength(responseMsg.getContentLength());

            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}