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