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.meltmedia.cadmium.servlets.ErrorPageFilter.java

/**
 * Called to render the error page, if possible.
 * // w w  w .  jav a 2 s .  c  o m
 * @param sc the status code of the error.
 * @param message the message for the error.
 * @param request the request that caused the error.
 * @param response the response that the error will be written to.
 * @throws IOException if there is a problem rendering the error page.
 */
@SuppressWarnings("deprecation")
protected void sendError(int sc, String message, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    if (400 <= sc && sc < 600 && !response.isCommitted()) {
        String[] fileNames = new String[] { "/" + Integer.toString(sc) + ".html",
                "/" + Integer.toString(sc).subSequence(0, 2) + "x.html",
                "/" + Integer.toString(sc).subSequence(0, 1) + "xx.html" };

        InputStream errorPageIn = null;
        try {
            String path = request.getRequestURI();
            while (path != null && errorPageIn == null) {
                if (path.endsWith("/")) {
                    path = path.substring(0, path.length() - 1);
                }
                for (String fileName : fileNames) {
                    if ((errorPageIn = contentService.getResourceAsStream(path + fileName)) != null) {
                        log.trace("Found error page for path {} at {}", path, path + fileName);
                        break;
                    }
                }
                if (errorPageIn == null) {
                    if (path.length() > 0) {
                        path = path.substring(0, path.lastIndexOf("/"));
                    } else {
                        path = null;
                    }
                }
            }

            // get the default page.
            if (errorPageIn == null) {
                for (String fileName : fileNames) {
                    if ((errorPageIn = ErrorPageFilter.class.getResourceAsStream(fileName)) != null) {
                        log.trace("Found error page at {}", fileName);
                        break;
                    } else if ((errorPageIn = ErrorPageFilter.class
                            .getResourceAsStream("./" + fileName)) != null) {
                        log.trace("Found error page at {}", "./" + fileName);
                        break;
                    }
                }
            }

            if (errorPageIn == null) {
                log.trace("No error page found.");
                if (message == null)
                    response.sendError(sc);
                else
                    response.sendError(sc, message);
                return;
            }

            // set the status code.
            if (message != null)
                response.setStatus(sc, message);
            else
                response.setStatus(sc);

            // create a UTF-8 reader for the error page content.
            response.setContentType(MediaType.TEXT_HTML);
            log.trace("Sending error page content to response:{}", response.getClass().getName());
            IOUtils.copy(errorPageIn, response.getOutputStream());
            log.trace("Done sending error page. {}", sc);
        } finally {
            IOUtils.closeQuietly(errorPageIn);
            IOUtils.closeQuietly(response.getOutputStream());
        }
    } else {
        if (response.isCommitted())
            log.trace("Response is committed!");
        if (message == null)
            response.sendError(sc);
        else
            response.sendError(sc, message);
    }
}

From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProcessingFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, Authentication authResult) throws IOException, ServletException {

    super.successfulAuthentication(request, response, chain, authResult);

    if (!response.isCommitted()) {
        //chain.doFilter(request, response);
    }//from w w w  . j a v a 2  s.  co  m
}

From source file:org.apache.sling.auth.core.impl.HttpBasicAuthenticationHandler.java

/**
 * Sends status <code>401</code> (Unauthorized) with a
 * <code>WWW-Authenticate</code> requesting standard HTTP header
 * authentication with the <code>Basic</code> scheme and the configured
 * realm name./*w  w w.  j  a v a  2 s .c o m*/
 *
 * @param response The response object to which to send the request
 * @return <code>true</code> if the 401/UNAUTHORIZED method has successfully
 *         been sent and the response has been committed.
 */
boolean sendUnauthorized(HttpServletResponse response) {

    if (response.isCommitted()) {

        log.error("sendUnauthorized: Cannot send 401/UNAUTHORIZED; response is already committed");

    } else {

        response.resetBuffer();

        /*
         * TODO: Check whether we have to redirect
         * If this is a GET request not targeted at the registration path
         * for which this handler is selected we have to redirect to the
         * registration path using either the provided resource attribute
         * or parameter or the current URL as the "resource" parameter
         * for the redirect and also setting the "sling:authRequestLogin"
         * parameter to "BASIC" to get the 401 response for the registration
         * path and redirect back to actual path afterwards.
         */

        // just set the status because this may be called as part of an
        // error handler in which case sendError would result in an error
        // handler loop and thus be ignored.
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader(HEADER_WWW_AUTHENTICATE,
                AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\"");

        try {
            response.flushBuffer();
            return true;
        } catch (IOException ioe) {
            log.error("sendUnauthorized: Failed requesting authentication", ioe);
        }
    }

    return false;
}

From source file:org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler.java

/**
 * Invokes the configured {@code RedirectStrategy} with the URL returned by the
 * {@code determineTargetUrl} method./*  w  w  w. j  a  v  a 2 s  .c  o  m*/
 * <p>
 * The redirect will not be performed if the response has already been committed.
 */
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    String targetUrl = determineTargetUrl(request, response, authentication);

    if (response.isCommitted()) {
        logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}

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

/**
 * Redirect based on the mapping in config/server/.node.xml
 * @param request HttpServletRequest/* w  ww. j  a  va2 s  .  c om*/
 * @param response HttpServletResponse
 * @return <code>true</code> if request has been redirected, <code>false</code> otherwise
 */
private boolean redirect(HttpServletRequest request, HttpServletResponse response) {
    String uri = this.getURIMap(request);
    if (StringUtils.isNotEmpty(uri)) {
        if (!response.isCommitted()) {

            if (uri.startsWith("redirect:")) {
                try {
                    response.sendRedirect(
                            request.getContextPath() + StringUtils.substringAfter(uri, "redirect:"));
                } catch (IOException e) {
                    log.error("Failed to redirect to {}:{}", //$NON-NLS-1$
                            new Object[] { uri, e.getMessage() });
                }
            } else {

                try {
                    request.getRequestDispatcher(uri).forward(request, response);
                } catch (Exception e) {
                    log.error("Failed to forward to {} - {}:{}", //$NON-NLS-1$
                            new Object[] { uri, ClassUtils.getShortClassName(e.getClass()), e.getMessage() });
                }
            }
        } else {
            log.warn("Response is already committed, cannot forward to {} (original URI was {})", //$NON-NLS-1$
                    uri, request.getRequestURI());
        }

        return true;
    }
    return false;
}

From source file:org.displaytag.filter.ExportDelegate.java

/**
 * Actually writes exported data. Extracts content from the Map stored in request with the
 * <code>TableTag.FILTER_CONTENT_OVERRIDE_BODY</code> key.
 * /*from   w w  w.ja  va 2s  .  c  o m*/
 * @param wrapper BufferedResponseWrapper implementation
 * @param response HttpServletResponse
 * @param request ServletRequest
 * @throws IOException exception thrown by response writer/outputStream
 */
protected static void writeExport(HttpServletResponse response, ServletRequest request,
        BufferedResponseWrapper wrapper) throws IOException {

    if (wrapper.isOutRequested()) {
        // data already written
        log.debug("Filter operating in unbuffered mode. Everything done, exiting");
        return;
    }

    // if you reach this point the PARAMETER_EXPORTING has been found, but the special header has never been set in
    // response (this is the signal from table tag that it is going to write exported data)
    log.debug("Filter operating in buffered mode. ");

    Map bean = (Map) request.getAttribute(TableTag.FILTER_CONTENT_OVERRIDE_BODY);

    if (log.isDebugEnabled()) {
        log.debug(bean);
    }

    Object pageContent = bean.get(TableTagParameters.BEAN_BODY);

    if (pageContent == null) {
        if (log.isDebugEnabled()) {
            log.debug("Filter is enabled but exported content has not been found. Maybe an error occurred?");
        }

        PrintWriter out = response.getWriter();
        out.write(wrapper.getContentAsString());
        out.flush();
        return;
    }

    // clear headers
    if (!response.isCommitted()) {
        response.reset();
    }

    String filename = (String) bean.get(TableTagParameters.BEAN_FILENAME);
    String contentType = "application/download";

    String characterEncoding = wrapper.getCharacterEncoding();
    String wrappedContentType = wrapper.getContentType();

    if (wrappedContentType != null && wrappedContentType.indexOf("charset") > -1) {
        // charset is already specified (see #921811)
        characterEncoding = StringUtils.substringAfter(wrappedContentType, "charset=");
    }

    if (characterEncoding != null && contentType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        contentType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    ExibicaoDocumento exibicao = new ExibicaoDocumento();
    exibicao.setTipoConteudo(contentType);
    exibicao.setNomeArquivo(filename);
    exibicao.setAsAttachment(true);
    if (((String) bean.get(TableTagParameters.BEAN_CONTENTTYPE)).indexOf("excel") > -1) {
        exibicao.setExtensaoArquivo(".xls");
    } else if (((String) bean.get(TableTagParameters.BEAN_CONTENTTYPE)).indexOf("csv") > -1) {
        exibicao.setExtensaoArquivo(".csv");
    } else if (((String) bean.get(TableTagParameters.BEAN_CONTENTTYPE)).indexOf("xml") > -1) {
        exibicao.setExtensaoArquivo(".xml");
    } else if (((String) bean.get(TableTagParameters.BEAN_CONTENTTYPE)).indexOf("pdf") > -1) {
        exibicao.setExtensaoArquivo(".pdf");
    }

    byte[] content;
    if (pageContent instanceof String) {
        content = ((String) pageContent).getBytes(characterEncoding);
    } else {
        content = (byte[]) pageContent;
    }

    try {
        exibicao.gerarExibicaoDocumento(response, content);
    } catch (CDException cde) {
        // TODO Tratar erro....
    }
}

From source file:de.steilerdev.myVerein.server.security.rest.RestAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
    User currentUser = (User) authentication.getPrincipal();
    logger.info("[{}] Successfully authenticated user from IP {}", currentUser,
            SecurityHelper.getClientIpAddr(request));
    clearAuthenticationAttributes(request);
    if (!response.isCommitted()) {
        Settings settings = Settings.loadSettings(settingsRepository);
        response.setHeader("System-ID", settings.getId());
        response.setHeader("System-Version", settings.getSystemVersion());
        response.setHeader("User-ID", currentUser.getId());
        response.sendError(HttpServletResponse.SC_OK, "Successfully logged in");
    }//from  w  ww  .j a  v  a2s  .  com
}

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

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

    if (!servletResponse.isCommitted()) {
        servletResponse.setStatus(httpResponse.getStatusCode());
    }/*from w  w w  .  j  a  v  a  2 s .co  m*/

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

From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    try {/*w w w  .  jav  a 2 s.  com*/
        if ("/set".equals(request.getPathInfo()))
            set(request, response);
        else if (!response.isCommitted())
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (JDOMException jE) {
        ScoreBoardManager.printMessage("XmlScoreBoardServlet ERROR: " + jE.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.springframework.boot.context.web.ErrorPageFilter.java

private void handleErrorStatus(HttpServletRequest request, HttpServletResponse response, int status,
        String message) throws ServletException, IOException {
    if (response.isCommitted()) {
        handleCommittedResponse(request, null);
        return;//  w w w  .ja  v a 2s  .c om
    }
    String errorPath = getErrorPath(this.statuses, status);
    if (errorPath == null) {
        response.sendError(status, message);
        return;
    }
    response.setStatus(status);
    setErrorAttributes(request, status, message);
    request.getRequestDispatcher(errorPath).forward(request, response);
}