1
19
20 package com.liferay.portal.upload;
21
22 import com.liferay.portal.kernel.log.Log;
23 import com.liferay.portal.kernel.log.LogFactoryUtil;
24 import com.liferay.portal.kernel.util.ByteArrayMaker;
25 import com.liferay.portal.kernel.util.GetterUtil;
26 import com.liferay.portal.util.PropsUtil;
27 import com.liferay.util.servlet.ByteArrayInputStreamWrapper;
28 import com.liferay.util.servlet.ServletInputStreamWrapper;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32
33 import javax.servlet.ServletInputStream;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpSession;
36
37
45 public class LiferayInputStream extends ServletInputStreamWrapper {
46
47 public static final int THRESHOLD_SIZE = GetterUtil.getInteger(
48 PropsUtil.get(LiferayInputStream.class.getName() + ".threshold.size"));
49
50 public LiferayInputStream(HttpServletRequest request) throws IOException {
51 super(request.getInputStream());
52
53 _session = request.getSession();
54 _totalSize = request.getContentLength();
55 }
56
57 public int read(byte[] b, int off, int len) throws IOException {
58 int bytesRead = super.read(b, off, len);
59
60 if (bytesRead > 0) {
61 _totalRead += bytesRead;
62 }
63 else {
64 return bytesRead;
65 }
66
67 int percent = (_totalRead * 100) / _totalSize;
68
69 if (_log.isDebugEnabled()) {
70 _log.debug(bytesRead + "/" + _totalRead + "=" + percent);
71 }
72
73 if (_totalSize < THRESHOLD_SIZE) {
74 _cachedBytes.write(b, off, bytesRead);
75 }
76
77 Integer curPercent = (Integer)_session.getAttribute(
78 LiferayFileUpload.PERCENT);
79
80 if ((curPercent == null) || (percent - curPercent.intValue() >= 1)) {
81 _session.setAttribute(
82 LiferayFileUpload.PERCENT, new Integer(percent));
83 }
84
85 return bytesRead;
86 }
87
88 public ServletInputStream getCachedInputStream() {
89 if (_totalSize < THRESHOLD_SIZE) {
90 return this;
91 }
92 else {
93 return new ByteArrayInputStreamWrapper(
94 new ByteArrayInputStream(_cachedBytes.toByteArray()));
95 }
96 }
97
98 private static Log _log = LogFactoryUtil.getLog(LiferayInputStream.class);
99
100 private HttpSession _session;
101 private int _totalRead;
102 private int _totalSize;
103 private ByteArrayMaker _cachedBytes = new ByteArrayMaker();
104
105 }