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.webflow.mvc.servlet.FlowHandlerAdapter.java

/**
 * The default algorithm for handling a {@link FlowException} now handled by the Web Flow system. Only called if
 * {@link FlowHandler#handleException(FlowException, HttpServletRequest, HttpServletResponse)} returns null. This
 * implementation rethrows the exception unless it is a {@link NoSuchFlowExecutionException}. If the exception is a
 * NoSuchFlowExecutionException, this implementation attempts to start a new execution of the ended or expired flow.
 * Subclasses may override./* ww w.  j  ava2s .c om*/
 * @param flowId the id of the ended flow
 * @param e the flow exception
 * @param request the current request
 * @param response the current response
 */
protected void defaultHandleException(String flowId, FlowException e, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (e instanceof NoSuchFlowExecutionException && flowId != null) {
        if (!response.isCommitted()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Restarting a new execution of previously ended flow '" + flowId + "'");
            }
            // by default, attempt to restart the flow
            String flowUrl = flowUrlHandler.createFlowDefinitionUrl(flowId, null, request);
            sendRedirect(flowUrl, request, response);
        }
    } else {
        throw e;
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.proxy.ProxyAuthenticator.java

/**
 * Handle redirection so that context is rebuilt correctly see NXP-2060 + NXP-2064
 *///from  w ww.  j av  a2 s.  c  o  m
protected void handleRedirectToValidStartPage(HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {
    boolean isStartPageValid = false;
    if (httpRequest.getMethod().equals("GET") || httpRequest.getMethod().equals("POST")) {
        // try to keep valid start page
        NuxeoAuthenticationFilter filter = new NuxeoAuthenticationFilter();
        isStartPageValid = filter.saveRequestedURLBeforeRedirect(httpRequest, httpResponse);
    }
    HttpSession session;
    if (httpResponse.isCommitted()) {
        session = httpRequest.getSession(false);
    } else {
        session = httpRequest.getSession(true);
    }
    if (session != null && !isStartPageValid) {
        session.setAttribute(NXAuthConstants.START_PAGE_SAVE_KEY,
                LoginScreenHelper.getStartupPagePath() + "?loginRedirection=true");
    }
}

From source file:net.sf.ehcache.constructs.web.filter.CachingFilter.java

/**
 * Performs the filtering for a request. This method caches
 * based responses keyed by {@link #calculateKey(javax.servlet.http.HttpServletRequest)}
 * <p/>// w w  w  .  jav  a  2 s  .  c o m
 * By default this method will queue requests requesting the page response for a given key
 * until the first thread in the queue has completed. The request which occurs when the page
 * expires incurs the cost of waiting for the downstream processing to return the respone.
 * <p/>
 * The maximum time to wait can be configured by setting <code>setTimeoutMillis</code> on the
 * underlying <code>BlockingCache</code>.
 *
 * @param request
 * @param response
 * @param chain
 * @throws AlreadyGzippedException     if a double gzip is attempted
 * @throws AlreadyCommittedException   if the response was committed on the way in or the on the way back
 * @throws FilterNonReentrantException if an attempt is made to reenter this filter in the same request.
 * @throws LockTimeoutException        if this request is waiting on another that is populating the cache entry
 *                                     and timeouts while waiting. Only occurs if the BlockingCache has a timeout set.
 * @throws Exception                   for all other exceptions. They will be caught and logged in
 *                                     {@link Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)}
 */
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws AlreadyGzippedException, AlreadyCommittedException,
        FilterNonReentrantException, LockTimeoutException, Exception {
    if (response.isCommitted()) {
        throw new AlreadyCommittedException("Response already committed before doing buildPage.");
    }
    logRequestHeaders(request);
    PageInfo pageInfo = buildPageInfo(request, response, chain);

    //return on error or redirect code
    int statusCode = pageInfo.getStatusCode();
    if (statusCode != HttpServletResponse.SC_OK) {
        return;
    }

    if (response.isCommitted()) {
        throw new AlreadyCommittedException("Response already committed after doing buildPage"
                + "but before writing response from PageInfo.");
    }
    writeResponse(request, response, pageInfo);
}

From source file:org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.java

/**
 * Handle the case where an async request timed out.
 * <p>The default implementation sends an HTTP 503 error.
 * @param ex the {@link AsyncRequestTimeoutException }to be handled
 * @param request current HTTP request/*from   ww w. j a v a2s  .  c  o  m*/
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen
 * at the time of the exception (for example, if multipart resolution failed)
 * @return an empty ModelAndView indicating the exception was handled
 * @throws IOException potentially thrown from response.sendError()
 * @since 4.2.8
 */
protected ModelAndView handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex,
        HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException {

    if (!response.isCommitted()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (logger.isErrorEnabled()) {
        logger.error("Async timeout for " + request.getMethod() + " [" + request.getRequestURI() + "]");
    }
    return new ModelAndView();
}

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

private void handleException(HttpServletRequest request, HttpServletResponse response,
        ErrorWrapperResponse wrapped, Throwable ex) throws IOException, ServletException {
    Class<?> type = ex.getClass();
    String errorPath = getErrorPath(type);
    if (errorPath == null) {
        rethrow(ex);//from w  w  w  . j  a  va2s .com
        return;
    }
    if (response.isCommitted()) {
        handleCommittedResponse(request, ex);
        return;
    }

    forwardToErrorPage(errorPath, request, wrapped, ex);
}

From source file:org.asimba.idp.profile.catalog.CatalogProfile.java

/**
 * {@inheritDoc}//from  ww  w .  j  a v a2  s .com
 */
public void service(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse)
        throws OAException {
    ICatalog oCatalog = establishCatalogHandler(oServletRequest);

    if (oCatalog != null) {
        oCatalog.service(oServletRequest, oServletResponse);
    } else {
        String sErrorMessage = "Invalid catalog requested: " + oServletRequest.getRequestURI();
        _oLogger.warn(sErrorMessage);

        try {
            if (!oServletResponse.isCommitted()) {
                oServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sErrorMessage);
            }
        } catch (IOException ioe) {
            _oLogger.warn("Could not send response", ioe);
        }
    }

    return;
}

From source file:org.zkoss.zkgrails.ZKGrailsPageFilter.java

protected void applyDecorator(Page page, Decorator decorator, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    final String uriPath = decorator.getURIPath();
    if (uriPath != null && uriPath.endsWith(".gsp")) {
        request.setAttribute(PAGE, page);

        detectContentTypeFromPage(page, response);

        RequestDispatcher rd = request.getRequestDispatcher(decorator.getURIPath());
        if (!response.isCommitted()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rendering layout using forward: " + decorator.getURIPath());
            }/*from w ww. j  a  v a  2 s  .c  o  m*/
            rd.forward(request, response);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rendering layout using include: " + decorator.getURIPath());
            }
            request.setAttribute(GrailsApplicationAttributes.GSP_TO_RENDER, decorator.getURIPath());
            rd.include(request, response);
            request.removeAttribute(GrailsApplicationAttributes.GSP_TO_RENDER);
        }

        // set the headers specified as decorator init params
        while (decorator.getInitParameterNames().hasNext()) {
            String initParam = (String) decorator.getInitParameterNames().next();
            if (initParam.startsWith("header.")) {
                response.setHeader(initParam.substring(initParam.indexOf('.')),
                        decorator.getInitParameter(initParam));
            }
        }
        request.removeAttribute(PAGE);
    } else {

        super.applyDecorator(page, decorator, request, response);

    }
}

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

/**
 * If the {@link #REQUEST_LOGIN_PARAMETER} parameter is set this method
 * 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. If the response is already committed, an error message is
 * logged but the 401 status is not sent.
 * <p>// w  ww .  j  a v a2s  .  c o  m
 * <code>false</code> is returned if the request parameter is not set, if
 * the response is already committed or if an error occurred sending the
 * status response. The latter two situations are logged as errors.
 * 
 * @param request The request object
 * @param response The response object to which to send the request
 * @return <code>true</code> if the 401/UNAUTHORIZED method has successfully
 *         been sent.
 */
private boolean forceAuthentication(HttpServletRequest request, HttpServletResponse response) {

    // presume 401/UNAUTHORIZED has not been sent
    boolean authenticationForced = false;

    if (request.getParameter(REQUEST_LOGIN_PARAMETER) != null) {

        if (!response.isCommitted()) {

            authenticationForced = sendUnauthorized(response);

        } else {

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

        }

    } else {

        log.debug("forceAuthentication: Not forcing authentication because request parameter {} is not set",
                REQUEST_LOGIN_PARAMETER);

    }

    // true if 401/UNAUTHORIZED has been sent, false otherwise
    return authenticationForced;
}

From source file:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }/*ww  w  . jav  a 2 s  .co  m*/

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

From source file:org.n52.iceland.service.Service.java

private void logResponse(HttpServletRequest request, HttpServletResponse response, long count,
        Stopwatch stopwatch) {/*  w w w  .  j a v  a 2 s. c  o m*/
    long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
    this.serviceEventBus.submit(new OutgoingResponseEvent(request, response, count, elapsed));
    LOGGER.debug("Outgoing response for request No. {} is committed = {} (took {} ms)", count,
            response.isCommitted(), elapsed);
}