001: /* -----------------------------------------------------------------------------
002: * Copyright (c) 2001, Low Kin Onn
003: * All rights reserved.
004: * Redistribution and use in source and binary forms, with or without
005: * modification, are permitted provided that the following conditions are met:
006: *
007: *
008: * Redistributions of source code must retain the above copyright notice, this
009: * list of conditions and the following disclaimer.
010: *
011: * Redistributions in binary form must reproduce the above copyright notice,
012: * this list of conditions and the following disclaimer in the documentation
013: * and/or other materials provided with the distribution.
014: *
015: * Neither name of the Scioworks Pte. Ltd. nor the names of its contributors
016: * may beused to endorse or promote products derived from this software without
017: * specific prior written permission.
018: *
019: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
020: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
021: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
022: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
023: * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
024: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
025: * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
026: * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
027: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
028: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029: *
030: * -----------------------------------------------------------------------------
031: */
032:
033: package scioworks.imap.presentation.imapWeb;
034:
035: import org.w3c.dom.*;
036: import org.w3c.dom.html.*;
037:
038: import com.lutris.appserver.server.httpPresentation.*;
039: import com.lutris.util.KeywordValueException;
040: import com.lutris.mime.*;
041: import java.io.*;
042:
043: import scioworks.imap.presentation.base.*;
044: import scioworks.imap.spec.ImapWebException;
045: import scioworks.imap.spec.ImapWebConstant;
046:
047: public class FileUpload extends BasePO {
048:
049: FileUploadSessionData fFileUploadSessionData = null;
050:
051: private String processUpload() throws HttpPresentationException,
052: ImapWebException {
053:
054: if (fFileUploadSessionData.isExceedFileCount()) {
055: return "Maximum file count reached.";
056: }
057:
058: try {
059: String contentType = super .getComms().request
060: .getContentType();
061:
062: if (contentType == null) {
063: contentType = "";
064: }
065:
066: ContentHeader contentHdr = new ContentHeader(
067: "Content-Type: " + contentType);
068:
069: if (!contentHdr.getValue().toLowerCase().startsWith(
070: "multipart/")) {
071: // not a multipart - do nothing and return
072: return " ";
073: }
074:
075: HttpPresentationInputStream input = super .getComms().request
076: .getInputStream();
077:
078: MultipartMimeInput mime = new MultipartMimeInput(input,
079: contentHdr);
080:
081: MultipartMimeInputStream in;
082:
083: while ((in = mime.nextPart()) != null) {
084:
085: String type;
086:
087: MimeHeader hdr = in.getHeader("Content-Type");
088:
089: if (hdr != null) {
090: ContentHeader chdr = new ContentHeader(hdr);
091: type = chdr.getValue();
092: } else {
093: type = "null";
094: }
095:
096: String contentDisp = null;
097: String contentName = null;
098: String fileName = null;
099:
100: if ((hdr = in.getHeader("Content-Disposition")) != null) {
101: ContentHeader chdr = new ContentHeader(hdr);
102: contentDisp = chdr.getValue();
103: contentName = chdr.getParameter("name");
104: fileName = chdr.getParameter("filename").trim();
105: }
106:
107: if (contentDisp == null) {
108: contentDisp = "null";
109: }
110:
111: if (contentName == null) {
112: contentName = "null";
113: }
114:
115: if (fileName == null) {
116: fileName = "null";
117: }
118:
119: int n, count = 0;
120: byte[] buffer = new byte[4096];
121:
122: if (fileName.equals("null")) {
123: return "File not found.";
124:
125: } else {
126:
127: String actualFilename = fileName
128: .substring(fileName.lastIndexOf(System
129: .getProperty("file.separator")) + 1);
130:
131: // create write to tmp file
132: String tmpFilename = ImapWebConstant.singleton()
133: .fileTmpDir()
134: + System.currentTimeMillis()
135: + actualFilename;
136:
137: FileOutputStream out = new FileOutputStream(
138: tmpFilename);
139:
140: while ((n = in.read(buffer, 0, buffer.length)) > 0) {
141: out.write(buffer, 0, n);
142: count += n;
143: }
144:
145: in.close(); // Close this part (but not whole upload).
146: out.close(); // Close output file.
147:
148: if (count == 0) {
149: // not a valid upload
150: return "Invalid file. Make sure the file exists.";
151: }
152:
153: if (!fFileUploadSessionData.addFile(tmpFilename,
154: actualFilename, count, type)) {
155: return "You've exceeded the attachment limit.";
156: }
157:
158: }
159:
160: } // while
161:
162: /** @todo : target url */
163: return "File attached.";
164:
165: } catch (MimeException e) {
166: throw new ImapWebException("Error uploading file.", e);
167:
168: } catch (FileNotFoundException e) {
169: throw new ImapWebException("Error uploading file.", e);
170:
171: } catch (IOException e) {
172: throw new ImapWebException("Error uploading file.", e);
173: }
174:
175: }
176:
177: private String removeFile(
178: FileUploadSessionData fileUploadSessionData)
179: throws HttpPresentationException {
180:
181: // get input parameter
182: int fFileId = super .getIntParameter(PARAM_fileid);
183:
184: String tmpFilename = fileUploadSessionData
185: .getTmpFilename(fFileId);
186:
187: if (fileUploadSessionData.removeFile(fFileId)) {
188:
189: File file = new File(tmpFilename);
190: if (!file.delete()) {
191: System.out.println("Tmp file not deleted: "
192: + tmpFilename);
193: }
194:
195: return "Attachment removed";
196:
197: } else {
198: return "Error removing attachment";
199: }
200: }
201:
202: public String handleDefault() throws HttpPresentationException {
203:
204: // get event parameter
205: String fEvent = super .getStringParameter(PARAM_event);
206:
207: String msg;
208:
209: try {
210: // try get the session data
211: Object obj = getComms().sessionData
212: .get(FileUploadSessionData.SESSION_KEY);
213:
214: if (obj == null) {
215: // no session data - first time
216: fFileUploadSessionData = new FileUploadSessionData(
217: ImapWebConstant.singleton().fileCount(),
218: ImapWebConstant.singleton().fileTotalSize());
219: // set the session data
220: getComms().sessionData.set(
221: FileUploadSessionData.SESSION_KEY,
222: fFileUploadSessionData);
223:
224: } else {
225: // get the existing session data
226: fFileUploadSessionData = (FileUploadSessionData) obj;
227: }
228:
229: if (fEvent.equals(EVENT_removeFile)) {
230: msg = removeFile(fFileUploadSessionData);
231:
232: } else {
233: // this is the default event , as we are processing a multi-part form
234: msg = processUpload();
235: }
236:
237: attachmentHTML page = (attachmentHTML) m_comms.xmlcFactory
238: .create(attachmentHTML.class);
239:
240: // Get reference to the row to be modified
241: HTMLTableRowElement fileListRow = page
242: .getElementFileListRow();
243: Node fileListTable = fileListRow.getParentNode();
244:
245: // set the message, if any
246: if ((msg.length() == 0) || (msg == null)) {
247: page.setTextMessage(" ");
248: } else {
249: page.setTextMessage(msg);
250: }
251:
252: // set the max count and max file size allowed
253: page.setTextFileMaxCount(Integer.toString(ImapWebConstant
254: .singleton().fileCount()));
255:
256: page
257: .setTextFileTotalSize(TextUtil.singleton()
258: .verboseFilesize(
259: ImapWebConstant.singleton()
260: .fileTotalSize()));
261:
262: // get reference to the Remove file link
263: HTMLAnchorElement fileRemoveLink = page
264: .getElementFileRemoveLink();
265: String currLink = fileRemoveLink.getHref() + "?"
266: + PARAM_event + "=" + EVENT_removeFile + "&"
267: + PARAM_fileid + "=";
268:
269: StringBuffer attachmentList = new StringBuffer();
270: String verboseSize;
271: for (int i = 0; i < fFileUploadSessionData.getFileCount(); i++) {
272: // set the name of the file
273: page.setTextFilename(fFileUploadSessionData
274: .getFilename(i));
275:
276: // set the size of the file
277: verboseSize = TextUtil.singleton().verboseFilesize(
278: fFileUploadSessionData.getFilesize(i));
279: page.setTextFilesize(verboseSize);
280:
281: // set the remove link
282: fileRemoveLink.setHref(currLink + i);
283:
284: // add to the attachment list
285: attachmentList.append(
286: fFileUploadSessionData.getFilename(i)).append(
287: " ");
288: attachmentList.append("(").append(verboseSize).append(
289: ");");
290:
291: fileListTable.appendChild(fileListRow.cloneNode(true));
292: }
293: fileListTable.removeChild(fileListRow);
294:
295: // prepare to set the attachment list
296: if (attachmentList.length() == 0) {
297: attachmentList.append("(None)");
298: }
299:
300: HTMLBodyElement bodyEle = page.getElementPageBody();
301: HTMLScriptElement attachScript = (HTMLScriptElement) page
302: .createElement("SCRIPT");
303: attachScript.appendChild(page
304: .createTextNode("window.opener.SetAttachment('"
305: + attachmentList.toString() + "');"));
306: bodyEle.appendChild(attachScript);
307:
308: return page.toDocument();
309:
310: } catch (KeywordValueException e) {
311: return super .showErrorPage(MSG_OPERATION_FAILED,
312: "Problem getting session data from session. "
313: + e.getMessage(), "", "");
314:
315: } catch (ImapWebException e) {
316: e.printStackTrace();
317: return super .showErrorPage(MSG_OPERATION_FAILED, e
318: .getMessage(), "", "");
319:
320: }
321: }
322:
323: }
|