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.struts.tiles.TilesRequestProcessor.java

/**
 * Do a forward using request dispatcher.
 * Uri is a valid uri. If response has already been commited, do an include
 * instead./*from   w ww .  ja  v  a  2 s .co m*/
 * @param uri Uri or Definition name to forward.
 * @param request Current page request.
 * @param response Current page response.
 */
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    if (response.isCommitted()) {
        this.doInclude(uri, request, response);

    } else {
        super.doForward(uri, request, response);
    }
}

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

/**
 * Simple little wrapper for HttpServletResponse.sendError - just to improve
 * readability of main-line code.// w  w w .j  av a 2  s  .c o  m
 * 
 * @param resp
 * @param errorCode
 * @param message
 * @throws IOException
 * @throws ResponseCommittedException
 */
protected void sendError(final HttpServletResponse resp, final int errorCode, final String message)
        throws IOException {
    if (!resp.isCommitted()) {
        resp.sendError(errorCode);
        return;
    } else {
        throw new ResponseCommittedException(message);
    }
}

From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if ((this._webSocketFactory.acceptWebSocket(request, response)) || (response.isCommitted()))
        return;/* w  w  w . j a va2 s.  c o m*/
    super.service(request, response);
}

From source file:org.alfresco.module.vti.web.actions.VtiWebDavAction.java

/**
 * <p>Process WebDAV protocol request, dispatch among set of 
 * WebDAVMethods, selects and invokes a realization of {@link WebDAVMethod}
 * to perform the requested method of WebDAV protocol.</p> 
 *
 * @param request HTTP request/*  w  ww . j  a va 2 s . com*/
 * @param response HTTP response
 */
public void execute(HttpServletRequest request, HttpServletResponse response) {
    WebDAVMethod method = getWebDAVMethod();
    try {
        FileFilterMode.setClient(Client.webdav);
        davActionExecutor.execute(method, request, response);
    } catch (WebDAVServerException e) {
        logger.debug(e);

        if (response.isCommitted()) {
            logger.warn(
                    "Could not return the status code to the client as the response has already been committed!",
                    e);
        } else {
            try {
                response.sendError(e.getHttpStatusCode());
            } catch (IOException e1) {
                throw new RuntimeException(e1);
            }
        }
    }
}

From source file:org.apache.velocity.tools.view.VelocityViewServlet.java

/**
 * Invoked when there is an error thrown in any part of doRequest() processing.
 * <br><br>/*from  ww  w  . ja v a  2 s  .  co m*/
 * Default will send a simple HTML response indicating there was a problem.
 *
 * @param request original HttpServletRequest from servlet container.
 * @param response HttpServletResponse object from servlet container.
 * @param e  Exception that was thrown by some other part of process.
 */
protected void error(HttpServletRequest request, HttpServletResponse response, Throwable e) {
    if (!response.isCommitted()) {
        return;
    }

    try {
        String path = ServletUtils.getPath(request);
        getLog().error("Error processing a template for path '" + path + "'", e);
        StringBuilder html = new StringBuilder();
        html.append("<html>\n");
        html.append("<head><title>Error</title></head>\n");
        html.append("<body>\n");
        html.append("<h2>VelocityView : Error processing a template for path '");
        html.append(path);
        html.append("'</h2>\n");

        Throwable cause = e;

        String why = cause.getMessage();
        if (why != null && why.length() > 0) {
            html.append(StringEscapeUtils.escapeHtml(why));
            html.append("\n<br>\n");
        }

        //TODO: add line/column/template info for parse errors et al

        // if it's an MIE, i want the real stack trace!
        if (cause instanceof MethodInvocationException) {
            // get the real cause
            cause = ((MethodInvocationException) cause).getWrappedThrowable();
        }

        StringWriter sw = new StringWriter();
        cause.printStackTrace(new PrintWriter(sw));

        html.append("<pre>\n");
        html.append(StringEscapeUtils.escapeHtml(sw.toString()));
        html.append("</pre>\n");
        html.append("</body>\n");
        html.append("</html>");
        response.getWriter().write(html.toString());
    } catch (Exception e2) {
        // clearly something is quite wrong.
        // let's log the new exception then give up and
        // throw a runtime exception that wraps the first one
        String msg = "Exception while printing error screen";
        getLog().error(msg, e2);
        throw new RuntimeException(msg, e);
    }
}

From source file:org.mule.transport.servlet.AbstractReceiverServlet.java

protected void writeResponseFromMessage(HttpServletResponse servletResponse, MuleMessage message)
        throws Exception {
    HttpResponse httpResponse = convertToHttpResponse(message);
    setHttpHeadersOnServletResponse(httpResponse, servletResponse);

    if (!servletResponse.isCommitted()) {
        servletResponse.setStatus(httpResponse.getStatusCode());
    }//  ww  w.j  a va  2  s  .c  o  m

    if (httpResponse.hasBody()) {
        OutputHandler outputHandler = httpResponse.getBody();
        outputHandler.write(RequestContext.getEvent(), servletResponse.getOutputStream());
    }
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 *   ? ?.//from   www  .  j ava2  s.  c  o m
 *  ? ??  ? .
 *
 * @param request   ?  web-
 * @param response   web-
 * @param handler  ,    ?
 * @param ex       ?
 * @return  web-
 */
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    // http://stackoverflow.com/questions/8271843/how-to-exclude-clientabortexception-from-simplemappingexceptionresolver
    if (ex != null && ex.getClass().getName().endsWith(".ClientAbortException") && response.isCommitted()) {
        return null;
    }

    ModelAndView modelAndView = super.doResolveException(request, response, handler, ex);
    if (modelAndView == null) {
        modelAndView = new ModelAndView("errors/common");
        prepareModelForCommonException(modelAndView, request, ex);
    }
    modelAndView.addObject("exception", ex);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return modelAndView;
}

From source file:com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java

private void sendErrorImpl(final HttpServletResponse httpServletResponse, final int statusCode,
        @Nullable final String msg) {
    try {//from  ww w . j  a  v  a  2  s.  co m
        if (!httpServletResponse.isCommitted()) {
            if (msg == null) {
                httpServletResponse.sendError(statusCode);
            } else {
                httpServletResponse.sendError(statusCode, msg);
            }
        }
    } catch (IOException e1) {
        log.error("Error occurred while sending error response : " + statusCode + " - " + msg + " because of"
                + e1.getMessage());
    }
}

From source file:org.sonar.server.ws.WebServiceEngineTest.java

@Test
public void does_not_fail_when_request_is_aborted_and_response_is_committed() throws Exception {
    ValidatingRequest request = new TestRequest().setMethod("GET")
            .setPath("/api/system/fail_with_client_abort_exception");
    Response response = mock(Response.class);
    ServletResponse.ServletStream servletStream = mock(ServletResponse.ServletStream.class);
    when(response.stream()).thenReturn(servletStream);
    HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
    when(httpServletResponse.isCommitted()).thenReturn(true);
    when(servletStream.response()).thenReturn(httpServletResponse);
    underTest.execute(request, response);

    assertThat(logTester.logs(LoggerLevel.DEBUG)).isNotEmpty();
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Serve the specified content, optionally including the data content.
 * This method handles both GET and HEAD requests.
 *///from   w  ww.  j  a  v  a2s. co  m
public static void serveContent(final MCRContent content, final HttpServletRequest request,
        final HttpServletResponse response, final ServletContext context, final Config config,
        final boolean withContent) throws IOException {

    boolean serveContent = withContent;

    final String path = getRequestPath(request);
    if (LOGGER.isDebugEnabled()) {
        if (serveContent) {
            LOGGER.debug("Serving '" + path + "' headers and data");
        } else {
            LOGGER.debug("Serving '" + path + "' headers only");
        }
    }

    if (response.isCommitted()) {
        //getContent has access to response
        return;
    }

    final boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;

    if (content == null && !isError) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return;
    }

    //Check if all conditional header validate
    if (!isError && !checkIfHeaders(request, response, content)) {
        return;
    }

    // Find content type.
    String contentType = content.getMimeType();
    final String filename = getFileName(request, content);
    if (contentType == null) {
        contentType = context.getMimeType(filename);
        content.setMimeType(contentType);
    }
    String enc = content.getEncoding();
    if (enc != null) {
        contentType = String.format(Locale.ROOT, "%s; charset=%s", contentType, enc);
    }

    String eTag = null;
    ArrayList<Range> ranges = null;
    if (!isError) {
        eTag = content.getETag();
        if (config.useAcceptRanges) {
            response.setHeader("Accept-Ranges", "bytes");
        }

        ranges = parseRange(request, response, content);

        response.setHeader("ETag", eTag);

        long lastModified = content.lastModified();
        if (lastModified >= 0) {
            response.setDateHeader("Last-Modified", lastModified);
        }
        if (serveContent) {
            String dispositionType = request.getParameter("dl") == null ? "inline" : "attachment";
            response.setHeader("Content-Disposition", dispositionType + ";filename=\"" + filename + "\"");
        }
    }

    final long contentLength = content.length();
    //No Content to serve?
    if (contentLength == 0) {
        serveContent = false;
    }

    if (content.isUsingSession()) {
        response.addHeader("Cache-Control", "private, max-age=0, must-revalidate");
        response.addHeader("Vary", "*");
    }

    try (ServletOutputStream out = serveContent ? response.getOutputStream() : null) {
        if (serveContent) {
            try {
                response.setBufferSize(config.outputBufferSize);
            } catch (final IllegalStateException e) {
                //does not matter if we fail
            }
        }
        if (response instanceof ServletResponseWrapper) {
            if (request.getHeader("Range") != null) {
                LOGGER.warn("Response is wrapped by ServletResponseWrapper, no 'Range' requests supported.");
            }
            ranges = FULL;
        }

        if (isError || (ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null
                || ranges == FULL) {
            //No ranges
            if (contentType != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentType='" + contentType + "'");
                }
                response.setContentType(contentType);
            }
            if (contentLength >= 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentLength=" + contentLength);
                }
                setContentLengthLong(response, contentLength);
            }

            if (serveContent) {
                copy(content, out, config.inputBufferSize, config.outputBufferSize);
            }

        } else {

            if (ranges == null || ranges.isEmpty()) {
                return;
            }

            // Partial content response.

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            if (ranges.size() == 1) {

                final Range range = ranges.get(0);
                response.addHeader("Content-Range",
                        "bytes " + range.start + "-" + range.end + "/" + range.length);
                final long length = range.end - range.start + 1;
                setContentLengthLong(response, length);

                if (contentType != null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("contentType='" + contentType + "'");
                    }
                    response.setContentType(contentType);
                }

                if (serveContent) {
                    copy(content, out, range, config.inputBufferSize, config.outputBufferSize);
                }

            } else {

                response.setContentType("multipart/byteranges; boundary=" + MIME_BOUNDARY);

                if (serveContent) {
                    copy(content, out, ranges.iterator(), contentType, config.inputBufferSize,
                            config.outputBufferSize);
                }
            }
        }
    }
}