Example usage for javax.servlet ServletResponse isCommitted

List of usage examples for javax.servlet ServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet ServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.acegisecurity.ui.AccessDeniedHandlerImpl.java

public void handle(ServletRequest request, ServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (errorPage != null) {
        // Put exception into request scope (perhaps of use to a view)
        ((HttpServletRequest) request).setAttribute(ACEGI_SECURITY_ACCESS_DENIED_EXCEPTION_KEY,
                accessDeniedException);/*from w w w .  java  2  s . c om*/

        // Perform RequestDispatcher "forward"
        RequestDispatcher rd = request.getRequestDispatcher(errorPage);
        rd.forward(request, response);
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                accessDeniedException.getMessage());
    }
}

From source file:org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String uri = httpRequest.getRequestURI();

    if (provider == null) {
        log.warn("No security provider available: disallowing web access to brooklyn");
        httpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/*from  www  . ja  va  2  s  . com*/
    }

    if (originalRequest.get() != null) {
        // clear the entitlement context before setting to avoid warnings
        Entitlements.clearEntitlementContext();
    } else {
        originalRequest.set(uri);
    }

    boolean authenticated = provider.isAuthenticated(httpRequest.getSession());
    if ("/logout".equals(uri) || "/v1/logout".equals(uri)) {
        httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"brooklyn\"");
        if (authenticated && httpRequest.getSession().getAttributeNames().hasMoreElements()) {
            logout(httpRequest);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/");
            log.debug("Not authenticated, forwarding request for {} to {}", uri, dispatcher);
            dispatcher.forward(httpRequest, httpResponse);
        }
        return;
    }

    if (!(httpRequest.getSession().getAttributeNames().hasMoreElements()
            && provider.isAuthenticated(httpRequest.getSession())) || "/logout".equals(originalRequest.get())) {
        authenticated = authenticate(httpRequest);
    }

    if (!authenticated) {
        httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"brooklyn\"");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Note that the attribute AUTHENTICATED_USER_SESSION_ATTRIBUTE is only set in the call to authenticate(httpRequest),
    // so must not try to get the user until that is done.
    String uid = RequestTaggingFilter.getTag();
    String user = Strings.toString(httpRequest.getSession().getAttribute(AUTHENTICATED_USER_SESSION_ATTRIBUTE));
    try {
        WebEntitlementContext entitlementContext = new WebEntitlementContext(user, httpRequest.getRemoteAddr(),
                uri, uid);
        Entitlements.setEntitlementContext(entitlementContext);

        chain.doFilter(request, response);
    } catch (Throwable e) {
        if (!response.isCommitted()) {
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        originalRequest.remove();
        Entitlements.clearEntitlementContext();
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException {

    // Reset any output that has been buffered, but keep headers/cookies
    if (response.isCommitted()) {
        if (log.isDebugEnabled())
            log.debug("  Forward on committed response --> ISE");
        throw new IllegalStateException(sm.getString("applicationDispatcher.forward.ise"));
    }//from w  ww  .j av a  2s.c o m
    try {
        response.resetBuffer();
    } catch (IllegalStateException e) {
        if (log.isDebugEnabled())
            log.debug("  Forward resetBuffer() returned ISE: " + e);
        throw e;
    }

    // Set up to handle the specified request and response
    setup(request, response, false);

    // Identify the HTTP-specific request and response objects (if any)
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;

    // Handle a non-HTTP forward by passing the existing request/response
    if ((hrequest == null) || (hresponse == null)) {

        if (log.isDebugEnabled())
            log.debug(" Non-HTTP Forward");

        processRequest(hrequest, hresponse);

    }

    // Handle an HTTP named dispatcher forward
    else if ((servletPath == null) && (pathInfo == null)) {

        if (log.isDebugEnabled())
            log.debug(" Named Dispatcher Forward");

        processRequest(request, response);

    }

    // Handle an HTTP path-based forward
    else {

        if (log.isDebugEnabled())
            log.debug(" Path Based Forward");

        ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest();
        String contextPath = context.getPath();
        wrequest.setContextPath(contextPath);
        wrequest.setRequestURI(requestURI);
        wrequest.setServletPath(servletPath);
        wrequest.setPathInfo(pathInfo);

        wrequest.setAttribute(Globals.FORWARD_REQUEST_URI_ATTR, hrequest.getRequestURI());
        wrequest.setAttribute(Globals.FORWARD_CONTEXT_PATH_ATTR, hrequest.getContextPath());
        wrequest.setAttribute(Globals.FORWARD_SERVLET_PATH_ATTR, hrequest.getServletPath());
        wrequest.setAttribute(Globals.FORWARD_PATH_INFO_ATTR, hrequest.getPathInfo());
        wrequest.setAttribute(Globals.FORWARD_QUERY_STRING_ATTR, hrequest.getQueryString());

        if (queryString != null) {
            wrequest.setQueryString(queryString);
            wrequest.setQueryParams(queryString);
        }

        processRequest(request, response);
        unwrapRequest();

    }

    // This is not a real close in order to support error processing
    if (log.isDebugEnabled())
        log.debug(" Disabling the response for futher output");

    if (response instanceof ResponseFacade) {
        ((ResponseFacade) response).finish();
    } else {
        // Servlet SRV.6.2.2. The Resquest/Response may have been wrapped
        // and may no longer be instance of RequestFacade 
        if (log.isDebugEnabled()) {
            log.debug(" The Response is vehiculed using a wrapper: " + response.getClass().getName());
        }

        // Close anyway
        try {
            PrintWriter writer = response.getWriter();
            writer.close();
        } catch (IllegalStateException e) {
            try {
                ServletOutputStream stream = response.getOutputStream();
                stream.close();
            } catch (IllegalStateException f) {
                ;
            } catch (IOException f) {
                ;
            }
        } catch (IOException e) {
            ;
        }
    }

}

From source file:org.apache.catalina.valves.ErrorReportValve.java

/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state, and output an error report is necessary.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @param context The valve context used to invoke the next valve
 *  in the current processing pipeline// w w  w  .j  a  va2s .  com
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext context)
        throws IOException, ServletException {

    // Perform the request
    context.invokeNext(request, response);

    ServletRequest sreq = (ServletRequest) request;
    Throwable throwable = (Throwable) sreq.getAttribute(Globals.EXCEPTION_ATTR);

    ServletResponse sresp = (ServletResponse) response;
    if (sresp.isCommitted()) {
        return;
    }

    if (throwable != null) {

        // The response is an error
        response.setError();

        // Reset the response (if possible)
        try {
            sresp.reset();
        } catch (IllegalStateException e) {
            ;
        }

        ServletResponse sresponse = (ServletResponse) response;
        if (sresponse instanceof HttpServletResponse)
            ((HttpServletResponse) sresponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }

    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        tt.printStackTrace();
    }

}

From source file:org.beangle.security.web.access.DefaultAccessDeniedHandler.java

public void handle(ServletRequest request, ServletResponse response, AccessDeniedException exception)
        throws IOException, ServletException {
    if (null != location) {

    }/*  ww  w  .  j  a  v  a  2 s  . c o m*/
    if (errorPage != null) {
        // Put exception into request scope (perhaps of use to a view)
        ((HttpServletRequest) request).setAttribute(ACCESS_DENIED_EXCEPTION_KEY, exception);
        // Perform RequestDispatcher "forward"
        RequestDispatcher rd = request.getRequestDispatcher(errorPage);
        rd.forward(request, response);
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, exception.getMessage());
    }
}

From source file:org.codehaus.groovy.grails.plugins.acegi.GrailsAccessDeniedHandlerImpl.java

public void handle(ServletRequest request, ServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;

    if (errorPage != null || (ajaxErrorPage != null && req.getHeader(ajaxHeader) != null)) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = req.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;//from  w ww .j a  v  a  2 s. c  om
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }

        String commonRedirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "")
                + contextPath;
        String redirectUrl = commonRedirectUrl + "";
        if (ajaxErrorPage != null && req.getHeader(ajaxHeader) != null) {
            redirectUrl = commonRedirectUrl + ajaxErrorPage;
        } else if (errorPage != null) {
            redirectUrl = commonRedirectUrl + errorPage;
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                    accessDeniedException.getMessage());
        }

        ((HttpServletResponse) response)
                .sendRedirect(((HttpServletResponse) response).encodeRedirectURL(redirectUrl));
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                accessDeniedException.getMessage());
    }
}

From source file:org.ireland.jnetty.webapp.RequestDispatcherImpl.java

@Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    // jsp/15m8/*from   w  w w .ja va 2s .  c  om*/
    if (response.isCommitted())
        throw new IllegalStateException("forward() not allowed after buffer has committed.");

    // build invocation,if not exist
    if (_forwardInvocation == null) {
        _forwardInvocation = buildForwardInvocation(_rawContextURI);
    }

    doForward((HttpServletRequest) request, (HttpServletResponse) response, _forwardInvocation);
}

From source file:org.ireland.jnetty.webapp.RequestDispatcherImpl.java

@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    // jsp/15m8//w  w  w. j av a2s . c  om
    if (response.isCommitted())
        throw new IllegalStateException("include() not allowed after buffer has committed.");

    // build invocation,if not exist
    if (_includeInvocation == null) {
        _includeInvocation = buildIncludeInvocation(_rawContextURI);
    }

    doInclude((HttpServletRequest) request, (HttpServletResponse) response, _forwardInvocation);
}

From source file:org.ireland.jnetty.webapp.RequestDispatcherImpl.java

/**
 * This method Wrap the dispatcher type of the given request to DispatcherType.ERROR.
 * //from  w  ww .ja v a2 s  .c om
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void error(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    // jsp/15m8
    if (response.isCommitted())
        throw new IllegalStateException("error() not allowed after buffer has committed.");

    // build invocation,if not exist
    if (_errorInvocation == null) {
        _errorInvocation = buildErrorInvocation(_rawContextURI);
    }

    doError((HttpServletRequest) request, (HttpServletResponse) response, _errorInvocation);
}

From source file:org.jboss.seam.mock.MockRequestDispatcher.java

public void forward(ServletRequest request, ServletResponse response) {
    if (response.isCommitted()) {
        throw new IllegalStateException("Cannot perform forward - response is already committed");
    }// w ww . ja v a  2  s .co m
    getMockHttpServletResponse(response).setForwardedUrl(this.url);
    if (logger.isDebugEnabled()) {
        logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
    }
}