001: package org.claros.intouch.webmail.services;
002:
003: import java.io.File;
004: import java.io.IOException;
005: import java.util.ArrayList;
006: import java.util.Iterator;
007: import java.util.List;
008:
009: import javax.servlet.ServletException;
010: import javax.servlet.http.HttpServletRequest;
011: import javax.servlet.http.HttpServletResponse;
012:
013: import org.apache.commons.fileupload.FileItem;
014: import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
015: import org.apache.commons.fileupload.disk.DiskFileItemFactory;
016: import org.apache.commons.fileupload.servlet.ServletFileUpload;
017: import org.claros.commons.mail.exception.MailSizeExceededException;
018: import org.claros.commons.mail.models.EmailPart;
019: import org.claros.commons.mail.utility.Utility;
020: import org.claros.commons.utility.MD5;
021: import org.claros.intouch.common.services.BaseService;
022: import org.claros.intouch.common.utility.Constants;
023:
024: public class UploadAttachmentService extends BaseService {
025: private static final long serialVersionUID = 1406344913366076583L;
026: private static int MAX_MEM_SIZE = 1024 * 1024;
027: private static int MAX_ATT_SIZE = 1024 * 1024 * Constants.maxAttSize;
028: private static int MAX_MAIL_SIZE = 1024 * 1024 * Constants.maxMailSize;
029:
030: private static String tmpDir = Constants.tmpDir;
031:
032: public void doGet(HttpServletRequest request,
033: HttpServletResponse response) throws ServletException,
034: IOException {
035: doPost(request, response);
036: }
037:
038: /**
039: * The doPost method of the servlet. <br>
040: *
041: * This method is called when a form has its tag value method equals to post.
042: *
043: * @param request the request send by the client to the server
044: * @param response the response send by the server to the client
045: * @throws ServletException if an error occurred
046: * @throws IOException if an error occurred
047: */
048: public void doPost(HttpServletRequest request,
049: HttpServletResponse response) throws ServletException,
050: IOException {
051: response.setHeader("Expires", "-1");
052: response.setHeader("Pragma", "no-cache");
053: response.setHeader("Cache-control", "no-cache");
054: response.setHeader("Content-Type", "text/html; charset=utf-8");
055:
056: request.setCharacterEncoding("UTF-8");
057:
058: ArrayList parts = (ArrayList) request.getSession()
059: .getAttribute("attachments");
060: if (parts == null) {
061: parts = new ArrayList();
062: }
063:
064: String id = null;
065:
066: String fileName = null;
067: String strSize = null;
068: long totalSize = 0;
069: try {
070: // Create a factory for disk-based file items
071: DiskFileItemFactory factory = new DiskFileItemFactory();
072:
073: // Set factory constraints
074: factory.setSizeThreshold(MAX_MEM_SIZE);
075: factory.setRepository(new File(tmpDir));
076:
077: // Create a new file upload handler
078: ServletFileUpload upload = new ServletFileUpload(factory);
079:
080: // Set overall request size constraint
081: upload.setSizeMax(MAX_ATT_SIZE);
082:
083: // Parse the request
084: List items = upload.parseRequest(request);
085: // Process the uploaded items
086: Iterator iter = items.iterator();
087:
088: EmailPart part = null;
089: // we need the id any way so we parse it first
090: while (iter.hasNext()) {
091: FileItem item = (FileItem) iter.next();
092:
093: if (item.isFormField()) {
094: String name = item.getFieldName();
095: if (name != null && name.equals("iframeid")) {
096: id = item.getString();
097: }
098: }
099: }
100:
101: // we can parse the attachments now
102: iter = items.iterator();
103: while (iter.hasNext()) {
104: FileItem item = (FileItem) iter.next();
105:
106: if (!item.isFormField()) {
107: //String fieldName = item.getFieldName();
108: fileName = item.getName();
109: String contentType = item.getContentType();
110: // boolean isInMemory = item.isInMemory();
111: long size = item.getSize();
112:
113: String tmpName = MD5.getHashString(request
114: .getSession().getId()
115: + fileName);
116:
117: File uploadedFile = new File(tmpDir + "/" + tmpName);
118: item.write(uploadedFile);
119: uploadedFile = null;
120:
121: if (fileName.indexOf("\\") > 0) {
122: fileName = fileName.substring(fileName
123: .lastIndexOf("\\") + 1);
124: }
125:
126: part = new EmailPart();
127: /*
128: byte data[] = item.get();
129:
130:
131: MimeBodyPart bodyPart = new MimeBodyPart();
132: DataSource ds = new ByteArrayDataSource(data, contentType, fileName);
133: bodyPart.setDataHandler(new DataHandler(ds));
134: bodyPart.setDisposition("attachment; filename=\"" + fileName + "\"");
135: bodyPart.setFileName(fileName);
136:
137: part.setDataSource(ds);
138:
139: part.setContent(bodyPart.getContent());
140: */
141: part.setContentType(contentType);
142: part.setDisposition(tmpDir + "/" + tmpName);
143:
144: // part.setDisposition(bodyPart.getDisposition());
145: part.setFilename(fileName);
146: part.setSize(size);
147: part.setSizeReadable(Utility
148: .sizeToHumanReadable(size));
149:
150: strSize = part.getSizeReadable();
151:
152: parts.add(part);
153: item.delete();
154: request.getSession().setAttribute("attachments",
155: parts);
156:
157: }
158: }
159: totalSize = calculateSize(parts);
160:
161: // check if the total mail size exceeds the limit
162: if (totalSize > MAX_MAIL_SIZE) {
163: parts.remove(parts.size() - 1);
164: throw new MailSizeExceededException();
165: }
166:
167: response.sendRedirect("../upload_ok.jsp?result=0&size="
168: + strSize
169: + "&fileName="
170: + java.net.URLEncoder.encode(java.net.URLEncoder
171: .encode(fileName, "UTF-8"), "UTF-8")
172: + "&id=" + id + "&totalSize="
173: + Utility.sizeToHumanReadable(totalSize));
174: } catch (SizeLimitExceededException e) {
175: // attachment exceeded the attachment upload size limit
176: response.sendRedirect("../upload_ok.jsp?result=1&fileName="
177: + java.net.URLEncoder.encode(fileName, "UTF-8")
178: + "&size=" + strSize + "&maxAttSize="
179: + Utility.sizeToHumanReadable(MAX_ATT_SIZE));
180: } catch (MailSizeExceededException e) {
181: // mail exceeded the total mail size limit
182: totalSize = calculateSize(parts);
183: response.sendRedirect("../upload_ok.jsp?result=2&fileName="
184: + java.net.URLEncoder.encode(fileName, "UTF-8")
185: + "&totalSize="
186: + Utility.sizeToHumanReadable(totalSize)
187: + "&maxMailSize="
188: + Utility.sizeToHumanReadable(MAX_MAIL_SIZE));
189: } catch (Exception e) {
190: response.sendRedirect("../upload_ok.jsp?result=3");
191: }
192: }
193:
194: private long calculateSize(ArrayList parts) {
195: EmailPart tmp = null;
196: long allSize = 0;
197: for (int i = 0; i < parts.size(); i++) {
198: tmp = (EmailPart) parts.get(i);
199: allSize = allSize + tmp.getSize();
200: }
201: return allSize;
202: }
203:
204: }
|