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.orderofthebee.addons.support.tools.share.LogFileHandler.java

protected void handleLogZipRequest(final List<String> filePaths, final HttpServletRequest req,
        final HttpServletResponse res, final Map<String, Object> model) throws IOException {
    try {//ww w.ja v a2s.  com
        final List<File> files = LogFileHandler.validateFilePaths(filePaths);
        final File logFileZip = TempFileProvider.createTempFile("ootbee-support-tools-logFiles", "zip");
        try {
            this.createZip(files, logFileZip);

            this.contentStreamer.streamContent(req, res, logFileZip, logFileZip.lastModified(), false,
                    "log-files.zip", model, "application/zip");
        } finally {
            // eager cleanup
            if (!logFileZip.delete()) {
                logFileZip.deleteOnExit();
            }
        }
    } catch (final WebScriptException wsex) {
        if (!res.isCommitted()) {
            res.reset();
            res.sendError(wsex.getStatus(), wsex.getMessage());
        } else {
            LOGGER.info("Could not send error via committed response", wsex);
        }
    }
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void sendInternalServerError(HttpServletRequest request, HttpServletResponse response,
        Throwable cause) throws IOException {
    if (cause != null) {
        process500HandlingCallback(request, response, cause);
        request.setAttribute(ERROR_ATTRIBUTE_KEY, cause); // for something outer process
    }//  w  w  w  . j a  v a  2  s  .  c  o  m
    try {
        if (!response.isCommitted()) { // might be committed in callback
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (IOException sendEx) {
        final String msg = "Failed to send error as '500 Error': " + sendEx.getMessage();
        if (errorLogging) {
            LOG.error(msg);
        } else {
            LOG.debug(msg);
        }
        return; // cannot help it
    }
}

From source file:org.xchain.framework.servlet.CatalogServlet.java

/**
 * Execute the proper XChain based on the incoming {@link HttpServletRequest} and sending output on the {@link HttpServletResponse}.
 * The path on the request determines which catalog to use while the method of the request determines which command to execute.
 * /*ww  w .  ja  v  a 2s. c  o  m*/
 * @param request The incoming request.
 * @param response The outgoing response.
 */
public void executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        // get the catalog name for the request.
        String catalogName = catalogNameForRequest(request);

        // get the command name for the request.
        QName commandName = commandNameForRequest(request);

        if (log.isDebugEnabled()) {
            log.debug("Executing '" + commandName + "' in catalog '" + catalogName + "'.");
        }

        // create the context for the request.
        JXPathContext context = jXPathContext(request, response);

        // execute the command.
        boolean result = CatalogFactory.getInstance().getCatalog(catalogName).getCommand(commandName)
                .execute(context);
        //      boolean result = CommandUtil.execute(catalogName, commandName, context);

        if (response.isCommitted() == false && result == false) {
            // it looks like we didn't do anything...
        }
    } catch (CatalogNotFoundException cae) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find xchain catalog.", cae);
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (CommandNotFoundException coe) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find xchain command.", coe);
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {

        if (log.isErrorEnabled()) {
            log.error("Unable to execute xchain.", e);
        }

        throw new ServletException(e);
    }
}

From source file:com.zimbra.cs.service.UserServlet.java

private void sendError(UserServletContext ctxt, HttpServletRequest req, HttpServletResponse resp,
        String message) throws IOException {
    if (resp.isCommitted()) {
        log.info("Response already committed. Skipping sending error code for response");
        return;/*from  w  w w .  j a v a2s  .c o  m*/
    }
    if (ctxt != null && !ctxt.cookieAuthHappened && ctxt.basicAuthAllowed() && !ctxt.basicAuthHappened) {
        resp.addHeader(AuthUtil.WWW_AUTHENTICATE_HEADER, getRealmHeader(req, null));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                L10nUtil.getMessage(MsgKey.errMustAuthenticate, req));
    } else if (ctxt != null && ctxt.cookieAuthHappened && !ctxt.isCsrfAuthSucceeded()
            && (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT"))) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                L10nUtil.getMessage(MsgKey.errMustAuthenticate, req));
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);
    }
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcSuccessHandler.java

protected void sendResponse(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    final RPCRequest rpcRequest;
    final String responsePayload;

    rpcRequest = AbstractRpcAuthenticationProcessingFilter.getRpcRequest(request);
    if (rpcRequest == null) {
        throw new CwtRpcException("RPC request has not been stored in request ("
                + AbstractRpcAuthenticationProcessingFilter.class.getName() + " must be used)");
    }// www  . j  av  a2s  .  com

    try {
        addNoCacheResponseHeaders(request, response);
        responsePayload = RPC.encodeResponseForSuccess(rpcRequest.getMethod(),
                getResponse(request, rpcRequest, authentication), rpcRequest.getSerializationPolicy(),
                rpcRequest.getFlags());
        RPCServletUtils.writeResponse(getServletContext(), response, responsePayload, false);
    } catch (SerializationException e) {
        log.error("Serialization error while processing service request", e);
        if (!response.isCommitted()) {
            RPCServletUtils.writeResponseForUnexpectedFailure(getServletContext(), response, e);
        }
    }
}

From source file:org.focusns.common.web.page.PageFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    ////  w  ww.ja  v a 2 s . c  o  m
    try {
        String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
        if (lookupPath.equals("/") || lookupPath.equals("")) {
            lookupPath = "/index";
        }
        //
        PageFilterRequest pageFilterRequest = new PageFilterRequest(request);
        PageFilterResponse pageFilterResponse = new PageFilterResponse(response);
        pageFilterRequest.parseMatrixParameters();
        //
        PageConfig pageConfig = pageFactory.find(lookupPath, pageFilterRequest.getParameterMap());
        if (pageConfig != null) {
            // parse matrix parameters
            pageFilterRequest.setAttribute("pageConfig", pageConfig);
            pageFilterRequest.getSession().setAttribute("pageConfig", pageConfig);
            pageEngine.doRender(pageFilterRequest, pageFilterResponse);
            //
            if (response.isCommitted()) {
                return;
            }
            String layout = !StringUtils.hasText(pageConfig.getLayout()) ? defaultLayout
                    : pageConfig.getLayout();
            request.getRequestDispatcher(layout).forward(pageFilterRequest, pageFilterResponse);
            //
            return;
        }
        //
        String widgetId = request.getParameter("widgetId");
        if (widgetId != null) {
            request.setAttribute("widgetId", widgetId);
            pageEngine.doAction(request, response);
            //
            return;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    //
    filterChain.doFilter(request, response);
}

From source file:com.googlecode.jtiger.modules.ecside.filter.ECSideFilter.java

@SuppressWarnings("rawtypes")
public void handleExport(HttpServletRequest request, HttpServletResponse response, WebContext context) {
    try {/*  w ww.  j a v a2 s . co  m*/
        Object viewData = request.getAttribute(TableConstants.VIEW_DATA);
        if (viewData != null) {
            Preferences preferences = new TableProperties();
            preferences.init(null, TableModelUtils.getPreferencesLocation(context));
            String viewResolver = (String) request.getAttribute(TableConstants.VIEW_RESOLVER);
            Class classDefinition = Class.forName(viewResolver);
            ViewResolver handleExportViewResolver = (ViewResolver) classDefinition.newInstance();
            request.setAttribute(TableConstants.SERVLET_REAL_PATH, servletRealPath);
            logger.info(servletRealPath);
            handleExportViewResolver.resolveView(request, response, preferences, viewData);
            // response.flushBuffer();
            if (!response.isCommitted()) {
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.zkoss.zk.grails.web.ZKGrailsPageFilter.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;// w w  w.ja v  a  2s.  com
    }

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

    if (isZK(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.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

/**
 * Prints the error HTML page./*from www.  j a  va  2s .  com*/
 */
protected void printError(Exception ex, HttpServletResponse response) {
    int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String exceptionName = "runtime";

    if (ex instanceof CmisRuntimeException) {
        LOG.error(ex.getMessage(), ex);
    } else if (ex instanceof CmisStorageException) {
        LOG.error(ex.getMessage(), ex);
        statusCode = getErrorCode((CmisStorageException) ex);
        exceptionName = ((CmisStorageException) ex).getExceptionName();
    } else if (ex instanceof CmisBaseException) {
        statusCode = getErrorCode((CmisBaseException) ex);
        exceptionName = ((CmisBaseException) ex).getExceptionName();
    } else if (ex instanceof IOException) {
        LOG.warn(ex.getMessage(), ex);
    } else {
        LOG.error(ex.getMessage(), ex);
    }

    if (response.isCommitted()) {
        LOG.warn("Failed to send error message to client. Response is already committed.", ex);
        return;
    }

    String message = ex.getMessage();
    if (!(ex instanceof CmisBaseException)) {
        message = "An error occurred!";
    }

    try {
        response.resetBuffer();
        response.setStatus(statusCode);
        response.setContentType("text/html");
        response.setCharacterEncoding(IOUtils.UTF8);

        PrintWriter pw = response.getWriter();

        pw.print("<html><head><title>Apache Chemistry OpenCMIS - " + exceptionName + " error</title>"
                + "<style><!--H1 {font-size:24px;line-height:normal;font-weight:bold;background-color:#f0f0f0;color:#003366;border-bottom:1px solid #3c78b5;padding:2px;} "
                + "BODY {font-family:Verdana,arial,sans-serif;color:black;font-size:14px;} "
                + "HR {color:#3c78b5;height:1px;}--></style></head><body>");
        pw.print("<h1>HTTP Status " + statusCode + " - <!--exception-->" + exceptionName
                + "<!--/exception--></h1>");
        pw.print("<p><!--message-->" + StringEscapeUtils.escapeHtml(message) + "<!--/message--></p>");

        String st = ExceptionHelper.getStacktraceAsString(ex);
        if (st != null) {
            pw.print("<hr noshade='noshade'/><!--stacktrace--><pre>\n" + st
                    + "\n</pre><!--/stacktrace--><hr noshade='noshade'/>");
        }

        pw.print("</body></html>");
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        try {
            response.sendError(statusCode, message);
        } catch (Exception en) {
            // there is nothing else we can do
        }
    }
}

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

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final AggregationState aggregationState = MgnlContext.getAggregationState();

    String templateName = aggregationState.getTemplateName();
    if (StringUtils.isNotEmpty(templateName)) {
        try {/*from   www  .ja  v a  2  s .  c o  m*/
            // don't reset any existing status code, see MAGNOLIA-2005
            // response.setStatus(HttpServletResponse.SC_OK);
            if (response != MgnlContext.getWebContext().getResponse()) {
                log.warn("Context response not synced. This may lead to discrepancies in rendering.");
            }

            Node content = aggregationState.getMainContent().getJCRNode();

            // if the content isn't visible output a 404
            if (!isVisible(content, request, response, aggregationState)) {
                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());
                }
                return;
            }

            render(content, templateName, response);

            try {
                response.flushBuffer();
            } catch (IOException e) {
                // don't log at error level since tomcat typically throws a
                // org.apache.catalina.connector.ClientAbortException if the user stops loading the page
                log.debug("Exception flushing response " + e.getClass().getName() + ": " + e.getMessage(), e);
            }

        } catch (RenderException e) {
            // TODO better handling of rendering exception
            // TODO dlipp: why not move this section up to the actual call to render() -> that's the only place where a RenderException could occur...
            log.error(e.getMessage(), e);
            throw new ServletException(e);
        } catch (Exception e) {
            // TODO dlipp: there's no other checked exceptions thrown in the code above - is it correct to react like that???
            log.error(e.getMessage(), e);
            if (!response.isCommitted()) {
                response.setContentType("text/html");
            }
            throw new RuntimeException(e);
        }
    } else {
        // direct request
        handleResourceRequest(aggregationState, request, response);
    }

    // TODO don't make it a dead end
    //      currently we can't process the chain because there is no content/nop servlet
    // chain.doFilter(request, response);
}