KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > dispatcher > multipart > MultiPartRequestWrapper


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.webwork.dispatcher.multipart;
6
7 import com.opensymphony.webwork.config.Configuration;
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10
11 import javax.servlet.http.HttpServletRequest JavaDoc;
12 import java.io.File JavaDoc;
13 import java.lang.reflect.Constructor JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.*;
16
17
18 /**
19  * Parses a multipart request and provides a wrapper around the request. The parsing implementation used
20  * depends on the <tt>webwork.multipart.parser</tt> setting. It should be set to a class which
21  * extends {@link com.opensymphony.webwork.dispatcher.multipart.MultiPartRequest}. <p>
22  * <p/>
23  * Webwork ships with three implementations,
24  * {@link com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest}, and
25  * {@link com.opensymphony.webwork.dispatcher.multipart.CosMultiPartRequest} and
26  * {@link com.opensymphony.webwork.dispatcher.multipart.JakartaMultiPartRequest}. The Pell implementation
27  * is the default. The <tt>webwork.multipart.parser</tt> property should be set to <tt>pell</tt> for
28  * the Pell implementation and <tt>cos</tt> for the Jason Hunter implementation. <p>
29  * <p/>
30  * The files are uploaded when the object is instantiated. If there are any errors they are logged using
31  * {@link #addError(String)}. An action handling a multipart form should first check {@link #hasErrors()}
32  * before doing any other processing. <p>
33  *
34  * @author Matt Baldree
35  */

36 public class MultiPartRequestWrapper extends WebWorkRequestWrapper {
37     protected static final Log log = LogFactory.getLog(MultiPartRequestWrapper.class);
38
39     Collection errors;
40     MultiPartRequest multi;
41
42     /**
43      * Instantiates the appropriate MultiPartRequest parser implementation and processes the data.
44      *
45      * @param request the servlet request object
46      * @param saveDir directory to save the file(s) to
47      * @param maxSize maximum file size allowed
48      */

49     public MultiPartRequestWrapper(HttpServletRequest JavaDoc request, String JavaDoc saveDir, int maxSize) {
50         super(request);
51
52         if (request instanceof MultiPartRequest) {
53             multi = (MultiPartRequest) request;
54         } else {
55             String JavaDoc parser = Configuration.getString("webwork.multipart.parser");
56
57             // If it's not set, use Pell
58
if (parser.equals("")) {
59                 log.warn("Property webwork.multipart.parser not set." +
60                         " Using com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest");
61                 parser = "com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest";
62             }
63             // legacy support for old style property values
64
else if (parser.equals("pell")) {
65                 parser = "com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest";
66             } else if (parser.equals("cos")) {
67                 parser = "com.opensymphony.webwork.dispatcher.multipart.CosMultiPartRequest";
68             } else if (parser.equals("jakarta")) {
69                 parser = "com.opensymphony.webwork.dispatcher.multipart.JakartaMultiPartRequest";
70             }
71
72             try {
73                 Class JavaDoc baseClazz = com.opensymphony.webwork.dispatcher.multipart.MultiPartRequest.class;
74
75                 Class JavaDoc clazz = Class.forName(parser);
76
77                 // make sure it extends MultiPartRequest
78
if (!baseClazz.isAssignableFrom(clazz)) {
79                     addError("Class '" + parser + "' does not extend MultiPartRequest");
80
81                     return;
82                 }
83
84                 // get the constructor
85
Constructor JavaDoc ctor = clazz.getDeclaredConstructor(new Class JavaDoc[]{
86                         Class.forName("javax.servlet.http.HttpServletRequest"),
87                         java.lang.String JavaDoc.class, int.class
88                 });
89
90                 // build the parameter list
91
Object JavaDoc[] parms = new Object JavaDoc[]{
92                         request, saveDir, new Integer JavaDoc(maxSize)
93                 };
94
95                 // instantiate it
96
multi = (MultiPartRequest) ctor.newInstance(parms);
97                 for (Iterator iter = multi.getErrors().iterator(); iter.hasNext();) {
98                     String JavaDoc error = (String JavaDoc) iter.next();
99                     addError(error);
100                 }
101             } catch (ClassNotFoundException JavaDoc e) {
102                 addError("Class: " + parser + " not found.");
103             } catch (NoSuchMethodException JavaDoc e) {
104                 addError("Constructor error for " + parser + ": " + e);
105             } catch (InstantiationException JavaDoc e) {
106                 addError("Error instantiating " + parser + ": " + e);
107             } catch (IllegalAccessException JavaDoc e) {
108                 addError("Access errror for " + parser + ": " + e);
109             } catch (InvocationTargetException JavaDoc e) {
110                 // This is a wrapper for any exceptions thrown by the ctor called from newInstance
111
addError(e.getTargetException().toString());
112             }
113         }
114     }
115
116     /**
117      * @deprecated use {@link #getFileParameterNames()} instead
118      */

119     public Enumeration getFileNames() {
120         return getFileParameterNames();
121     }
122
123     /**
124      * Get an enumeration of the parameter names for uploaded files
125      *
126      * @return enumeration of parameter names for uploaded files
127      */

128     public Enumeration getFileParameterNames() {
129         if (multi == null) {
130             return null;
131         }
132
133         return multi.getFileParameterNames();
134     }
135
136     /**
137      * @deprecated use {@link #getContentTypes(String)} instead
138      */

139     public String JavaDoc getContentType(String JavaDoc fieldName) {
140         String JavaDoc[] contentTypes = getContentTypes(fieldName);
141         if (contentTypes != null && contentTypes.length > 0) {
142             return contentTypes[0];
143         }
144
145         return null;
146     }
147
148
149     /**
150      * Get an array of content encoding for the specified input field name or <tt>null</tt> if
151      * no content type was specified.
152      *
153      * @param name input field name
154      * @return an array of content encoding for the specified input field name
155      */

156     public String JavaDoc[] getContentTypes(String JavaDoc name) {
157         if (multi == null) {
158             return null;
159         }
160
161         return multi.getContentType(name);
162     }
163
164     /**
165      * @deprecated use {@link #getFiles(String)} instead
166      */

167     public File JavaDoc getFile(String JavaDoc fieldName) {
168         File JavaDoc[] files = getFiles(fieldName);
169         if (files != null && files.length > 0) {
170             return files[0];
171         }
172
173         return null;
174     }
175
176     /**
177      * Get a {@link java.io.File[]} for the given input field name.
178      *
179      * @param fieldName input field name
180      * @return a File[] object for files associated with the specified input field name
181      */

182     public File JavaDoc[] getFiles(String JavaDoc fieldName) {
183         if (multi == null) {
184             return null;
185         }
186
187         return multi.getFile(fieldName);
188     }
189
190     /**
191      * Get a String array of the file names for uploaded files
192      *
193      * @return a String[] of file names for uploaded files
194      */

195     public String JavaDoc[] getFileNames(String JavaDoc fieldName) {
196         if (multi == null) {
197             return null;
198         }
199
200         return multi.getFileNames(fieldName);
201     }
202
203     /**
204      * @deprecated use {@link #getFileSystemNames(String)} instead
205      */

206     public String JavaDoc getFilesystemName(String JavaDoc fieldName) {
207         String JavaDoc[] names = getFileSystemNames(fieldName);
208         if (names != null && names.length > 0) {
209             return names[0];
210         }
211
212         return null;
213     }
214
215     /**
216      * Get the filename(s) of the file(s) uploaded for the given input field name.
217      * Returns <tt>null</tt> if the file is not found.
218      *
219      * @param fieldName input field name
220      * @return the filename(s) of the file(s) uploaded for the given input field name or
221      * <tt>null</tt> if name not found.
222      */

223     public String JavaDoc[] getFileSystemNames(String JavaDoc fieldName) {
224         if (multi == null) {
225             return null;
226         }
227
228         return multi.getFilesystemName(fieldName);
229     }
230
231     /**
232      * @see javax.servlet.http.HttpServletRequest#getParameter(String)
233      */

234     public String JavaDoc getParameter(String JavaDoc name) {
235         return ((multi == null) || (multi.getParameter(name) == null)) ? super.getParameter(name) : multi.getParameter(name);
236     }
237
238     /**
239      * @see javax.servlet.http.HttpServletRequest#getParameterMap()
240      */

241     public Map getParameterMap() {
242         Map map = new HashMap();
243         Enumeration enumeration = getParameterNames();
244
245         while (enumeration.hasMoreElements()) {
246             String JavaDoc name = (String JavaDoc) enumeration.nextElement();
247             map.put(name, this.getParameterValues(name));
248         }
249
250         return map;
251     }
252
253     /**
254      * @see javax.servlet.http.HttpServletRequest#getParameterNames()
255      */

256     public Enumeration getParameterNames() {
257         if (multi == null) {
258             return super.getParameterNames();
259         } else {
260             return mergeParams(multi.getParameterNames(), super.getParameterNames());
261         }
262     }
263
264     /**
265      * @see javax.servlet.http.HttpServletRequest#getParameterValues(String)
266      */

267     public String JavaDoc[] getParameterValues(String JavaDoc name) {
268         return ((multi == null) || (multi.getParameterValues(name) == null)) ? super.getParameterValues(name) : multi.getParameterValues(name);
269     }
270
271     /**
272      * Returns <tt>true</tt> if any errors occured when parsing the HTTP multipart request, <tt>false</tt> otherwise.
273      *
274      * @return <tt>true</tt> if any errors occured when parsing the HTTP multipart request, <tt>false</tt> otherwise.
275      */

276     public boolean hasErrors() {
277         if ((errors == null) || errors.isEmpty()) {
278             return false;
279         } else {
280             return true;
281         }
282     }
283
284     /**
285      * Returns a collection of any errors generated when parsing the multipart request.
286      *
287      * @return the error Collection.
288      */

289     public Collection getErrors() {
290         return errors;
291     }
292
293     /**
294      * Adds an error message.
295      *
296      * @param anErrorMessage the error message to report.
297      */

298     protected void addError(String JavaDoc anErrorMessage) {
299         if (errors == null) {
300             errors = new ArrayList();
301         }
302
303         errors.add(anErrorMessage);
304     }
305
306     /**
307      * Merges 2 enumeration of parameters as one.
308      *
309      * @param params1 the first enumeration.
310      * @param params2 the second enumeration.
311      * @return a single Enumeration of all elements from both Enumerations.
312      */

313     protected Enumeration mergeParams(Enumeration params1, Enumeration params2) {
314         Vector temp = new Vector();
315
316         while (params1.hasMoreElements()) {
317             temp.add(params1.nextElement());
318         }
319
320         while (params2.hasMoreElements()) {
321             temp.add(params2.nextElement());
322         }
323
324         return temp.elements();
325     }
326 }
327
Popular Tags