001
014
015 package com.liferay.portal.upload;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStreamWrapper;
019 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
020 import com.liferay.portal.kernel.log.Log;
021 import com.liferay.portal.kernel.log.LogFactoryUtil;
022 import com.liferay.portal.kernel.util.GetterUtil;
023 import com.liferay.portal.util.PropsUtil;
024 import com.liferay.util.servlet.ServletInputStreamWrapper;
025
026 import java.io.IOException;
027
028 import javax.servlet.ServletInputStream;
029 import javax.servlet.http.HttpServletRequest;
030 import javax.servlet.http.HttpSession;
031
032
037 public class LiferayInputStream extends ServletInputStreamWrapper {
038
039 public static final int THRESHOLD_SIZE = GetterUtil.getInteger(
040 PropsUtil.get(LiferayInputStream.class.getName() + ".threshold.size"));
041
042 public LiferayInputStream(HttpServletRequest request) throws IOException {
043 super(request.getInputStream());
044
045 _session = request.getSession();
046 _totalSize = request.getContentLength();
047 }
048
049 @Override
050 public int read(byte[] b, int off, int len) throws IOException {
051 int bytesRead = super.read(b, off, len);
052
053 if (bytesRead > 0) {
054 _totalRead += bytesRead;
055 }
056 else {
057 return bytesRead;
058 }
059
060 int percent = (int)((_totalRead * 100L) / _totalSize);
061
062 if (_log.isDebugEnabled()) {
063 _log.debug(bytesRead + "/" + _totalRead + "=" + percent);
064 }
065
066 if ((_totalSize > 0) && (_totalSize < THRESHOLD_SIZE)) {
067 _cachedBytes.write(b, off, bytesRead);
068 }
069
070 Integer curPercent = (Integer)_session.getAttribute(
071 LiferayFileUpload.PERCENT);
072
073 if ((curPercent == null) || (percent - curPercent.intValue() >= 1)) {
074 _session.setAttribute(
075 LiferayFileUpload.PERCENT, new Integer(percent));
076 }
077
078 return bytesRead;
079 }
080
081 public ServletInputStream getCachedInputStream() {
082 if (_totalSize < THRESHOLD_SIZE) {
083 return this;
084 }
085 else {
086 return new UnsyncByteArrayInputStreamWrapper(
087 new UnsyncByteArrayInputStream(
088 _cachedBytes.unsafeGetByteArray(), 0, _cachedBytes.size()));
089 }
090 }
091
092 private static Log _log = LogFactoryUtil.getLog(LiferayInputStream.class);
093
094 private HttpSession _session;
095 private int _totalRead;
096 private int _totalSize;
097 private UnsyncByteArrayOutputStream _cachedBytes =
098 new UnsyncByteArrayOutputStream();
099
100 }