KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > util > MultipartRequest


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/util/MultipartRequest.java,v 1.19 2005/02/19 21:26:32 hkollmann Exp $
3  * $Revision: 1.19 $
4  * $Date: 2005/02/19 21:26:32 $
5  *
6  * DbForms - a Rapid Application Development Framework
7  * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  */

23
24 package org.dbforms.util;
25
26 import org.apache.commons.fileupload.DiskFileUpload;
27 import org.apache.commons.fileupload.FileItem;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import java.io.File JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34
35 import java.util.Enumeration JavaDoc;
36 import java.util.Hashtable JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Vector JavaDoc;
40
41 import javax.servlet.http.HttpServletRequest JavaDoc;
42 import org.dbforms.util.external.FileUtil;
43
44
45 /**
46  * A utility class to handle <code>multipart/form-data</code> requests, the
47  * kind of requests that support file uploads. This class emulates the interface
48  * of <code>HttpServletRequest</code>, making it familiar to use. It uses a
49  * "push" model where any incoming files are read and saved directly to disk in
50  * the constructor. If you wish to have more flexibility, e.g. write the files
51  * to a database, use the "pull" model <code>MultipartParser</code> instead.
52  * <p>
53  * This class can receive arbitrarily large files (up to an artificial limit you
54  * can set), and fairly efficiently too. It cannot handle nested data (multipart
55  * content within multipart content) or internationalized content (such as non
56  * Latin-1 filenames).
57  * </p>
58  * <p>
59  * See the included <a HREF="upload.war">upload.war </a> for an example of how
60  * to use this class.
61  * <p>
62  * The full file upload specification is contained in experimental RFC 1867,
63  * available at <a HREF="http://www.ietf.org/rfc/rfc1867.txt"
64  * http://www.ietf.org/rfc/rfc1867.txt </a>.
65  * </p>
66  * <p>
67  * PLEASE NOTE: this class uses Multipart Support Classes by Jason Hunter.
68  * Copyright (C) 1998 by Jason Hunter. All rights reserved.
69  * Use of this class is limited. Please see the LICENSE for more information.
70  * Make sure that you project meets the requierements defined by Jason Hunter
71  * respective O'reilly!
72  * </p>
73  *
74  * @see MultipartParser
75  *
76  * @author Jason Hunter
77  * @author Geoff Soutter
78  * @author Joe Peer - _changed_ it for use in DbForms (i apologize)
79  */

80 public class MultipartRequest {
81    private static Log logCat = LogFactory.getLog(MultipartRequest.class); // logging category
82
private Hashtable JavaDoc files = new Hashtable JavaDoc(); // name - UploadedFile
83

84    // for this class
85
//private File dir;
86
private Hashtable JavaDoc parameters = new Hashtable JavaDoc(); // name - Vector of values
87

88    /**
89     * Constructs a new MultipartRequest to handle the specified request,
90     * {saving any uploaded files to the given directory}, and limiting the
91     * upload size to the specified length. If the content is too large, an
92     * IOException is thrown. This constructor actually parses the
93     * <tt>multipart/form-data</tt> and throws an IOException if there's any
94     * problem reading or parsing the request.
95     *
96     * @param request
97     * the servlet request.
98     * @param maxPostSize
99     * the maximum size of the POST content.
100     * @exception IOException
101     * if the uploaded content is larger than
102     * <tt>maxPostSize</tt> or there's a problem reading or
103     * parsing the request.
104     */

105    public MultipartRequest(HttpServletRequest JavaDoc request,
106                            int maxPostSize)
107                     throws IOException JavaDoc {
108       // Sanity check values
109
if (request == null) {
110          throw new IllegalArgumentException JavaDoc("request cannot be null");
111       }
112
113       // Create a new file upload handler
114
DiskFileUpload upload = new DiskFileUpload();
115
116       // Set upload parameters
117
upload.setSizeMax(maxPostSize);
118
119       String JavaDoc tmpDir = System.getProperty("java.io.tmpdir");
120       upload.setRepositoryPath(tmpDir);
121
122       // Parse the request
123
try {
124          List JavaDoc items = upload.parseRequest(request);
125          Iterator JavaDoc iter = items.iterator();
126
127          while (iter.hasNext()) {
128             FileItem item = (FileItem) iter.next();
129             String JavaDoc name = item.getFieldName();
130
131             if (item.isFormField()) {
132                String JavaDoc value = item.getString();
133
134                // plain parameters get allways into parameters structure
135
Vector JavaDoc existingValues = (Vector JavaDoc) parameters.get(name);
136
137                if (existingValues == null) {
138                   existingValues = new Vector JavaDoc();
139                   parameters.put(name, existingValues);
140                }
141
142                existingValues.addElement(value);
143             } else {
144                String JavaDoc fileName = item.getName();
145
146                if (!Util.isNull(fileName)) {
147                   File JavaDoc f = new File JavaDoc(fileName);
148                   // 2004-08-05-HKK/Dziugas Baltrunas:
149
// FileItem always returns the full pathname!
150
fileName = FileUtil.filename(f.getName());
151
152                   // The part actually contained a file
153
// #changes by joe peer:
154
// we must delay storing the file-inputstream (into
155
// database, filesystem or whatever)
156
// until we know exactly what should happen with it
157
FileHolder fileHolder = new FileHolder(fileName, item);
158                   files.put(name, fileHolder);
159                   logCat.info("buffered and now added as " + name
160                               + " the following fileHolder:"
161                               + fileHolder.getFileName());
162
163                   // #changes by joe peer:
164
// if a file parameter is not null it gets into the
165
// parameters structures as well
166
// this is important to provide a simple access to
167
// request (no distinction between files and plain
168
// params)
169
Vector JavaDoc existingValues = (Vector JavaDoc) parameters.get(name);
170
171                   if (existingValues == null) {
172                      existingValues = new Vector JavaDoc();
173                      parameters.put(name, existingValues);
174                   }
175
176                   existingValues.addElement(fileName);
177                }
178             }
179          }
180       } catch (Exception JavaDoc e) {
181          logCat.error("MultipartRequest", e);
182       }
183    }
184
185    /**
186     * Returns the content type of the specified file (as supplied by the client
187     * browser), or null if the file was not included in the upload.
188     *
189     * @param name
190     * the file name.
191     * @return the content type of the file.
192     */

193    public String JavaDoc getContentType(String JavaDoc name) {
194       try {
195          //#changed by joe peer
196
//UploadedFile file = (UploadedFile)files.get(name);
197
FileHolder filePart = (FileHolder) files.get(name);
198
199          return filePart.getContentType(); // may be null
200
} catch (Exception JavaDoc e) {
201          return null;
202       }
203    }
204
205
206    /**
207     * Returns a FilePart object for the specified file this method was added by
208     * joe peer
209     *
210     * @param name
211     * the file name.
212     * @return a FilePart object for the named file.
213     */

214    public FileHolder getFileHolder(String JavaDoc name) {
215       try {
216          return (FileHolder) files.get(name);
217       } catch (Exception JavaDoc e) {
218          return null;
219       }
220    }
221
222
223    /**
224     * Returns a InputStream object for the specified file saved on the server's
225     * filesystem, or null if the file was not included in the upload.
226     *
227     * @param name
228     * the file name.
229     * @return a InputStream object for the named file.
230     */

231    public InputStream JavaDoc getFileInputStream(String JavaDoc name) {
232       try {
233          //#changed by joe peer
234
//UploadedFile file = (UploadedFile)files.get(name);
235
FileHolder filePart = (FileHolder) files.get(name);
236
237          return filePart.getInputStreamFromBuffer(); // may be null
238
} catch (Exception JavaDoc e) {
239          return null;
240       }
241    }
242
243
244    /**
245     * Returns the names of all the uploaded files as an Enumeration of Strings.
246     * It returns an empty Enumeration if there are no uploaded files. Each file
247     * name is the name specified by the form, not by the user.
248     *
249     * @return the names of all the uploaded files as an Enumeration of Strings.
250     */

251    public Enumeration JavaDoc getFileNames() {
252       return files.keys();
253    }
254
255
256    /**
257     * Returns the filesystem name of the specified file, or null if the file
258     * was not included in the upload. A filesystem name is the name specified
259     * by the user. It is also the name under which the file is actually saved.
260     *
261     * @param name
262     * the file name.
263     * @return the filesystem name of the file.
264     */

265    public String JavaDoc getFilesystemName(String JavaDoc name) {
266       try {
267          //#changed by joe peer
268
//UploadedFile file = (UploadedFile)files.get(name);
269
FileHolder filePart = (FileHolder) files.get(name);
270
271          return filePart.getFileName(); // may be null
272
} catch (Exception JavaDoc e) {
273          return null;
274       }
275    }
276
277
278    /**
279     * Returns the value of the named parameter as a String, or null if the
280     * parameter was not sent or was sent without a value. The value is
281     * guaranteed to be in its normal, decoded form. If the parameter has
282     * multiple values, only the last one is returned (for backward
283     * compatibility). For parameters with multiple values, it's possible the
284     * last "value" may be null.
285     *
286     * @param name
287     * the parameter name.
288     * @return the parameter value.
289     */

290    public String JavaDoc getParameter(String JavaDoc name) {
291       try {
292          Vector JavaDoc values = (Vector JavaDoc) parameters.get(name);
293
294          if ((values == null) || (values.size() == 0)) {
295             return null;
296          }
297
298          String JavaDoc value = (String JavaDoc) values.elementAt(0);
299
300          return value;
301       } catch (Exception JavaDoc e) {
302          return null;
303       }
304    }
305
306
307    /**
308     * Returns the names of all the parameters as an Enumeration of Strings. It
309     * returns an empty Enumeration if there are no parameters.
310     *
311     * @return the names of all the parameters as an Enumeration of Strings.
312     */

313    public Enumeration JavaDoc getParameterNames() {
314       return parameters.keys();
315    }
316
317
318    /**
319     * Returns the values of the named parameter as a String array, or null if
320     * the parameter was not sent. The array has one entry for each parameter
321     * field sent. If any field was sent without a value that entry is stored in
322     * the array as a null. The values are guaranteed to be in their normal,
323     * decoded form. A single value is returned as a one-element array.
324     *
325     * @param name
326     * the parameter name.
327     * @return the parameter values.
328     */

329    public String JavaDoc[] getParameterValues(String JavaDoc name) {
330       try {
331          Vector JavaDoc values = (Vector JavaDoc) parameters.get(name);
332
333          if ((values == null) || (values.size() == 0)) {
334             return null;
335          }
336
337          String JavaDoc[] valuesArray = new String JavaDoc[values.size()];
338          values.copyInto(valuesArray);
339
340          return valuesArray;
341       } catch (Exception JavaDoc e) {
342          return null;
343       }
344    }
345 }
346
Popular Tags