KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > scioworks > imap > presentation > imapWeb > FileUpload


1 /* -----------------------------------------------------------------------------
2  * Copyright (c) 2001, Low Kin Onn
3  * All rights reserved.
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  *
8  * Redistributions of source code must retain the above copyright notice, this
9  * list of conditions and the following disclaimer.
10  *
11  * Redistributions in binary form must reproduce the above copyright notice,
12  * this list of conditions and the following disclaimer in the documentation
13  * and/or other materials provided with the distribution.
14  *
15  * Neither name of the Scioworks Pte. Ltd. nor the names of its contributors
16  * may beused to endorse or promote products derived from this software without
17  * specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * -----------------------------------------------------------------------------
31  */

32
33 package scioworks.imap.presentation.imapWeb;
34
35 import org.w3c.dom.*;
36 import org.w3c.dom.html.*;
37
38 import com.lutris.appserver.server.httpPresentation.*;
39 import com.lutris.util.KeywordValueException;
40 import com.lutris.mime.*;
41 import java.io.*;
42
43 import scioworks.imap.presentation.base.*;
44 import scioworks.imap.spec.ImapWebException;
45 import scioworks.imap.spec.ImapWebConstant;
46
47 public class FileUpload extends BasePO {
48
49   FileUploadSessionData fFileUploadSessionData = null;
50
51   private String JavaDoc processUpload()
52       throws HttpPresentationException, ImapWebException {
53
54     if (fFileUploadSessionData.isExceedFileCount()) {
55       return "Maximum file count reached.";
56     }
57
58     try {
59       String JavaDoc contentType = super.getComms().request.getContentType();
60
61       if (contentType == null) {
62         contentType = "";
63       }
64
65       ContentHeader contentHdr = new ContentHeader("Content-Type: " + contentType);
66
67       if (!contentHdr.getValue().toLowerCase().startsWith("multipart/")) {
68         // not a multipart - do nothing and return
69
return " ";
70       }
71
72       HttpPresentationInputStream input = super.getComms().request.getInputStream();
73
74       MultipartMimeInput mime = new MultipartMimeInput(input, contentHdr);
75
76       MultipartMimeInputStream in;
77
78       while ((in = mime.nextPart()) != null) {
79
80         String JavaDoc type;
81
82         MimeHeader hdr = in.getHeader("Content-Type");
83
84         if (hdr != null) {
85           ContentHeader chdr = new ContentHeader(hdr);
86           type = chdr.getValue();
87         } else {
88           type = "null";
89         }
90
91         String JavaDoc contentDisp = null;
92         String JavaDoc contentName = null;
93         String JavaDoc fileName = null;
94
95         if ((hdr = in.getHeader("Content-Disposition")) != null) {
96           ContentHeader chdr = new ContentHeader(hdr);
97           contentDisp = chdr.getValue();
98           contentName = chdr.getParameter("name");
99           fileName = chdr.getParameter("filename").trim();
100         }
101
102         if (contentDisp == null) {
103           contentDisp = "null";
104         }
105
106         if (contentName == null) {
107           contentName = "null";
108         }
109
110         if (fileName == null) {
111           fileName = "null";
112         }
113
114         int n, count=0;
115         byte[] buffer = new byte[4096];
116
117         if (fileName.equals("null")) {
118           return "File not found.";
119
120         } else {
121
122         String JavaDoc actualFilename = fileName.substring(fileName.lastIndexOf(System.getProperty("file.separator"))+1);
123
124         // create write to tmp file
125
String JavaDoc tmpFilename = ImapWebConstant.singleton().fileTmpDir() +
126                              System.currentTimeMillis() + actualFilename;
127
128         FileOutputStream out = new FileOutputStream(tmpFilename);
129
130         while ((n = in.read(buffer, 0, buffer.length)) > 0) {
131           out.write(buffer, 0, n);
132           count += n;
133         }
134
135         in.close(); // Close this part (but not whole upload).
136
out.close(); // Close output file.
137

138         if (count == 0) {
139           // not a valid upload
140
return "Invalid file. Make sure the file exists.";
141         }
142
143         if (!fFileUploadSessionData.addFile(tmpFilename, actualFilename, count, type)) {
144           return "You've exceeded the attachment limit.";
145         }
146
147         }
148
149       } // while
150

151       /** @todo : target url */
152       return "File attached.";
153
154     } catch (MimeException e) {
155       throw new ImapWebException("Error uploading file.", e);
156
157     } catch (FileNotFoundException e) {
158       throw new ImapWebException("Error uploading file.", e);
159
160     } catch (IOException e) {
161       throw new ImapWebException("Error uploading file.", e);
162     }
163
164   }
165
166   private String JavaDoc removeFile(FileUploadSessionData fileUploadSessionData)
167       throws HttpPresentationException {
168
169     // get input parameter
170
int fFileId = super.getIntParameter(PARAM_fileid);
171
172     String JavaDoc tmpFilename = fileUploadSessionData.getTmpFilename(fFileId);
173
174     if (fileUploadSessionData.removeFile(fFileId)) {
175
176       File file = new File(tmpFilename);
177       if (!file.delete()) {
178         System.out.println("Tmp file not deleted: " + tmpFilename);
179       }
180
181       return "Attachment removed";
182
183     } else {
184       return "Error removing attachment";
185     }
186   }
187
188   public String JavaDoc handleDefault()
189       throws HttpPresentationException {
190
191     // get event parameter
192
String JavaDoc fEvent = super.getStringParameter(PARAM_event);
193
194     String JavaDoc msg;
195
196     try {
197       // try get the session data
198
Object JavaDoc obj = getComms().sessionData.get(FileUploadSessionData.SESSION_KEY);
199
200       if (obj == null) {
201         // no session data - first time
202
fFileUploadSessionData =
203             new FileUploadSessionData(ImapWebConstant.singleton().fileCount(),
204                                       ImapWebConstant.singleton().fileTotalSize());
205         // set the session data
206
getComms().sessionData.set(FileUploadSessionData.SESSION_KEY, fFileUploadSessionData);
207
208       } else {
209         // get the existing session data
210
fFileUploadSessionData = (FileUploadSessionData) obj;
211       }
212
213       if (fEvent.equals(EVENT_removeFile)) {
214         msg = removeFile(fFileUploadSessionData);
215
216       } else {
217         // this is the default event , as we are processing a multi-part form
218
msg = processUpload();
219       }
220
221
222       attachmentHTML page = (attachmentHTML)m_comms.xmlcFactory.create(attachmentHTML.class);
223
224       // Get reference to the row to be modified
225
HTMLTableRowElement fileListRow = page.getElementFileListRow();
226       Node fileListTable = fileListRow.getParentNode();
227
228       // set the message, if any
229
if ((msg.length() == 0) || (msg == null)) {
230         page.setTextMessage(" ");
231       } else {
232         page.setTextMessage(msg);
233       }
234
235       // set the max count and max file size allowed
236
page.setTextFileMaxCount(Integer.toString(ImapWebConstant.singleton().fileCount()));
237      
238      
239      
240       page.setTextFileTotalSize(TextUtil.singleton().verboseFilesize(ImapWebConstant.singleton().fileTotalSize()));
241
242       // get reference to the Remove file link
243
HTMLAnchorElement fileRemoveLink = page.getElementFileRemoveLink();
244       String JavaDoc currLink = fileRemoveLink.getHref() + "?" +
245                         PARAM_event + "=" + EVENT_removeFile + "&" +
246                         PARAM_fileid + "=" ;
247
248       StringBuffer JavaDoc attachmentList = new StringBuffer JavaDoc();
249       String JavaDoc verboseSize;
250       for (int i=0; i<fFileUploadSessionData.getFileCount(); i++) {
251         // set the name of the file
252
page.setTextFilename(fFileUploadSessionData.getFilename(i));
253
254         // set the size of the file
255
verboseSize = TextUtil.singleton().verboseFilesize(fFileUploadSessionData.getFilesize(i));
256         page.setTextFilesize(verboseSize);
257
258         // set the remove link
259
fileRemoveLink.setHref(currLink + i);
260
261         // add to the attachment list
262
attachmentList.append(fFileUploadSessionData.getFilename(i)).append(" ");
263         attachmentList.append("(").append(verboseSize).append(");");
264
265         fileListTable.appendChild(fileListRow.cloneNode(true));
266       }
267       fileListTable.removeChild(fileListRow);
268
269
270       // prepare to set the attachment list
271
if (attachmentList.length() == 0) {
272         attachmentList.append("(None)");
273       }
274
275       HTMLBodyElement bodyEle = page.getElementPageBody();
276       HTMLScriptElement attachScript = (HTMLScriptElement) page.createElement("SCRIPT");
277       attachScript.appendChild(page.createTextNode("window.opener.SetAttachment('" +
278                                                    attachmentList.toString() +
279                                                    "');"));
280       bodyEle.appendChild(attachScript);
281
282       return page.toDocument();
283
284     } catch (KeywordValueException e) {
285       return super.showErrorPage(MSG_OPERATION_FAILED,
286                                  "Problem getting session data from session. " + e.getMessage(),
287                                  "", "");
288
289     } catch (ImapWebException e) {
290       e.printStackTrace();
291       return super.showErrorPage(MSG_OPERATION_FAILED, e.getMessage(), "", "");
292
293     }
294   }
295
296 }
Popular Tags