Java Code Examples for javax.servlet.ServletResponse#isCommitted()

The following examples show how to use javax.servlet.ServletResponse#isCommitted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHeaderSecurityFilter.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response.isCommitted()) {
        throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
    }

    // HSTS
    if (hstsEnabled && request.isSecure() && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
    }

    // anti click-jacking
    if (antiClickJackingEnabled && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(
                ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
    }

    // Block content type sniffing
    if (blockContentTypeSniffingEnabled && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
    }
    chain.doFilter(request, response);
}
 
Example 2
Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void forward(ServletRequest request, ServletResponse response)
    throws IOException, ServletException
{

  if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) {
    throw new ServletException("Must be http request");
  }

  if (response.isCommitted()) {
    throw new IllegalStateException(
                                    "Cannot forward request after response is committed");
  }
  response.reset();

  service((RequestImpl) request, (ResponseImpl) response);

  response.flushBuffer();
}
 
Example 3
Source File: ExpiresFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest &&
            response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString(
                        "expiresFilter.responseAlreadyCommited",
                        httpRequest.getRequestURL()));
            }
            chain.doFilter(request, response);
        } else {
            XHttpServletResponse xResponse = new XHttpServletResponse(
                    httpRequest, httpResponse);
            chain.doFilter(request, xResponse);
            if (!xResponse.isWriteResponseBodyStarted()) {
                // Empty response, manually trigger
                // onBeforeWriteResponseBody()
                onBeforeWriteResponseBody(httpRequest, xResponse);
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 4
Source File: EntityHttpServletRequest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void forward(ServletRequest request, ServletResponse response) {
    if (request == null || response == null) {
        throw new IllegalArgumentException("request and response cannot be null");
    }
    if (response.isCommitted()) {
        throw new IllegalStateException("Cannot perform forward - response is already committed");
    }
    getEntityHttpServletResponse(response).setForwardedUrl(this.url);
}
 
Example 5
Source File: GatewayServlet.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain ) throws IOException, ServletException {
  try {
    auditService.createContext();
    GatewayFilter f = filter;
    if( f != null ) {
      try {
        f.doFilter( servletRequest, servletResponse );

        /* if response is committed in case of SSO redirect no need to apply further filters */
        if(!servletResponse.isCommitted()) {
          //TODO: This should really happen naturally somehow as part of being a filter.  This way will cause problems eventually.
          chain.doFilter( servletRequest, servletResponse );
        }

      } catch( IOException | RuntimeException | ServletException e ) {
        LOG.failedToExecuteFilter( e );
        throw e;
      }
    } else {
      ((HttpServletResponse)servletResponse).setStatus( HttpServletResponse.SC_SERVICE_UNAVAILABLE );
    }
    auditLog(servletRequest, servletResponse);
  } finally {
    auditService.detachContext();
  }
}
 
Example 6
Source File: ResponseTag.java    From ontopia with Apache License 2.0 5 votes vote down vote up
/**
 * Process the start tag for this instance.
 */
@Override
public int doStartTag() throws JspTagException {

  // Get navigator application
  NavigatorApplicationIF navApp = NavigatorUtils.getNavigatorApplication(pageContext);

  // Get navigator configuration
  NavigatorConfigurationIF navConf = navApp.getConfiguration();

  // Get content type
  String ctype = content_type;
  if (content_type == null)
    ctype = navConf.getProperty(NavigatorConfigurationIF.DEF_CONTENT_TYPE, "text/html");

  // Get character encoding
  String charEnc = charset;
  if (charEnc == null)
    charEnc = navConf.getProperty(NavigatorConfigurationIF.DEF_CHAR_ENCODING, "utf-8");

  // Get response instance
  ServletResponse response = pageContext.getResponse();
  if (response != null && !response.isCommitted())

    // Set Content-type header
    if (ctype != null) {
      if (charEnc != null) {
        log.debug("set content-type to: " + ctype + "; charset=" + charEnc);
        response.setContentType(ctype + "; charset=" + charEnc);
      } else {
        log.debug("set content-type to: " + ctype);
        response.setContentType(ctype);
      }
    } else {
      log.debug("not setting content-type");
    }

  // empty tag has not to eval anything
  return SKIP_BODY;
}
 
Example 7
Source File: EntityHttpServletRequest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void forward(ServletRequest request, ServletResponse response) {
    if (request == null || response == null) {
        throw new IllegalArgumentException("request and response cannot be null");
    }
    if (response.isCommitted()) {
        throw new IllegalStateException("Cannot perform forward - response is already committed");
    }
    getEntityHttpServletResponse(response).setForwardedUrl(this.url);
}
 
Example 8
Source File: MockRequestDispatcher.java    From live-chat-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void forward(ServletRequest request, ServletResponse response) {
	if (response.isCommitted()) {
		throw new IllegalStateException("Cannot perform forward - response is already committed");
	}
	getMockHttpServletResponse(response).setForwardedUrl(this.url);
	if (logger.isDebugEnabled()) {
		logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
	}
}
 
Example 9
Source File: RewriteFilter.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites the outgoing stream to make sure URLs and headers
 * are correct. The incoming request is first processed to 
 * identify what resource we want to proxy.
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    
    if (response.isCommitted()) {
        log.info("Not proxying, already committed.");
        return;
    } else if (!(request instanceof HttpServletRequest)) {
        log.info("Request is not HttpRequest, will only handle HttpRequests.");
        return;
    } else if (!(response instanceof HttpServletResponse)) {
        log.info("Request is not HttpResponse, will only handle HttpResponses.");
        return;
    } else {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        
        Server server = serverChain.evaluate(httpRequest);
        if (server == null) {
            log.info("Could not find a rule for this request, will not do anything.");
            filterChain.doFilter(request, response);
        } else {
            httpRequest.setAttribute("proxyServer", server);
            
            String ownHostName = request.getServerName() + ":" + request.getServerPort();
            UrlRewritingResponseWrapper wrappedResponse;
            wrappedResponse = new UrlRewritingResponseWrapper(httpResponse, server, ownHostName, httpRequest.getContextPath(), serverChain);
            
            filterChain.doFilter(httpRequest, wrappedResponse);

            wrappedResponse.processStream();
        }
    }
}
 
Example 10
Source File: HttpHeaderSecurityFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
        }

        // HSTS
        if (hstsEnabled && request.isSecure()) {
            httpResponse.setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
        }

        // anti click-jacking
        if (antiClickJackingEnabled) {
            httpResponse.setHeader(ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
        }

        // Block content type sniffing
        if (blockContentTypeSniffingEnabled) {
            httpResponse.setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                    BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
        }

        // cross-site scripting filter protection
        if (xssProtectionEnabled) {
            httpResponse.setHeader(XSS_PROTECTION_HEADER_NAME, XSS_PROTECTION_HEADER_VALUE);
        }
    }

    chain.doFilter(request, response);
}
 
Example 11
Source File: ExpiresFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest &&
            response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString(
                        "expiresFilter.responseAlreadyCommited",
                        httpRequest.getRequestURL()));
            }
            chain.doFilter(request, response);
        } else {
            XHttpServletResponse xResponse = new XHttpServletResponse(
                    httpRequest, httpResponse);
            chain.doFilter(request, xResponse);
            if (!xResponse.isWriteResponseBodyStarted()) {
                // Empty response, manually trigger
                // onBeforeWriteResponseBody()
                onBeforeWriteResponseBody(httpRequest, xResponse);
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 12
Source File: MockRequestDispatcher.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void forward(ServletRequest request, ServletResponse response) {
	Assert.notNull(request, "Request must not be null");
	Assert.notNull(response, "Response must not be null");
	if (response.isCommitted()) {
		throw new IllegalStateException("Cannot perform forward - response is already committed");
	}
	getMockHttpServletResponse(response).setForwardedUrl(this.resource);
	if (logger.isDebugEnabled()) {
		logger.debug("MockRequestDispatcher: forwarding to [" + this.resource + "]");
	}
}
 
Example 13
Source File: MockRequestDispatcher.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void forward(ServletRequest request, ServletResponse response) {
	Assert.notNull(request, "Request must not be null");
	Assert.notNull(response, "Response must not be null");
	if (response.isCommitted()) {
		throw new IllegalStateException("Cannot perform forward - response is already committed");
	}
	getMockHttpServletResponse(response).setForwardedUrl(this.resource);
	if (logger.isDebugEnabled()) {
		logger.debug("MockRequestDispatcher: forwarding to [" + this.resource + "]");
	}
}
 
Example 14
Source File: ExpiresFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest &&
            response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString(
                        "expiresFilter.responseAlreadyCommited",
                        httpRequest.getRequestURL()));
            }
            chain.doFilter(request, response);
        } else {
            XHttpServletResponse xResponse = new XHttpServletResponse(
                    httpRequest, httpResponse);
            chain.doFilter(request, xResponse);
            if (!xResponse.isWriteResponseBodyStarted()) {
                // Empty response, manually trigger
                // onBeforeWriteResponseBody()
                onBeforeWriteResponseBody(httpRequest, xResponse);
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 15
Source File: RestAsyncListener.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void onTimeout(AsyncEvent event) throws IOException {
  // in this time, maybe:
  // 1.invocation in executor's queue
  // 2.already executing in executor
  // 3.already send response
  // to avoid concurrent, must lock request
  ServletRequest request = event.getSuppliedRequest();
  HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST);
  LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());

  // Waiting till executing in executor done. This operation may block container pool and make timeout requests in executor's
  // queue getting executed, and will cause bad performance. So default timeout is setting to -1 to disable timeout.
  synchronized (requestEx) {
    ServletResponse response = event.getAsyncContext().getResponse();
    if (!response.isCommitted()) {
      // invocation in executor's queue
      response.setContentType(MediaType.APPLICATION_JSON);

      // we don't know if developers declared one statusCode in contract
      // so we use cse inner statusCode here
      ((HttpServletResponse) response).setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode());
      PrintWriter out = response.getWriter();
      out.write(TIMEOUT_MESSAGE);
      response.flushBuffer();
    }

    request.removeAttribute(RestConst.REST_REQUEST);
  }

  LOGGER.error("Rest request timeout committed, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());
}
 
Example 16
Source File: SpamFilterTooFreq.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	if (!isFilter) {
		chain.doFilter(request, response);
		return;
	}

	HttpServletRequest httpRequest = (HttpServletRequest) request;

	if (!httpRequest.getRequestURI().contains("registerCode"))
		if (!isPermittedRobot(httpRequest)) {
			String path = httpRequest.getServletPath();
			if (numPattern.matcher(path).matches()) {
				int slash = path.lastIndexOf("/");
				String id = path.substring(slash + 1, path.length());
				if (!checkSpamHit(id, httpRequest)) {
					log.warn("spammer,  fetching too frequency:" + httpRequest.getRequestURI() + " remote:" + httpRequest.getRemoteAddr());
					disableSessionOnlines(httpRequest);
					if (!response.isCommitted())
						response.reset();
					HttpServletResponse httpResponse = (HttpServletResponse) response;
					httpResponse.sendError(503);
					return;
				}
			}
		}
	chain.doFilter(request, response);
	return;
}
 
Example 17
Source File: SpamFilter.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	if (safeips.contains(request.getRemoteAddr())) {
		chain.doFilter(request, response);
		return;
	}

	if (safeips.size() > 500) {
		safeips.clear();
	}

	if (iPBanListManagerIF == null)
		iPBanListManagerIF = (IPBanListManagerIF) WebAppUtil.getComponentInstance("iPBanListManager", servletContext);

	if (!httpRequest.getRequestURI().contains("registerCode")) {
		if (isSpam(httpRequest)) {
			log.debug("spammer, giving 'em a 503");
			safeips.remove(request.getRemoteAddr());
			disableSessionOnlines(httpRequest);
			if (!response.isCommitted())
				response.reset();
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			httpResponse.sendError(503);
			return;
		}
	}

	safeips.add(request.getRemoteAddr());
	chain.doFilter(request, response);
	return;
}
 
Example 18
Source File: HttpHeaderSecurityFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
        }

        // HSTS
        if (hstsEnabled && request.isSecure()) {
            httpResponse.setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
        }

        // anti click-jacking
        if (antiClickJackingEnabled) {
            httpResponse.setHeader(ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
        }

        // Block content type sniffing
        if (blockContentTypeSniffingEnabled) {
            httpResponse.setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                    BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
        }

        // cross-site scripting filter protection
        if (xssProtectionEnabled) {
            httpResponse.setHeader(XSS_PROTECTION_HEADER_NAME, XSS_PROTECTION_HEADER_VALUE);
        }
    }

    chain.doFilter(request, response);
}
 
Example 19
Source File: JCacheFilter.java    From commons-jcs with Apache License 2.0 4 votes vote down vote up
private void checkResponse(final ServletResponse servletResponse)
{
    if (servletResponse.isCommitted()) {
        throw new IllegalStateException("Response committed");
    }
}
 
Example 20
Source File: GZipServletFilter.java    From para with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) {
		// Client accepts zipped content
		if (log.isTraceEnabled()) {
			log.trace("{} Written with gzip compression", httpRequest.getRequestURL());
		}

		// Create a gzip stream
		final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
		final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

		// Handle the request
		final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout);
		wrapper.setDisableFlushBuffer(true);
		chain.doFilter(request, wrapper);
		wrapper.flush();

		gzout.close();

           // double check one more time before writing out
		// repsonse might have been committed due to error
		if (response.isCommitted()) {
			return;
		}

		// return on these special cases when content is empty or unchanged
		switch (wrapper.getStatus()) {
			case HttpServletResponse.SC_NO_CONTENT:
			case HttpServletResponse.SC_RESET_CONTENT:
			case HttpServletResponse.SC_NOT_MODIFIED:
				return;
			default:
		}

		// Saneness checks
		byte[] compressedBytes = compressed.toByteArray();
		boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest);
		boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus());
		if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
               // No reason to add GZIP headers or write body if no content was written or status code specifies no
			// content
			response.setContentLength(0);
			return;
		}

		// Write the zipped body
		GZipResponseUtil.addGzipHeader(httpResponse);

		// Only write out header Vary as needed
		GZipResponseUtil.addVaryAcceptEncoding(wrapper);

		response.setContentLength(compressedBytes.length);

		response.getOutputStream().write(compressedBytes);
	} else {
		// Client does not accept zipped content - don't bother zipping
		if (log.isTraceEnabled()) {
			log.trace("{} Written without gzip compression because the request does not accept gzip",
					httpRequest.getRequestURL());
		}
		chain.doFilter(request, response);
	}
}