KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > filters > CommonsFileUploadMultipartRequestFilter


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.filters;
14
15 import info.magnolia.cms.beans.runtime.MultipartForm;
16 import info.magnolia.cms.core.Path;
17
18 import java.io.File JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23
24 import javax.servlet.Filter JavaDoc;
25 import javax.servlet.FilterChain JavaDoc;
26 import javax.servlet.FilterConfig JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import javax.servlet.ServletRequest JavaDoc;
29 import javax.servlet.ServletResponse JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31
32 import org.apache.commons.fileupload.FileItem;
33 import org.apache.commons.fileupload.FileUploadBase;
34 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
35 import org.apache.commons.fileupload.servlet.ServletFileUpload;
36 import org.apache.commons.fileupload.servlet.ServletRequestContext;
37 import org.apache.commons.lang.StringUtils;
38
39
40 /**
41  * A <code>Filter</code> that determines if a <code>HttpServletRequest</code> contains multipart content and if so
42  * parses it into a request attribute for further processing.
43  * @author Andreas Brenk
44  * @version $Id: CommonsFileUploadMultipartRequestFilter.java 6341 2006-09-12 09:18:27Z philipp $
45  */

46 public class CommonsFileUploadMultipartRequestFilter implements Filter JavaDoc {
47
48     /**
49      * Default max file upload size (200 MB).
50      */

51     private static final int DEFAULT_MAX_FILE_SIZE = 209715200;
52
53     /**
54      * Config parameter name for max file size.
55      */

56     private static final String JavaDoc PARAM_MAX_FILE_SIZE = "maxFileSize";
57
58     /**
59      * The maximum size a file upload may have.
60      */

61     private int maxFileSize = DEFAULT_MAX_FILE_SIZE;
62
63     /**
64      * The directory for temporary storage of uploaded files.
65      */

66     private File JavaDoc tempDir;
67
68     /**
69      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
70      */

71     public void init(FilterConfig JavaDoc config) throws ServletException JavaDoc {
72         String JavaDoc maxFileSize = config.getInitParameter(PARAM_MAX_FILE_SIZE);
73         if (maxFileSize != null) {
74             this.maxFileSize = Integer.parseInt(maxFileSize);
75         }
76
77         this.tempDir = new File JavaDoc(Path.getTempDirectoryPath());
78     }
79
80     /**
81      * @see javax.servlet.Filter#destroy()
82      */

83     public void destroy() {
84         // unused
85
}
86
87     /**
88      * Determine if the request has multipart content and if so parse it into a <code>MultipartForm</code> and store
89      * it as a request attribute.
90      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
91      * javax.servlet.FilterChain)
92      */

93     public void doFilter(ServletRequest JavaDoc request, ServletResponse JavaDoc response, FilterChain JavaDoc chain) throws IOException JavaDoc,
94         ServletException JavaDoc {
95         if (request instanceof HttpServletRequest JavaDoc) {
96
97             boolean isMultipartContent = FileUploadBase.isMultipartContent(new ServletRequestContext(
98                 (HttpServletRequest JavaDoc) request));
99             if (isMultipartContent) {
100                 try {
101                     parseRequest((HttpServletRequest JavaDoc) request);
102                 }
103                 catch (IOException JavaDoc e) {
104                     throw e;
105                 }
106                 catch (Exception JavaDoc e) {
107                     throw new ServletException JavaDoc(e);
108                 }
109             }
110         }
111
112         chain.doFilter(request, response);
113     }
114
115     /**
116      * Parse the request and store it as a request attribute.
117      */

118     private void parseRequest(HttpServletRequest JavaDoc request) throws Exception JavaDoc {
119         MultipartForm form = new MultipartForm();
120
121         ServletFileUpload upload = newServletFileUpload();
122
123         List JavaDoc fileItems = upload.parseRequest(request);
124
125         for (Iterator JavaDoc fileItemIterator = fileItems.iterator(); fileItemIterator.hasNext();) {
126             FileItem item = (FileItem) fileItemIterator.next();
127             if (item.isFormField()) {
128                 addField(request, item, form);
129             }
130             else {
131                 addFile(item, form);
132             }
133         }
134
135         request.setAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, form);
136     }
137
138     /**
139      * Create a new <code>DiskFileUpload</code>.
140      */

141     private ServletFileUpload newServletFileUpload() {
142         ServletFileUpload upload = new ServletFileUpload();
143         upload.setSizeMax(this.maxFileSize);
144         DiskFileItemFactory fif = new DiskFileItemFactory();
145         fif.setRepository(Path.getTempDirectory());
146         upload.setFileItemFactory(fif);
147
148         return upload;
149     }
150
151     /**
152      * Add the <code>FileItem</code> as a paramter into the <code>MultipartForm</code>.
153      */

154     private void addField(HttpServletRequest JavaDoc request, FileItem item, MultipartForm form) {
155         String JavaDoc name = item.getFieldName();
156
157         String JavaDoc value;
158         try {
159             String JavaDoc encoding = StringUtils.defaultString(request.getCharacterEncoding(), "UTF-8");
160             value = item.getString(encoding);
161         }
162         catch (UnsupportedEncodingException JavaDoc ex) {
163             value = item.getString();
164         }
165         form.addParameter(name, value);
166
167         String JavaDoc[] values = request.getParameterValues(name);
168         if (values != null) {
169             form.addparameterValues(name, values);
170         }
171     }
172
173     /**
174      * Add the <code>FileItem</code> as a document into the <code>MultipartForm</code>.
175      */

176     private void addFile(FileItem item, MultipartForm form) throws Exception JavaDoc {
177         String JavaDoc atomName = item.getFieldName();
178         String JavaDoc fileName = item.getName();
179         String JavaDoc type = item.getContentType();
180         File JavaDoc file = File.createTempFile(atomName, null, this.tempDir);
181         item.write(file);
182
183         form.addDocument(atomName, fileName, type, file);
184     }
185 }
186
Popular Tags