Java Code Examples for org.springframework.web.util.ContentCachingResponseWrapper

The following examples show how to use org.springframework.web.util.ContentCachingResponseWrapper. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: ShallowEtagHeaderFilter.java    License: 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
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 Project: java-technology-stack   Source File: ShallowEtagHeaderFilter.java    License: 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 Project: micrometer   Source File: HttpMetricsTagConfiguration.java    License: 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 Project: plumdo-work   Source File: RequestLogFilter.java    License: Apache License 2.0 6 votes vote down vote up
private void updateResponse(String requestUri, ContentCachingResponseWrapper responseWrapper) {
    try {
        HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
        byte[] body = responseWrapper.getContentAsByteArray();
        ServletOutputStream outputStream = rawResponse.getOutputStream();
        if (rawResponse.isCommitted()) {
            if (body.length > 0) {
                StreamUtils.copy(body, outputStream);
            }
        } else {
            if (body.length > 0) {
                rawResponse.setContentLength(body.length);
                StreamUtils.copy(body, rawResponse.getOutputStream());
            }
        }
        finishResponse(outputStream, body);
    } catch (Exception ex) {
        log.error("请求地址为" + requestUri + "的连接返回报文失败,原因是{}", ex.getMessage());
    }
}
 
Example 6
Source Project: spring-analysis-note   Source File: ShallowEtagHeaderFilter.java    License: MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	HttpServletResponse responseToUse = response;
	if (!isAsyncDispatch(request) && !(response instanceof ContentCachingResponseWrapper)) {
		responseToUse = new HttpStreamingAwareContentCachingResponseWrapper(response, request);
	}

	filterChain.doFilter(request, responseToUse);

	if (!isAsyncStarted(request) && !isContentCachingDisabled(request)) {
		updateResponse(request, responseToUse);
	}
}
 
Example 7
Source Project: java-technology-stack   Source File: ShallowEtagHeaderFilter.java    License: MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	HttpServletResponse responseToUse = response;
	if (!isAsyncDispatch(request) && !(response instanceof ContentCachingResponseWrapper)) {
		responseToUse = new HttpStreamingAwareContentCachingResponseWrapper(response, request);
	}

	filterChain.doFilter(request, responseToUse);

	if (!isAsyncStarted(request) && !isContentCachingDisabled(request)) {
		updateResponse(request, responseToUse);
	}
}
 
Example 8
Source Project: lams   Source File: ShallowEtagHeaderFilter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	HttpServletResponse responseToUse = response;
	if (!isAsyncDispatch(request) && !(response instanceof ContentCachingResponseWrapper)) {
		responseToUse = new HttpStreamingAwareContentCachingResponseWrapper(response, request);
	}

	filterChain.doFilter(request, responseToUse);

	if (!isAsyncStarted(request) && !isContentCachingDisabled(request)) {
		updateResponse(request, responseToUse);
	}
}
 
Example 9
Source Project: lams   Source File: ShallowEtagHeaderFilter.java    License: 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 10
Source Project: plumdo-work   Source File: RequestLogFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    long beginTime = DateUtils.currentTimeMillis();
    long timeCost;
    String requestUri = request.getRequestURI();
    String method = request.getMethod();
    String ip = request.getRemoteAddr();
    if (isNotJsonContentType(request.getContentType())) {
        filterChain.doFilter(request, response);
        timeCost = DateUtils.getTimeMillisConsume(beginTime);
        log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},[{}]ms", ip, requestUri, method, request.getQueryString(), timeCost);
    } else {
        JsonContentCachingRequestWrapper requestWrapper = new JsonContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        filterChain.doFilter(requestWrapper, responseWrapper);
        timeCost = DateUtils.getTimeMillisConsume(beginTime);
        String requestParam = convertString(requestWrapper.getContentAsByteArray());
        updateResponse(requestUri, responseWrapper);
        if (isNotJsonContentType(responseWrapper.getContentType())) {
            log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},[{}]ms", ip, requestUri, method, requestParam, timeCost);
        } else {
            String result = convertString(responseWrapper.getContentAsByteArray());
            log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},返回值是{},[{}]ms", ip, requestUri, method, requestParam, result, timeCost);
        }
    }

}
 
Example 11
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	HttpServletResponse responseToUse = response;
	if (!isAsyncDispatch(request) && !(response instanceof ContentCachingResponseWrapper)) {
		responseToUse = new HttpStreamingAwareContentCachingResponseWrapper(response, request);
	}

	filterChain.doFilter(request, responseToUse);

	if (!isAsyncStarted(request) && !isContentCachingDisabled(request)) {
		updateResponse(request, responseToUse);
	}
}
 
Example 12
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();
	}
}
 
Example 13
Source Project: fast-family-master   Source File: AccessLogger.java    License: Apache License 2.0 4 votes vote down vote up
public void appendResponseCommonMessage(ContentCachingResponseWrapper response, long cost){
    responseInfo.setSize(response.getContentSize());
    responseInfo.setStatus(response.getStatusCode());
    responseInfo.setCost(cost);
}