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.almende.eve.transport.http.AgentServlet.java

/**
 * Get an agents web interface Usage: GET /servlet/{agentId}.
 * /*from   ww  w .  ja va  2  s . com*/
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String uri = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(uri));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    String resource = httpTransport.getAgentResource(uri);

    // if no agentId is found, return generic information on servlet usage
    if (agentId == null || agentId.equals("")) {
        resp.getWriter().write(getServletDocs());
        resp.setContentType("text/plain");
        return;
    }

    // check if the agent exists
    try {
        if (!host.hasAgent(agentId)) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Agent with id '" + agentId + "' not found.");
            return;
        }
    } catch (final Exception e) {
        throw new ServletException(e);
    }

    // If this is a handshake request, handle it.
    if (handleHandShake(req, resp)) {
        return;
    }

    try {
        if (host.getAgent(agentId).hasPrivate() && !handleSession(req, resp)) {
            if (!resp.isCommitted()) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
            return;
        }
    } catch (final Exception e1) {
        LOG.log(Level.WARNING, "", e1);
    }
    // get the resource name from the end of the url
    if (resource == null || resource.equals("")) {
        if (!uri.endsWith("/") && !resp.isCommitted()) {
            final String redirect = uri + "/";
            resp.sendRedirect(redirect);
            return;
        }
        resource = "index.html";
    }
    final String extension = resource.substring(resource.lastIndexOf('.') + 1);

    if (resource.equals("events")) {
        //TODO: fix this again.
    } else {
        // load the resource
        final String mimetype = StreamingUtil.getMimeType(extension);
        final String filename = RESOURCES + resource;
        final InputStream is = this.getClass().getResourceAsStream(filename);
        if (is != null) {
            StreamingUtil.streamBinaryData(is, mimetype, resp);
        } else {
            throw new ServletException("Resource '" + resource + "' not found");
        }
    }
}

From source file:net.hedtech.banner.filters.ZKPageFilter2.java

@Override
public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) rq;
    HttpServletResponse response = (HttpServletResponse) rs;
    ServletContext servletContext = filterConfig.getServletContext();

    SiteMeshWebAppContext webAppContext = new SiteMeshWebAppContext(request, response, servletContext);

    if (filterAlreadyAppliedForRequest(request)) {
        // Prior to Servlet 2.4 spec, it was unspecified whether the filter should be called again upon an include().
        chain.doFilter(request, response);
        return;//from w  ww.j av  a 2 s  .c  o m
    }

    if (isRoot(request)) {
        //request.getRequestDispatcher("/").forward(request,response);
        String redirectURL = (String) Holders.getFlatConfig()
                .get("bannerxe.admin.login.rootContextRedirectURL");
        if (null != redirectURL && !"".equals(redirectURL)) {
            response.sendRedirect(redirectURL);
        } else {
            response.sendRedirect("banner.zul?page=mainPage");
        }
        return;
    }

    if (isZUL(request)) {

        applyFormContext(request);

        //
        // TODO if disable live
        //
        Content content = obtainContent(contentProcessor, webAppContext, request, response, chain);
        if (content == null || response.isCommitted()) {
            return;
        }
        //applyLive(request, content);
        new GrailsNoDecorator().render(content, webAppContext);
        return;
    }

    if (isZK(request)) {
        applyFormContext(request);
        chain.doFilter(request, response);
        return;
    }

    if (!contentProcessor.handles(webAppContext)) {
        // Optimization: If the content doesn't need to be processed, bypass SiteMesh.
        chain.doFilter(request, response);
        return;
    }

    // clear the page in case it is already present
    request.removeAttribute(RequestConstants.PAGE);

    if (containerTweaks.shouldAutoCreateSession()) {
        request.getSession(true);
    }

    boolean dispatched = false;
    try {
        persistenceInterceptor.init();
        Content content = obtainContent(contentProcessor, webAppContext, request, response, chain);
        if (content == null || response.isCommitted()) {
            return;
        }
        // applyLive(request, content);
        detectContentTypeFromPage(content, response);
        com.opensymphony.module.sitemesh.Decorator decorator = decoratorMapper.getDecorator(request,
                GSPSitemeshPage.content2htmlPage(content));
        if (decorator instanceof Decorator) {
            ((Decorator) decorator).render(content, webAppContext);
        } else {
            new OldDecorator2NewDecorator(decorator).render(content, webAppContext);
        }
        dispatched = true;
    } catch (IllegalStateException e) {
        // Some containers (such as WebLogic) throw an IllegalStateException when an error page is served.
        // It may be ok to ignore this. However, for safety it is propegated if possible.
        if (!containerTweaks.shouldIgnoreIllegalStateExceptionOnErrorPage()) {
            throw e;
        }
    } finally {
        if (!dispatched) {
            // an error occured
            request.setAttribute(ALREADY_APPLIED_KEY, null);
        }
        if (persistenceInterceptor.isOpen()) {
            persistenceInterceptor.flush();
            persistenceInterceptor.destroy();
        }
    }
}

From source file:com.alfaariss.oa.profile.saml2.SAML2Profile.java

/**
 * Process a SAML2 message or query./*from   w w  w.  jav  a  2s  .c o  m*/
 * @see IService#service(javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    try {
        ISAML2Profile samlProfile = resolveSAMLProfile(servletRequest);
        if (samlProfile != null) {
            //Process SAML using a profile
            samlProfile.process(servletRequest, servletResponse);
        } else {
            String sRequestURI = servletRequest.getRequestURI();

            //remove a trailing '/' from the URL if it is available
            if (sRequestURI.endsWith("/"))
                sRequestURI = sRequestURI.substring(0, sRequestURI.length() - 1);

            String sContextPath = servletRequest.getContextPath();
            String sServletPath = servletRequest.getServletPath();

            int iBaseURILength = sContextPath.length() + sServletPath.length() + "/".length() + _sID.length();

            if (sRequestURI.length() == iBaseURILength) { //DD The metadata can be requested by accessing the root of the SAML2 profile
                _logger.debug("Supplying Metadata");
                handleMetaData(servletResponse);
            } else {
                String sRequestURL = servletRequest.getRequestURL().toString();
                _logger.debug("No SAML Profile found for request and no metadata requested: " + sRequestURL);
                try {
                    if (!servletResponse.isCommitted())
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                } catch (IOException e1) {
                    _logger.warn("Could not send response", e1);
                }
            }
        }
    } catch (OAException e) //Internal error
    {
        throw e;
    } catch (Exception e) //Unknown internal error
    {
        _logger.fatal("Internal error during service", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static void service_ActionErrorRedirect(String id_action, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response) {
    String redirectURI = "";
    try {/*ww  w . ja  v a 2  s.c  om*/
        i_action action_instance = getAction_config().actionFactory(id_action, request.getSession(),
                request.getSession().getServletContext());
        redirectURI = action_instance.get_infoaction().getError();
        if (redirectURI.equals("")) {
            if (getAction_config() == null || getAction_config().getError() == null
                    || getAction_config().getError().equals(""))
                redirectURI = "";
            else
                redirectURI = getAction_config().getError();
        }
        if (!response.isCommitted())
            servletContext.getRequestDispatcher(redirectURI).forward(request, response);
        else
            servletContext.getRequestDispatcher(redirectURI).include(request, response);

    } catch (Exception ex) {
        writeLog(request,
                "Controller generic redirect error. Action: [" + id_action + "] URI: [" + redirectURI + "]");
    }
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.java

/**
 * Invokes the action defined by the webRequest for the given arguments.
 *
 * @param controller The controller instance
 * @param actionName The current action//  w  w w .  j a va 2  s .c  om
 * @param viewName The name of the view to delegate to if necessary
 * @param webRequest the current web Request
 * @param params A map of parameters
 * @return A Spring ModelAndView instance
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected ModelAndView executeAction(GroovyObject controller, String actionName, String viewName,
        GrailsWebRequest webRequest, Map params) {

    // Step 5a: Check if there is a before interceptor if there is execute it
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    HttpServletResponse response = webRequest.getCurrentResponse();
    HttpServletRequest request = webRequest.getCurrentRequest();
    try {
        // Step 6: get action from implementation
        Object action = retrieveAction(controller, actionName, response);

        // Step 7: process the action
        Object returnValue = null;
        try {
            returnValue = handleAction(controller, action, request, response, params);
            for (ActionResultTransformer actionResultTransformer : actionResultTransformers) {
                returnValue = actionResultTransformer.transformActionResult(webRequest, viewName, returnValue);
            }
        } catch (Throwable t) {
            String pluginName = GrailsPluginUtils.getPluginName(controller.getClass());
            pluginName = pluginName != null ? "in plugin [" + pluginName + "]" : "";
            throw new ControllerExecutionException(
                    "Executing action [" + actionName + "] of controller [" + controller.getClass().getName()
                            + "] " + pluginName + " caused exception: " + t.getMessage(),
                    t);
        }

        // Step 8: determine return value type and handle accordingly
        Map chainModel = initChainModel(request);

        if (response.isCommitted()
                || request.getAttribute(GrailsApplicationAttributes.REDIRECT_ISSUED) != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Response has been redirected, returning null model and view");
            }
            return null;
        }

        TokenResponseHandler handler = (TokenResponseHandler) request.getAttribute(TokenResponseHandler.KEY);
        if (handler != null && !handler.wasInvoked() && handler.wasInvalidToken()) {
            String uri = (String) request.getAttribute(SynchronizerTokensHolder.TOKEN_URI);
            if (uri == null) {
                uri = WebUtils.getForwardURI(request);
            }
            try {
                FlashScope flashScope = webRequest.getFlashScope();
                flashScope.put("invalidToken", request.getParameter(SynchronizerTokensHolder.TOKEN_KEY));
                response.sendRedirect(uri);
                return null;
            } catch (IOException e) {
                throw new ControllerExecutionException("I/O error sending redirect to URI: " + uri, e);
            }
        }

        if (request.getAttribute(FORWARD_CALLED) == null
                && request.getAttribute(GrailsApplicationAttributes.ASYNC_STARTED) == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Action [" + actionName + "] executed with result [" + returnValue
                        + "] and view name [" + viewName + "]");
            }
            ModelAndView mv = handleActionResponse(controller, returnValue, webRequest, chainModel, actionName,
                    viewName);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Action [" + actionName + "] handled, created Spring model and view [" + mv + "]");
            }
            return mv;
        }

        return null;
    } finally {
        try {
            Thread.currentThread().setContextClassLoader(cl);
        } catch (AccessControlException e) {
            // not allowed by container, probably related to WAR deployment on AppEngine. Proceed.
        }
    }
}

From source file:info.magnolia.rendering.engine.RenderingFilter.java

/**
 * Get the requested resource and copy it to the ServletOutputStream, bit by bit.
 * @param request HttpServletRequest as given by the servlet container
 * @param response HttpServletResponse as given by the servlet container
 * @throws IOException standard servlet exception
 *//*from  w w w .ja  v a  2s  .  co  m*/
protected void handleResourceRequest(AggregationState aggregationState, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    final String resourceHandle = aggregationState.getHandle();

    log.debug("handleResourceRequest, resourceHandle=\"{}\"", resourceHandle);

    if (StringUtils.isNotEmpty(resourceHandle)) {

        InputStream is = null;
        try {
            Session session = MgnlContext.getJCRSession(aggregationState.getRepository());
            is = getNodedataAsStream(resourceHandle, session, response);
            if (null != is) {
                // don't reset any existing status code, see MAGNOLIA-2005
                // response.setStatus(HttpServletResponse.SC_OK);
                sendUnCompressed(is, response);
                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
            log.debug("Exception while dispatching resource " + e.getClass().getName() + ": " + e.getMessage(),
                    e);
            return;
        } catch (Exception e) {
            log.error("Exception while dispatching resource  " + e.getClass().getName() + ": " + e.getMessage(),
                    e);
            return;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI());

    if (!response.isCommitted()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        log.info("Unable to redirect to 404 page for {}, response is already committed",
                request.getRequestURI());
    }

}

From source file:org.opencms.loader.CmsJspLoader.java

/**
 * Dispatches the current request to the OpenCms internal JSP.<p>
 * //from   ww w.jav  a2s .  c o  m
 * @param controller the current controller
 * 
 * @return the content of the processed JSP
 * 
 * @throws ServletException if inclusion does not work
 * @throws IOException if inclusion does not work
 */
protected byte[] dispatchJsp(CmsFlexController controller) throws ServletException, IOException {

    // get request / response wrappers
    CmsFlexRequest f_req = controller.getCurrentRequest();
    CmsFlexResponse f_res = controller.getCurrentResponse();

    try {
        f_req.getRequestDispatcher(controller.getCmsObject().getSitePath(controller.getCmsResource()))
                .include(f_req, f_res);
    } catch (SocketException e) {
        // uncritical, might happen if client (browser) does not wait until end of page delivery
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
    }

    byte[] result = null;
    HttpServletResponse res = controller.getTopResponse();

    if (!controller.isStreaming() && !f_res.isSuspended()) {
        try {
            // if a JSP error page was triggered the response will be already committed here
            if (!res.isCommitted() || m_errorPagesAreNotCommitted) {

                // check if the current request was done by a workplace user
                boolean isWorkplaceUser = CmsWorkplaceManager.isWorkplaceUser(f_req);

                // check if the content was modified since the last request
                if (controller.isTop() && !isWorkplaceUser
                        && CmsFlexController.isNotModifiedSince(f_req, controller.getDateLastModified())) {
                    if (f_req.getParameterMap().size() == 0) {
                        // only use "expires" header on pages that have no parameters,
                        // otherwise some browsers (e.g. IE 6) will not even try to request 
                        // updated versions of the page
                        CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                m_clientCacheMaxAge);
                    }
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }

                // get the result byte array
                result = f_res.getWriterBytes();
                HttpServletRequest req = controller.getTopRequest();
                if (req.getHeader(CmsRequestUtil.HEADER_OPENCMS_EXPORT) != null) {
                    // this is a non "on-demand" static export request, don't write to the response stream
                    req.setAttribute(CmsRequestUtil.HEADER_OPENCMS_EXPORT,
                            new Long(controller.getDateLastModified()));
                } else if (controller.isTop()) {
                    // process headers and write output if this is the "top" request/response                                  
                    res.setContentLength(result.length);
                    // check for preset error code
                    Integer errorCode = (Integer) req.getAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE);
                    if (errorCode == null) {
                        // set last modified / no cache headers only if this is not an error page
                        if (isWorkplaceUser) {
                            res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
                            CmsRequestUtil.setNoCacheHeaders(res);
                        } else {
                            // set date last modified header                        
                            CmsFlexController.setDateLastModifiedHeader(res, controller.getDateLastModified());
                            if ((f_req.getParameterMap().size() == 0)
                                    && (controller.getDateLastModified() > -1)) {
                                // only use "expires" header on pages that have no parameters
                                // and that are cachable (i.e. 'date last modified' is set)
                                // otherwise some browsers (e.g. IE 6) will not even try to request 
                                // updated versions of the page
                                CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                        m_clientCacheMaxAge);
                            }
                        }
                        // set response status to "200 - OK" (required for static export "on-demand")
                        res.setStatus(HttpServletResponse.SC_OK);
                    } else {
                        // set previously saved error code
                        res.setStatus(errorCode.intValue());
                    }
                    // process the headers
                    CmsFlexResponse.processHeaders(f_res.getHeaders(), res);
                    res.getOutputStream().write(result);
                    res.getOutputStream().flush();
                }
            }
        } catch (IllegalStateException e) {
            // uncritical, might happen if JSP error page was used
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        } catch (SocketException e) {
            // uncritical, might happen if client (browser) does not wait until end of page delivery
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        }
    }

    return result;
}

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

/**
 * Handle GET requests for weblog feeds.
 *///  w ww  .  jav  a 2s.com
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Planet planet = null;
    PlanetGroup group = null;

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

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

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

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

    // set content type
    response.setContentType("application/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", opmlRequest);

        // Load models for feeds
        String opmlModels = PlanetConfig.getProperty("rendering.opmlModels");
        ModelLoader.loadModels(opmlModels, 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");
        Template template = new StaticTemplate("opml.vm", 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 opml.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:com.alfaariss.oa.profile.saml2.profile.sso.SingleLogout.java

/**
 * @see ISAML2Profile#process(javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *///from   www  .  ja v  a 2s .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);

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

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

/**
 * All HTTP/s requests are handled here.
 * @param req HttpServletRequest/* w w w. j  a va 2s  . c  o  m*/
 * @param res HttpServletResponse
 * @throws IOException can be thrown when the servlet is unable to write to the response stream
 * @throws ServletException
 */
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    // Initialize magnolia context
    super.doGet(req, res);

    if (ConfigLoader.isBootstrapping()) {
        // @todo a nice page, with the log content...
        res.getWriter().write("Magnolia bootstrapping has failed, check bootstrap.log in magnolia/logs"); //$NON-NLS-1$
        return;
    }

    if (ModuleRegistration.getInstance().isRestartNeeded()) {
        res.sendRedirect(req.getContextPath() + "/.magnolia/pages/restart.html");
    }

    try {
        if (isAuthorized(req, res)) {

            if (redirect(req, res)) {

                return;
            }
            intercept(req, res);
            // aggregate content
            boolean success = Aggregator.collect(req);
            if (success) {

                Template template = (Template) req.getAttribute(Aggregator.TEMPLATE);

                if (template != null) {
                    try {
                        String type = template.getType();
                        TemplateRenderer renderer = TemplateRendererManager.getInstance().getRenderer(type);

                        if (renderer == null) {
                            throw new RuntimeException("No renderer found for type " + type);
                        }
                        renderer.renderTemplate(template, req, res);
                    } catch (Exception e) {
                        // @todo better handling of rendering exception
                        log.error(e.getMessage(), e);
                        if (!res.isCommitted()) {
                            res.reset();
                            res.setContentType("text/html");
                        }
                        throw new NestableRuntimeException(e);
                    }
                } else {
                    // direct request
                    req.getRequestDispatcher(DIRECT_REQUEST_RECEIVER).forward(req, res);
                }

            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Resource not found, redirecting request for [{}] to 404 URI", //$NON-NLS-1$
                            req.getRequestURI());
                }

                if (!res.isCommitted()) {
                    res.sendError(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    log.info("Unable to redirect to 404 page, response is already committed. URI was {}", //$NON-NLS-1$
                            req.getRequestURI());
                }
            }
        }
    } catch (AccessDeniedException e) {
        // don't log AccessDenied as errors, it can happen...
        log.warn(e.getMessage());
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    }
}