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