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.b3log.latke.servlet.renderer.AbstractFreeMarkerRenderer.java

@Override
public void render(final RequestContext context) {
    final HttpServletResponse response = context.getResponse();
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    PrintWriter writer;/*from  w w w  .jav  a2 s  .  co  m*/
    try {
        writer = response.getWriter();
    } catch (final Exception e) {
        try {
            writer = new PrintWriter(response.getOutputStream());
        } catch (final IOException ex) {
            LOGGER.log(Level.ERROR, "Can not get response writer", ex);
            return;
        }
    }

    if (response.isCommitted()) { // response has been sent redirect
        writer.flush();
        writer.close();

        return;
    }

    final HttpServletRequest request = context.getRequest();
    final Template template = getTemplate();
    if (null == template) {
        LOGGER.log(Level.ERROR, "Not found template [{0}]", templateName);

        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.log(Level.ERROR, "Can not send error 404!", ex);
        }

        return;
    }

    try {
        dataModel.put(Keys.REQUEST, request);
        Keys.fillServer(dataModel);

        beforeRender(context);

        final String html = genHTML(context.getRequest(), dataModel, template);
        doRender(html, context.getRequest(), response);

        afterRender(context);
    } catch (final Exception e) {
        final String requestLog = Requests.getLog(request);
        LOGGER.log(Level.ERROR, "Renders template [" + templateName + "] failed [" + requestLog + "]", e);

        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (final IOException ex) {
            LOGGER.log(Level.ERROR, "Sends error 500 failed", ex);
        }
    }
}

From source file:org.sakaiproject.hybrid.tool.SiteVisitToolPlacementServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///from www . ja  v a  2s.  co m
@Override
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength", "PMD.NPathComplexity" })
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("doGet(HttpServletRequest " + req + ", HttpServletResponse " + resp + ")");
    }
    // ensure siteId getParameter
    final String siteId = req.getParameter(SITE_ID);
    if (siteId == null || "".equals(siteId)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        } else {
            throw new IllegalAccessError("HttpServletResponse.SC_BAD_REQUEST");
        }
    }
    // should we record a site visit event?
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    final boolean writeEvent = Boolean.parseBoolean(req.getParameter("writeEvent"));
    // current user
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    final String principal = sessionManager.getCurrentSession().getUserEid();
    // 1) get the Site object for siteId
    // 2) ensure user has access to Site via SiteService.getSiteVisit()
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    Site site = null;
    try {
        site = siteService.getSiteVisit(siteId);
    } catch (IdUnusedException e) {
        LOG.debug("Site not found: " + siteId, e);
        sendError(resp, HttpServletResponse.SC_NOT_FOUND, "HttpServletResponse.SC_NOT_FOUND: " + siteId);
        return;
    } catch (PermissionException e) {
        LOG.warn("Permission denied: " + principal + " could not access site " + siteId);
        sendError(resp, HttpServletResponse.SC_FORBIDDEN, "HttpServletResponse.SC_FORBIDDEN");
        return;
    }
    if (site != null) { // normal program flow
        final JSONObject json = new JSONObject();
        json.element("principal", sessionManager.getCurrentSession().getUserEid());
        final JSONObject siteJson = new JSONObject();
        siteJson.element("title", site.getTitle());
        siteJson.element("id", site.getId());
        siteJson.element("icon", site.getIconUrlFull());
        siteJson.element("skin", site.getSkin());
        siteJson.element("type", site.getType());
        // get the list of site pages
        final List<SitePage> pages = site.getOrderedPages();
        int number = 0;
        if (pages != null && canAccessAtLeastOneTool(site, pages)) {
            final JSONArray pagesArray = new JSONArray();
            for (SitePage page : pages) { // for each page
                if (!canAccessAtLeastOneTool(site, page)) {
                    continue;
                }
                final JSONObject pageJson = new JSONObject();
                pageJson.element("id", page.getId());
                pageJson.element("name", page.getTitle());
                pageJson.element("layout", page.getLayout());
                pageJson.element("number", ++number);
                pageJson.element("popup", page.isPopUp());
                // get list of tools for the page
                final List<ToolConfiguration> tools = page.getTools();
                if (tools != null && !tools.isEmpty()) {
                    pageJson.element("iconclass", "icon-" + tools.get(0).getToolId().replaceAll("[.]", "-"));
                    final JSONArray toolsArray = new JSONArray();
                    for (ToolConfiguration toolConfig : tools) {
                        // for each toolConfig
                        if (toolHelper.allowTool(site, toolConfig)) {
                            final JSONObject toolJson = new JSONObject();
                            toolJson.element("url", toolConfig.getId());
                            final Tool tool = toolConfig.getTool();
                            if (tool != null && tool.getId() != null) {
                                toolJson.element("title", tool.getTitle());
                                toolJson.element("layouthint", toolConfig.getLayoutHints());
                            } else {
                                toolJson.element("title", page.getTitle());
                            }
                            toolsArray.add(toolJson);
                        }
                    }
                    pageJson.element("tools", toolsArray);
                }
                pagesArray.add(pageJson);
            }
            siteJson.element("pages", pagesArray);
        }
        // get roles for site
        final JSONArray rolesArray = new JSONArray();
        try {
            final AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId);
            final Set<Role> roles = group.getRoles();
            for (Role role : roles) {
                final JSONObject roleJson = new JSONObject();
                roleJson.element("id", role.getId());
                roleJson.element("description", role.getDescription());
                rolesArray.add(roleJson);
            }
        } catch (GroupNotDefinedException e) {
            LOG.warn("No AuthzGroup found for site: " + siteId);
        }
        siteJson.element("roles", rolesArray);

        // write siteJson to containing json
        json.element("site", siteJson);
        // dump json to response writer
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(HttpServletResponse.SC_OK);
        json.write(resp.getWriter());
        // post events if requested
        if (writeEvent) {
            final Event presenceBegin = eventTrackingService.newEvent("pres.begin",
                    "/presence/" + siteId + "-presence", true);
            eventTrackingService.post(presenceBegin);
            final Event siteVisit = eventTrackingService.newEvent("site.visit", "/site/" + siteId, true);
            eventTrackingService.post(siteVisit);
        }
    } else {
        sendError(resp, HttpServletResponse.SC_NOT_FOUND, "HttpServletResponse.SC_NOT_FOUND: " + siteId);
        return;
    }
}

From source file:org.apache.struts.faces.application.FacesRequestProcessor.java

/**
 * <p>Set up a Faces Request if we are not already processing one.  Next,
 * create a new view if the specified <code>uri</code> is different from
 * the current view identifier.  Finally, cause the new view to be
 * rendered, and call <code>FacesContext.responseComplete()</code> to
 * indicate that this has already been done.</p>
 *
 * @param uri Context-relative path to forward to
 * @param request Current page request//from   ww w.  j  av a2 s . c  om
 * @param response Current page response
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        log.debug("doForward(" + uri + ")");
    }

    // Remove the current ActionEvent (if any)
    request.removeAttribute(Constants.ACTION_EVENT_KEY);

    // Process a Struts controller request normally
    if (isStrutsRequest(uri)) {
        if (response.isCommitted()) {
            if (log.isTraceEnabled()) {
                log.trace("  super.doInclude(" + uri + ")");
            }
            super.doInclude(uri, request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("  super.doForward(" + uri + ")");
            }
            super.doForward(uri, request, response);
        }
        return;
    }

    // Create a FacesContext for this request if necessary
    LifecycleFactory lf = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    Lifecycle lifecycle = // FIXME - alternative lifecycle ids
            lf.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
    boolean created = false;
    FacesContext context = FacesContext.getCurrentInstance();
    if (context == null) {
        if (log.isTraceEnabled()) {
            log.trace("  Creating new FacesContext for '" + uri + "'");
        }
        created = true;
        FacesContextFactory fcf = (FacesContextFactory) FactoryFinder
                .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        // HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request, uri);
        // context = fcf.getFacesContext(servlet.getServletContext(), wrapper,
        //                               response, lifecycle); 
        // Comment out the previous three lines and uncomment
        // the following two lines to test eliminating the wrapper
        context = fcf.getFacesContext(servlet.getServletContext(), request, response, lifecycle);
    }

    // Create a new view root
    ViewHandler vh = context.getApplication().getViewHandler();
    if (log.isTraceEnabled()) {
        log.trace("  Creating new view for '" + uri + "'");
    }
    context.setViewRoot(vh.createView(context, uri));

    // Cause the view to be rendered
    if (log.isTraceEnabled()) {
        log.trace("  Rendering view for '" + uri + "'");
    }
    lifecycle.render(context);
    if (created) {
        if (log.isTraceEnabled()) {
            log.trace("  Releasing context for '" + uri + "'");
        }
        context.release();
    } else {
        if (log.isTraceEnabled()) {
            log.trace("  Rendering completed");
        }
    }

}

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

/**
 * Handle GET requests for weblog feeds.
 */// w w w .j  a v a  2  s . c  om
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    // set content type
    response.setContentType("text/html; charset=utf-8");

    // initialize model
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();

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

    } catch (PlanetException ex) {
        log.error("ERROR loading model", 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");

        // what template are we going to render?
        Template template = new StaticTemplate("home.vm", null, "velocity");

        // get the Renderer
        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
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering", 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.struts.faces.application.FacesTilesRequestProcessor.java

/**
 * <p>Set up a Faces Request if we are not already processing one.  Next,
 * create a new view if the specified <code>uri</code> is different from
 * the current view identifier.  Finally, cause the new view to be
 * rendered, and call <code>FacesContext.responseComplete()</code> to
 * indicate that this has already been done.</p>
 *
 * @param uri Context-relative path to forward to
 * @param request Current page request//  w ww.  ja  va  2  s . c o m
 * @param response Current page response
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        log.debug("doForward(" + uri + ")");
    }

    // Remove the current ActionEvent (if any)
    request.removeAttribute(Constants.ACTION_EVENT_KEY);

    // Process a Struts controller request normally
    if (isStrutsRequest(uri)) {
        if (response.isCommitted()) {
            if (log.isTraceEnabled()) {
                log.trace("  super.doInclude(" + uri + ")");
            }
            super.doInclude(uri, request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("  super.doForward(" + uri + ")");
            }
            super.doForward(uri, request, response);
        }
        return;
    }

    // Create a FacesContext for this request if necessary
    LifecycleFactory lf = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    Lifecycle lifecycle = // FIXME - alternative lifecycle ids
            lf.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
    boolean created = false;
    FacesContext context = FacesContext.getCurrentInstance();
    if (context == null) {
        if (log.isTraceEnabled()) {
            log.trace("  Creating new FacesContext for '" + uri + "'");
        }
        created = true;
        FacesContextFactory fcf = (FacesContextFactory) FactoryFinder
                .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request, uri);
        context = fcf.getFacesContext(servlet.getServletContext(), wrapper, response, lifecycle);
        // Comment out the previous three lines and uncomment
        // the following two lines to test eliminating the wrapper
        // context = fcf.getFacesContext(servlet.getServletContext(),
        //                               request, response, lifecycle);
    }

    // Create a new view root
    ViewHandler vh = context.getApplication().getViewHandler();
    if (log.isTraceEnabled()) {
        log.trace("  Creating new view for '" + uri + "'");
    }
    context.setViewRoot(vh.createView(context, uri));

    // Cause the view to be rendered
    if (log.isTraceEnabled()) {
        log.trace("  Rendering view for '" + uri + "'");
    }
    lifecycle.render(context);
    if (created) {
        if (log.isTraceEnabled()) {
            log.trace("  Releasing context for '" + uri + "'");
        }
        context.release();
    } else {
        if (log.isTraceEnabled()) {
            log.trace("  Rendering completed");
        }
    }

}

From source file:cn.org.pomer.web.DirectResult.java

private void doDispatcher(HttpServletResponse response, HttpServletRequest request, String resultCodeAsLocation)
        throws IOException, ServletException {
    if (_log.isInfoEnabled()) {
        _log.info("Forwarding to location:" + resultCodeAsLocation);
    }/*from w  w  w  .ja v  a 2  s  . c  om*/

    PageContext pageContext = ServletActionContext.getPageContext();
    if (pageContext != null) {
        pageContext.include(resultCodeAsLocation);
        return;
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher(resultCodeAsLocation);
    if (dispatcher == null) {
        response.sendError(404, "result '" + resultCodeAsLocation + "' not found");
        return;
    }

    if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
        request.setAttribute("struts.view_uri", resultCodeAsLocation);
        request.setAttribute("struts.request_uri", request.getRequestURI());

        dispatcher.forward(request, response);
    } else {
        dispatcher.include(request, response);
    }
}

From source file:org.apache.struts.chain.commands.servlet.PerformForward.java

/**
 * <p>Perform the appropriate processing on the specified
 * <code>ForwardConfig</code>.</p>
 *
 * @param context       The context for this request
 * @param forwardConfig The forward to be performed
 *//*from   w w w  . j  a v a2  s  . c o m*/
protected void perform(ActionContext context, ForwardConfig forwardConfig) throws Exception {
    ServletActionContext sacontext = (ServletActionContext) context;
    String uri = forwardConfig.getPath();

    if (uri == null) {
        ActionServlet servlet = sacontext.getActionServlet();
        MessageResources resources = servlet.getInternal();

        throw new IllegalArgumentException(resources.getMessage("forwardPathNull"));
    }

    HttpServletRequest request = sacontext.getRequest();
    ServletContext servletContext = sacontext.getContext();
    HttpServletResponse response = sacontext.getResponse();

    // If the forward can be unaliased into an action, then use the path of the action
    String actionIdPath = RequestUtils.actionIdURL(forwardConfig, sacontext.getRequest(),
            sacontext.getActionServlet());
    if (actionIdPath != null) {
        uri = actionIdPath;
        ForwardConfig actionIdForwardConfig = new ForwardConfig(forwardConfig);
        actionIdForwardConfig.setPath(actionIdPath);
        forwardConfig = actionIdForwardConfig;
    }

    if (uri.startsWith("/")) {
        uri = resolveModuleRelativePath(forwardConfig, servletContext, request);
    }

    if (response.isCommitted() && !forwardConfig.getRedirect()) {
        handleAsInclude(uri, servletContext, request, response);
    } else if (forwardConfig.getRedirect()) {
        handleAsRedirect(uri, request, response);
    } else {
        handleAsForward(uri, servletContext, request, response);
    }
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void processUnexpectedFailure(HttpServletRequest request, HttpServletResponse response,
        Throwable exception) throws ServletException, IOException {
    log.error("Unexpected error while processing service request", exception);

    if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnUnexpectedException()) {
        invalidateSession(request);/* w  w  w .java2 s .  c om*/
    }
    if (!response.isCommitted()) {
        response.reset();
        addNoCacheResponseHeaders(request, response);
        RPCServletUtils.writeResponseForUnexpectedFailure(getServletContext(), response, exception);
        /*
         * Flush all remaining output to the client (client can continue
         * immediately). Also response will be marked as being committed
         * (status may be required later by a filter).
         */
        response.flushBuffer();
    }
}

From source file:org.docksidestage.dbflute.svflute.RequestLoggingFilter.java

protected void handle404NotFound(HttpServletResponse response, Request404NotFoundException notFoundEx)
        throws IOException {
    if (response.isCommitted()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("*Cannot send error as '404 Not Found' because of already committed");
        }/*from w  ww .j av a2  s  .  c  o  m*/
        return; // cannot help it
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("...Sending error as '404 Not Found' manually: " + notFoundEx.getMessage());
    }
    try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException sendEx) {
        final String msg = "Failed to send error as '404 Not Found': " + sendEx.getMessage();
        if (errorLogging) {
            LOG.error(msg);
        } else {
            LOG.debug(msg);
        }
        return; // cannot help it
    }
}