Java Code Examples for org.springframework.web.util.ContentCachingResponseWrapper#copyBodyToResponse()

The following examples show how to use org.springframework.web.util.ContentCachingResponseWrapper#copyBodyToResponse() . 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: ShallowEtagHeaderFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
	ContentCachingResponseWrapper responseWrapper =
			WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
	Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
	HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
	int statusCode = responseWrapper.getStatusCode();

	if (rawResponse.isCommitted()) {
		responseWrapper.copyBodyToResponse();
	}
	else if (isEligibleForEtag(request, responseWrapper, statusCode, responseWrapper.getContentInputStream())) {
		String responseETag = generateETagHeaderValue(responseWrapper.getContentInputStream(), this.writeWeakETag);
		rawResponse.setHeader(HttpHeaders.ETAG, responseETag);
		String requestETag = request.getHeader(HttpHeaders.IF_NONE_MATCH);
		if (requestETag != null && ("*".equals(requestETag) || compareETagHeaderValue(requestETag, responseETag))) {
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		responseWrapper.copyBodyToResponse();
	}
}
 
Example 2
Source File: ActuatorSecurityFilter.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
private void doFilterForHealth(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    ContentCachingResponseWrapper wrapper = new ContentCachingResponseWrapper(response);

    chain.doFilter(request, wrapper);
    String ip = request.getRemoteAddr();
    if (permittedAddrs.contains(ip)) {
        wrapper.copyBodyToResponse();
        return;
    }

    byte[] bytes = wrapper.getContentAsByteArray();
    int status = wrapper.getStatus();
    Map<String, Collection<String>> headers = wrapper.getHeaderNames()
            .stream().collect(Collectors.toMap(Function.identity(), wrapper::getHeaders));
    logger.info("overwrite response content, original={}", new String(bytes, "utf-8"));
    String result = wrapper.getStatus() == 200 ? "{\"status\":\"UP\"}" : "{\"status\":\"DOWN\"}";
    wrapper.reset();
    wrapper.setStatus(status);
    headers.forEach( (key, val) ->  val.forEach(v -> wrapper.addHeader(key, v)));
    try (OutputStream out = wrapper.getOutputStream()) {
        out.write(result.getBytes("UTF-8"));
    }

    wrapper.copyBodyToResponse();
}
 
Example 3
Source File: ShallowEtagHeaderFilter.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
	ContentCachingResponseWrapper responseWrapper =
			WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
	Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
	HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
	int statusCode = responseWrapper.getStatusCode();

	if (rawResponse.isCommitted()) {
		responseWrapper.copyBodyToResponse();
	}
	else if (isEligibleForEtag(request, responseWrapper, statusCode, responseWrapper.getContentInputStream())) {
		String responseETag = generateETagHeaderValue(responseWrapper.getContentInputStream(), this.writeWeakETag);
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (requestETag != null && ("*".equals(requestETag) || compareETagHeaderValue(requestETag, responseETag))) {
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		responseWrapper.copyBodyToResponse();
	}
}
 
Example 4
Source File: HttpMetricsTagConfiguration.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Bean
OncePerRequestFilter extractCountry() {
    return new OncePerRequestFilter() {
        private final ObjectMapper mapper = new ObjectMapper();

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain) throws ServletException, IOException {
            ContentCachingResponseWrapper cached = new ContentCachingResponseWrapper(response);
            filterChain.doFilter(request, cached);

            Object path = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
            if (path.equals("/api/person/{id}")) {
                // Prometheus requires the same tags on all `http.server.requests`. So we'll need to add
                // a `@Timed("person.requests") to the /api/person/{id} endpoint so it has a different name.
                Person person = mapper.readValue(cached.getContentAsByteArray(), Person.class);
                responseTags.put(response, Tags.of("country", person.getCountry()));
            }

            cached.copyBodyToResponse();
        }
    };
}
 
Example 5
Source File: ShallowEtagHeaderFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
	ContentCachingResponseWrapper responseWrapper =
			WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
	Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
	HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
	int statusCode = responseWrapper.getStatusCode();

	if (rawResponse.isCommitted()) {
		responseWrapper.copyBodyToResponse();
	}
	else if (isEligibleForEtag(request, responseWrapper, statusCode, responseWrapper.getContentInputStream())) {
		String responseETag = generateETagHeaderValue(responseWrapper.getContentInputStream(), this.writeWeakETag);
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (requestETag != null
				&& (responseETag.equals(requestETag)
				|| responseETag.replaceFirst("^W/", "").equals(requestETag.replaceFirst("^W/", ""))
				|| "*".equals(requestETag))) {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
			}
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag +
						"], sending normal response");
			}
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		if (logger.isTraceEnabled()) {
			logger.trace("Response with status code [" + statusCode + "] not eligible for ETag");
		}
		responseWrapper.copyBodyToResponse();
	}
}
 
Example 6
Source File: ShallowEtagHeaderFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
	ContentCachingResponseWrapper responseWrapper =
			WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
	Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
	HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
	int statusCode = responseWrapper.getStatusCode();

	if (rawResponse.isCommitted()) {
		responseWrapper.copyBodyToResponse();
	}
	else if (isEligibleForEtag(request, responseWrapper, statusCode, responseWrapper.getContentInputStream())) {
		String responseETag = generateETagHeaderValue(responseWrapper.getContentInputStream());
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (responseETag.equals(requestETag)) {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
			}
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag +
						"], sending normal response");
			}
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		if (logger.isTraceEnabled()) {
			logger.trace("Response with status code [" + statusCode + "] not eligible for ETag");
		}
		responseWrapper.copyBodyToResponse();
	}
}