1
2
3
4
5
6
7 package org.mule.transport.servlet;
8
9 import org.mule.util.IOUtils;
10
11 import java.io.ByteArrayInputStream;
12 import java.io.IOException;
13
14 import javax.servlet.ServletInputStream;
15 import javax.servlet.http.HttpServletRequest;
16 import javax.servlet.http.HttpServletRequestWrapper;
17
18 public class CachedHttpServletRequest extends HttpServletRequestWrapper
19 {
20
21 private CachedServletInputStream cachedServletInputStream;
22
23 public CachedHttpServletRequest(HttpServletRequest request)
24 {
25 super(request);
26 try
27 {
28 this.cachedServletInputStream = new CachedServletInputStream(request.getInputStream());
29 }
30 catch (IOException e)
31 {
32 throw new RuntimeException(e);
33 }
34 }
35
36 @Override
37 public ServletInputStream getInputStream() throws IOException
38 {
39 if (this.cachedServletInputStream != null)
40 {
41 return this.cachedServletInputStream;
42 }
43 else
44 {
45 return super.getInputStream();
46 }
47 }
48
49 private static class CachedServletInputStream extends ServletInputStream
50 {
51 private ByteArrayInputStream cachedStream;
52
53 public CachedServletInputStream(ServletInputStream servletInputStream)
54 {
55 byte[] bytes = IOUtils.toByteArray(servletInputStream);
56 this.cachedStream = new ByteArrayInputStream(bytes);
57 }
58
59 @Override
60 public int available() throws IOException
61 {
62 return this.cachedStream.available();
63 }
64
65 @Override
66 public void close() throws IOException
67 {
68 this.cachedStream.close();
69 }
70
71 @Override
72 public synchronized void mark(int readlimit)
73 {
74 this.cachedStream.mark(readlimit);
75 }
76
77 @Override
78 public boolean markSupported()
79 {
80 return true;
81 }
82
83 @Override
84 public int read() throws IOException
85 {
86 return this.cachedStream.read();
87 }
88
89 @Override
90 public int read(byte[] b, int off, int len) throws IOException
91 {
92 return this.cachedStream.read(b, off, len);
93 }
94
95 @Override
96 public int read(byte[] b) throws IOException
97 {
98 return this.cachedStream.read(b);
99 }
100
101 @Override
102 public synchronized void reset() throws IOException
103 {
104 this.cachedStream.reset();
105 }
106
107 @Override
108 public long skip(long n) throws IOException
109 {
110 return this.cachedStream.skip(n);
111 }
112 }
113 }