From 4d0800f3924fa8a7fc4a9b411974760b9e4e1305 Mon Sep 17 00:00:00 2001 From: zilong6 Date: Mon, 9 Jul 2018 19:15:21 +0200 Subject: [PATCH] Improve ContentCachingRequestWrapper performance This commit improves the performance of `read` method variants to write to the cache in an optimized way. Issue: SPR-15762 --- .../util/ContentCachingRequestWrapper.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java b/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java index 8fcacc4fac..fc8ec32f32 100644 --- a/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java +++ b/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java @@ -213,6 +213,57 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper { this.is = is; } + @Override + public int readLine(final byte[] b, final int off, final int len) throws IOException { + int count = is.readLine(b, off, len); + cache(b, off, count); + return count; + } + + private void cache(final byte[] b, final int off, final int count) { + if (contentCacheLimit != null && cachedContent.size() == contentCacheLimit) { + this.overflow = true; + handleContentOverflow(contentCacheLimit); + } else { + int sizeToCache = contentCacheLimit == null || count + cachedContent.size() < contentCacheLimit + ? count + : contentCacheLimit - cachedContent.size(); + cachedContent.write(b, off, sizeToCache); + if (sizeToCache < count) { + this.overflow = true; + handleContentOverflow(contentCacheLimit); + } + } + } + + @Override + public int read(final byte[] b) throws IOException { + int count = super.read(b); + if (!this.overflow && count > 0) { + if (contentCacheLimit != null && cachedContent.size() == contentCacheLimit) { + this.overflow = true; + handleContentOverflow(contentCacheLimit); + } else { + int sizeToCache = contentCacheLimit == null || count + cachedContent.size() < contentCacheLimit + ? count + : contentCacheLimit - cachedContent.size(); + cachedContent.write(b, 0, sizeToCache); + if (sizeToCache < count) { + this.overflow = true; + handleContentOverflow(contentCacheLimit); + } + } + } + return count; + } + + @Override + public int read(final byte[] b, final int off, final int len) throws IOException { + int count = is.read(b, off, len); + cache(b, off, count); + return count; + } + @Override public int read() throws IOException { int ch = this.is.read();