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