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
47 public class LiferayInputStream extends ServletInputStreamWrapper {
48
49 public static final int THRESHOLD_SIZE = GetterUtil.getInteger(
50 PropsUtil.get(LiferayInputStream.class.getName() + ".threshold.size"));
51
52 public LiferayInputStream(HttpServletRequest request) throws IOException {
53 super(request.getInputStream());
54
55 _session = request.getSession();
56 _totalSize = request.getContentLength();
57 }
58
59 public int read(byte[] b, int off, int len) throws IOException {
60 int bytesRead = super.read(b, off, len);
61
62 if (bytesRead > 0) {
63 _totalRead += bytesRead;
64 }
65 else {
66 return bytesRead;
67 }
68
69 int percent = (_totalRead * 100) / _totalSize;
70
71 if (_log.isDebugEnabled()) {
72 _log.debug(bytesRead + "/" + _totalRead + "=" + percent);
73 }
74
75 if (_totalSize < THRESHOLD_SIZE) {
76 _cachedBytes.write(b, off, bytesRead);
77 }
78
79 Integer curPercent = (Integer)_session.getAttribute(
80 LiferayFileUpload.PERCENT);
81
82 if ((curPercent == null) || (percent - curPercent.intValue() >= 1)) {
83 _session.setAttribute(
84 LiferayFileUpload.PERCENT, new Integer(percent));
85 }
86
87 return bytesRead;
88 }
89
90 public ServletInputStream getCachedInputStream() {
91 if (_totalSize < THRESHOLD_SIZE) {
92 return this;
93 }
94 else {
95 return new ByteArrayInputStreamWrapper(
96 new ByteArrayInputStream(_cachedBytes.toByteArray()));
97 }
98 }
99
100 private static Log _log = LogFactoryUtil.getLog(LiferayInputStream.class);
101
102 private HttpSession _session;
103 private int _totalRead;
104 private int _totalSize;
105 private ByteArrayMaker _cachedBytes = new ByteArrayMaker();
106
107 }