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.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.java

/**
 * Customize the response for NoHandlerFoundException.
 * <p>This method delegates to {@link #handleExceptionInternal}.
 * @param ex the exception/*from  w ww .  j a  v  a  2s  .co m*/
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param webRequest the current request
 * @return a {@code ResponseEntity} instance
 * @since 4.2.8
 */
@Nullable
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex,
        HttpHeaders headers, HttpStatus status, WebRequest webRequest) {

    if (webRequest instanceof ServletWebRequest) {
        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
        HttpServletRequest request = servletWebRequest.getRequest();
        HttpServletResponse response = servletWebRequest.getResponse();
        if (response != null && response.isCommitted()) {
            if (logger.isErrorEnabled()) {
                logger.error("Async timeout for " + request.getMethod() + " [" + request.getRequestURI() + "]");
            }
            return null;
        }
    }

    return handleExceptionInternal(ex, null, headers, status, webRequest);
}

From source file:org.viafirma.cliente.filter.FirmaViafirmaFilter.java

/**
 * Avisa a la aplicacin que utiliza este filtro de que la auntenticacin ha
 * sido correcta. En caso de que la aplicacin cliente considere al usuario
 * autenticado, el sistema deja parsar.// w w  w.  ja  v a2  s.c  om
 * 
 * @param chain
 * @param request
 * @param response
 * @param certificado
 * @throws ServletException
 * @throws IOException
 */
private void procesarResultado(FilterChain chain, HttpServletRequest request, HttpServletResponse response,
        FirmaInfoViafirma infoFirma) throws ServletException, IOException {
    // Avisamos a la aplicacin cliente del resultado de la firma
    boolean ok = finFirma(request, response, infoFirma);
    if (ok) {
        // todo el proceso ha funcionado correctamente.
        if (!response.isCommitted()) {
            try {
                chain.doFilter(request, response);
            } catch (ServletException e) {
                throw e;
            }
        }
    } else if (!response.isCommitted()) {// si el process no ha hecho
        // ninguna redireccin.
        // el sistema no ha podido autenticar al usuario aunque tenga un
        // certificado correcto.
        // redireccionamos hacia error401 con un codigo de error.
        request.getRequestDispatcher(ConfigUtil.getInstance().getUriError()).forward(request, response);
    }
}

From source file:net.prasenjit.auth.config.CustomAjaxAwareHandler.java

/** {@inheritDoc} */
@Override//from   www . java2s .com
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    request.setAttribute("javax.servlet.error.status_code", HttpServletResponse.SC_FORBIDDEN);
    request.setAttribute("org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.ERROR",
            accessDeniedException);
    if (accessDeniedException instanceof CsrfException && !response.isCommitted()) {
        // Remove the session cookie so that client knows it's time to obtain a new CSRF token
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, "");
        cookie.setMaxAge(0);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    delegatedAccessDeniedHandler.handle(request, response, accessDeniedException);
}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // don't do anything if already processed
    if (response.isCommitted() || baseRequest.isHandled())
        return;/*  w  w  w .j a va  2 s  . co  m*/

    final Iterator<Handler> handlers = this.handlers.iterator();
    if (!handlers.hasNext())
        return;

    final ThroughputMetric requestsMetric = metrics.getRequestsMetric();
    final long requestStart = requestsMetric.requestStarted();
    try {
        doHandle(target, baseRequest, request, response);
        if (response instanceof Response) {
            final int status = ((Response) response).getStatus();
            if (HttpStatus.isServerError(status)) {
                metrics.getRequestsMetric().requestFailed();
                metrics.error(status, ((Response) response).getReason());
            } else {
                metrics.getRequestsMetric().requestFinished(((Response) response).getContentCount(),
                        System.currentTimeMillis() - requestStart);
            }
        } else {
            metrics.getRequestsMetric().requestFinished(0, System.currentTimeMillis() - requestStart);
        }
    } catch (final EofException | RuntimeIOException | ContinuationThrowable e) {
        metrics.getRequestsMetric().requestFailed();
        throw e;
    } catch (final Exception e) {
        metrics.getRequestsMetric().requestFailed();

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type))) {
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            if (e instanceof ServletException)
                throw (ServletException) e;
        }

        // handle or log exception
        else if (e instanceof RuntimeIOException)
            throw (RuntimeIOException) e;
        else if (e instanceof EofException)
            throw (EofException) e;
        else if ((e instanceof IOException) || (e instanceof UnavailableException)
                || (e instanceof IllegalStateException)) {
            if (Platform.inDebugMode()) {
                LOG.debug("Exception processing request {}: {}", request.getRequestURI(),
                        ExceptionUtils.getMessage(e), e);
                LOG.debug(request.toString());
            }
        } else {
            LOG.error("Exception processing request {}: {}",
                    new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
            if (Platform.inDebugMode()) {
                LOG.debug(request.toString());
            }
        }

        // send error response if possible
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            if (e instanceof UnavailableException) {
                final UnavailableException ue = (UnavailableException) e;
                if (ue.isPermanent()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
                }
            } else if (e instanceof IllegalStateException) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } else {
            // give up
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    } catch (final Error e) {
        metrics.getRequestsMetric().requestFailed();

        // only handle some errors
        if (!((e instanceof LinkageError) || (e instanceof AssertionError)))
            throw e;

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type)))
            throw e;

        LOG.error("Error processing request {}: {}",
                new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
        if (JettyDebug.debug) {
            LOG.debug(request.toString());
        }

        // TODO httpResponse.getHttpConnection().forceClose();
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } else {
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:com.alibaba.dubbo.container.page.PageServlet.java

@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (!response.isCommitted()) {// ????
        PrintWriter writer = response.getWriter();
        String uri = request.getRequestURI();
        boolean isHtml = false;
        if (uri == null || uri.length() == 0 || "/".equals(uri)) {
            uri = "index";
            isHtml = true;// w  ww . jav a 2  s.  c  o m
        } else {
            if (uri.startsWith("/")) {
                uri = uri.substring(1);
            }
            if (uri.endsWith(".html")) {
                uri = uri.substring(0, uri.length() - ".html".length());
                isHtml = true;
            }
        }
        if (uri.endsWith("favicon.ico")) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ExtensionLoader<PageHandler> pageHandlerLoader = ExtensionLoader.getExtensionLoader(PageHandler.class);
        PageHandler pageHandler = pageHandlerLoader.hasExtension(uri) ? pageHandlerLoader.getExtension(uri)
                : null;
        if (isHtml) {// 
            writer.println("<html><head><title>Dubbo</title>");
            // writer.println("<link href=\"http://img3.douban.com/f/shire/25fe80f630af51c20b86da942fe012806db64132/css/core.css\" rel=\"stylesheet\">");
            // writer.println("<link href=\"http://img3.douban.com/f/shire/86e0773ca9b58697ddaae8e7a3b80ed1f3e909db/css/core/_init_.css\" rel=\"stylesheet\">");
            // writer.println("<link href=\"http://img3.douban.com/f/shire/645962960690dcfe678a90ab38dc9778a920e073/css/grids.css\" rel=\"stylesheet\">");
            // writer.println("<link href=\"http://img3.douban.com/f/shire/d1c3d122a1fb3d53a67b60fb3b5026a6da752dc8/css/platform/app.css\" rel=\"stylesheet\">");
            // writer.println("<link href=\"http://img3.douban.com/f/shire/55ef00473986e7ca5ef23a7941da807608548815/css/platform/markdown.css\" rel=\"stylesheet\">");
            writer.println(
                    "<style type=\"text/css\">html, body {margin: 10;padding: 0;background-color: #6D838C;font-family: Arial, Verdana;font-size: 12px;color: #FFFFFF;text-align: center;vertical-align: middle;word-break: break-all; } table {width: 90%; margin: 0px auto;border-collapse: collapse;border: 2px solid #FFFFFF; } thead tr {background-color: #253c46; } tbody tr {background-color: #8da5af; } th {padding-top: 4px;padding-bottom: 4px;font-size: 14px;height: 20px; } td {margin: 3px;padding: 3px;border: 2px solid #FFFFFF;font-size: 14px;height: 25px; } a {color: #FFFFFF;cursor: pointer;text-decoration: underline; } a:hover {text-decoration: none; }</style>");
            writer.println(
                    "<script language=\"javascript\">function openDialogWin(param){var result = window.showModalDialog(param,\"\",\"dialogHeight:600px;dialogWidth:800px;status:no; help:no;scroll:no\");}</script>");
            writer.println("</head><body>");
        }
        if (pageHandler != null) {
            Page page = null;
            try {
                String query = request.getQueryString();
                page = pageHandler.handle(URL.valueOf(request.getRequestURL().toString()
                        + (query == null || query.length() == 0 ? "" : "?" + query)));
            } catch (Throwable t) {
                logger.warn(t.getMessage(), t);
                String msg = t.getMessage();
                if (msg == null) {
                    msg = StringUtils.toString(t);
                }
                if (isHtml) {
                    writer.println("<table>");
                    writer.println("<thead>");
                    writer.println("    <tr>");
                    writer.println("        <th>Error</th>");
                    writer.println("    </tr>");
                    writer.println("</thead>");
                    writer.println("<tbody>");
                    writer.println("    <tr>");
                    writer.println("        <td>");
                    writer.println("            "
                            + msg.replace("<", "&lt;").replace(">", "&lt;").replace("\n", "<br/>"));
                    writer.println("        </td>");
                    writer.println("    </tr>");
                    writer.println("</tbody>");
                    writer.println("</table>");
                    writer.println("<br/>");
                } else {
                    writer.println(msg);
                }
            }
            if (page != null) {
                if (isHtml) {
                    String nav = page.getNavigation();
                    if (nav == null || nav.length() == 0) {
                        nav = ExtensionLoader.getExtensionLoader(PageHandler.class)
                                .getExtensionName(pageHandler);
                        nav = nav.substring(0, 1).toUpperCase() + nav.substring(1);
                    }
                    if (!"index".equals(uri)) {
                        nav = "<a href=\"/\">Home</a> &gt; " + nav;
                    }
                    writeMenu(request, writer, nav);
                    writeTable(writer, page.getTitle(), page.getColumns(), page.getRows());
                } else {
                    if (page.getRows().size() > 0 && page.getRows().get(0).size() > 0) {
                        writer.println(page.getRows().get(0).get(0));
                    }
                }
            }
        } else {
            if (isHtml) {
                writer.println("<table>");
                writer.println("<thead>");
                writer.println("    <tr>");
                writer.println("        <th>Error</th>");
                writer.println("    </tr>");
                writer.println("</thead>");
                writer.println("<tbody>");
                writer.println("    <tr>");
                writer.println("        <td>");
                writer.println(
                        "            Not found " + uri + " page. Please goto <a href=\"/\">Home</a> page.");
                writer.println("        </td>");
                writer.println("    </tr>");
                writer.println("</tbody>");
                writer.println("</table>");
                writer.println("<br/>");
            } else {
                writer.println("Not found " + uri + " page.");
            }
        }
        if (isHtml) {
            writer.println("</body></html>");
        }
        writer.flush();
    }
}

From source file:org.apache.sling.httpauth.impl.AuthorizationHeaderAuthenticationHandler.java

/**
 * Sends back the form to log into the system.
 * /*from   ww  w  . j  a va2s. com*/
 * @param request The request object
 * @param response The response object to which to send the request
 * @return <code>true</code> is always returned by this handler
 * @throws IOException if an error occurrs sending back the form.
 */
public boolean requestAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    // if the response is already committed, we have a problem !!
    if (!response.isCommitted()) {

        // reset the response
        response.reset();
        response.setStatus(HttpServletResponse.SC_OK);

        String form = getLoginForm();

        if (form != null) {

            form = replaceVariables(form, "@@contextPath@@", request.getContextPath(), "/");
            form = replaceVariables(form, "@@authType@@", request.getAuthType(), "");
            form = replaceVariables(form, "@@user@@", request.getRemoteUser(), "");

            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(form);

        } else {

            // have no form, so just send 401/UNATHORIZED for simple login
            sendUnauthorized(response);

        }

    } else {

        log.error("requestAuthentication: Response is committed, cannot request authentication");

    }

    return true;
}

From source file:info.magnolia.cms.filters.AggregatorFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    boolean success;
    try {//from  w  w w.  ja  v a  2  s . co  m
        success = collect();
    } catch (AccessDeniedException e) {
        // don't throw further, simply return error and break filter chain
        log.debug(e.getMessage(), e);
        if (!response.isCommitted()) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
        // stop the chain
        return;
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    }

    if (!success) {
        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, response is already committed. URI was {}",
                    request.getRequestURI());
        }
        // stop the chain
        return;
    }
    chain.doFilter(request, response);
}

From source file:org.meerkat.httpServer.CustomResourceHandler.java

@Override
public final void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    if (response.isCommitted() || baseRequest.isHandled()) {
        return;/*w  w  w.j  av  a2  s.  c o m*/
    } else {
        // little cheat for common request - favicon hack
        if (request.getRequestURI().equals("/favicon.ico")) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("image/x-icon");
            response.setContentLength(_favicon.length);
            response.getOutputStream().write(_favicon);
            baseRequest.setHandled(true);
            return;

        } else if (request.getRequestURI().contains("index.html")) { // Handle index.html
            String responseIndex = httpServer.getIndexPageContents();
            ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
            //response.setContentType(MimeTypes.TEXT_HTML);
            response.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.asString());
            response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
            writer.write(responseIndex);
            writer.flush();
            response.setContentLength(writer.size());
            OutputStream out = response.getOutputStream();
            writer.writeTo(out);
            out.close();
            writer.close();
            baseRequest.setHandled(true);
            return;

        } else if (request.getRequestURI().contains(eventRequestID)) { // This is a request for event
            // Get request id
            String requestRef = request.getRequestURI();
            requestRef = requestRef.substring(eventRequestID.length(), requestRef.length());
            int id = Integer.valueOf(requestRef);
            WebAppEvent ev = WebAppEvent.getEventByID(id);

            ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
            //response.setContentType(MimeTypes.TEXT_HTML);
            response.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.asString());
            if (ev != null) {
                response.setStatus(HttpServletResponse.SC_OK);

                // Escape the response
                String escapedResponse = escapeHtml3(ev.getCurrentResponse());
                //String escapedResponse = StringUtils.replaceEach(ev.getCurrentResponse(), new String[]{"&", "\"", "<", ">"}, new String[]{"&amp;", "&quot;", "&lt;", "&gt;"});

                // Prettify response
                String prettified = HtmlOperations.addPrettifier(escapedResponse);

                writer.write(prettified);
                writer.flush();
                response.setContentLength(writer.size());
                OutputStream out = response.getOutputStream();
                writer.writeTo(out);
                out.close();
                writer.close();
                baseRequest.setHandled(true);
                return;
            } else {
                writer.close();
                //log.info("-- prepare to load 404 handler..");
                processNotFound404(response, baseRequest);
            }

        }

        // Deal with request for datatables events
        else if (request.getRequestURI().contains(eventListRequest)) {

            // Get application
            String requestRef = request.getRequestURI();
            requestRef = requestRef.substring(eventListRequest.length(), requestRef.length());
            String appName = URLDecoder.decode(requestRef, "UTF-8");

            // Handle paging
            String displayStart, displayLength;
            displayStart = request.getParameter("iDisplayStart");
            displayLength = request.getParameter("iDisplayLength");
            if (displayStart == null || displayLength == null) {
                displayStart = "0";
                displayLength = "10";
            }

            // Ordering
            String orderBy = request.getParameter("iSortCol_0");
            String sortOrder = request.getParameter("sSortDir_0");
            if (orderBy == null || sortOrder == null) {
                orderBy = "0";
                sortOrder = "ASC";
            }

            String sEcho = request.getParameter("sEcho");
            if (sEcho == null) {
                sEcho = "1";
            }

            // Get number of events of application
            WebApp webapp = wac.getWebAppByName(appName);
            if (webapp == null) {
                log.info("Application " + appName + " not present!");
                webapp = new WebApp(); // prevent null in getCustomEventsList
                processNotFound404(response, baseRequest);
            }

            int numberEvents = 0;
            try {
                numberEvents = webapp.getNumberOfEvents();
            } catch (NullPointerException e) {
                log.error("Failed to get number of events from app. - " + e.getMessage());
            }

            int numberOfEventsToShow = Integer.valueOf(displayStart) + Integer.valueOf(displayLength);
            ArrayList<WebAppEvent> requestedEventList = webapp.getCustomEventsList(displayStart,
                    String.valueOf(numberOfEventsToShow), orderBy, sortOrder.toUpperCase());

            String returnResp = "{ \n" + "\"sEcho\": " + sEcho + ", \n" + "\"iTotalRecords\": \"" + numberEvents
                    + "\", \n" + "\"iTotalDisplayRecords\": \"" + numberEvents + "\", \n" + "\"aaData\": [ \n";

            Iterator<WebAppEvent> it = requestedEventList.iterator();
            WebAppEvent ev;
            String jSONresponse = returnResp;
            while (it.hasNext()) {
                ev = it.next();

                jSONresponse += "[\n" + "\"" + ev.getID() + "\", \n" + "\"" + ev.getDate() + "\", \n";

                if (ev.getStatus()) {
                    jSONresponse += "\"Online\", \n";
                } else {
                    jSONresponse += "\"Offline\", \n";
                }

                jSONresponse += "\"" + ev.getAvailability() + "\", \n" + "\"" + ev.getPageLoadTime() + "\", \n"
                        + "\"" + ev.getLatency() + "\", \n";

                jSONresponse += "\"" + ev.getHttpStatusCode() + "\", \n";

                jSONresponse += "\"" + ev.getDescription() + "\", \n" + "\"<a href=\\\"event-id-" + ev.getID()
                        + "\\\" onclick=\\\"return popitup('event-id-" + +ev.getID()
                        + "')\\\"><img src=\\\"resources/tango_edit-find.png\\\" border=\\\"0\\\" alt=\\\"\\\" /></a>\" \n"
                        + "],"; // only the one doesnt have ","
            }

            // remove the last ","
            jSONresponse = jSONresponse.substring(0, jSONresponse.length() - 1);

            jSONresponse += "\n] \n" + "}";

            ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
            //response.setContentType(MimeTypes.TEXT_JSON_UTF_8);
            response.setContentType(MimeTypes.Type.TEXT_JSON_UTF_8.asString());
            response.setStatus(HttpServletResponse.SC_OK);
            // Disable cache
            response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
            writer.write(jSONresponse);
            writer.flush();
            response.setContentLength(writer.size());
            OutputStream out = response.getOutputStream();
            writer.writeTo(out);
            out.close();
            writer.close();
            baseRequest.setHandled(true);
            return;
        }

        // Deal with request for Google Visualization events
        else if (request.getRequestURI().contains(eventListGoogleVisualizationRequest)) {
            // Get properties
            PropertiesLoader pl = new PropertiesLoader(propertiesFile);
            Properties prop = pl.getPropetiesFromFile();

            // Get the max number of records
            int maxNumberRecordsToShow = Integer.valueOf(prop.getProperty("meerkat.app.timeline.maxrecords"));

            // Get application
            String requestRef = request.getRequestURI();
            requestRef = requestRef.substring(eventListGoogleVisualizationRequest.length(),
                    requestRef.length());
            String appName = URLDecoder.decode(requestRef, "UTF-8");
            WebApp webapp = wac.getWebAppByName(appName);

            WebAppEventListIterator wAppEIt = new WebAppEventListIterator(webapp);

            String jsonResponse = wAppEIt.getJsonFormatLastXAppEvents(maxNumberRecordsToShow);

            ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
            //response.setContentType(MimeTypes.TEXT_JSON_UTF_8);
            response.setContentType(MimeTypes.Type.TEXT_JSON_UTF_8.asString());
            response.setStatus(HttpServletResponse.SC_OK);
            // Disable cache
            response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
            writer.write(jsonResponse);
            writer.flush();
            response.setContentLength(writer.size());
            OutputStream out = response.getOutputStream();
            writer.writeTo(out);
            out.close();
            writer.close();
            baseRequest.setHandled(true);
            return;
        }

        // Otherwise return not found 404
        processNotFound404(response, baseRequest);
    }
}

From source file:org.viafirma.cliente.filter.AutentifacionViafirmaFilter.java

/**
 * Avisa a la aplicacin que utiliza este filtro de que la auntenticacin ha
 * sido correcta. En caso de que la aplicacin cliente considere al usuario
 * autenticado, el sistema deja parsar./*from  w  w  w .  j  a v a  2 s. c  om*/
 * 
 * @param chain
 * @param request
 * @param response
 * @param certificado
 * @throws ServletException
 * @throws IOException
 */
private void autenticarAplicacion(FilterChain chain, HttpServletRequest request, HttpServletResponse response,
        UsuarioGenericoViafirma usuario) throws ServletException, IOException {
    // La aplicacin cliente indica si el usuario tiene permisos para su
    // sistema.
    boolean ok = procesarAutenticacion(request, response, usuario);
    if (ok) {
        // el usuario se ha autenticado y puede continuar
        if (!response.isCommitted()) {
            chain.doFilter(request, response);
        }
    } else if (!response.isCommitted()) {// si el process no ha hecho
        // ninguna redireccin.
        // el sistema no ha podido autenticar al usuario aunque tenga un
        // certificado correcto.
        // redireccionamos hacia error401 con un codigo de error.
        request.getRequestDispatcher(ConfigUtil.getInstance().getUriError()).forward(request, response);
    }
}

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

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    // If the request is already authenticated we can assume that this
    // filter is not needed

    Authentication authentication = getAuthentication(request);
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }//w ww .  j  a  v a  2s  .co  m

    if (response.isCommitted())
        logger.info("RESPONSE IS COMMITTED!");

    return createAuthentication(request);
}