KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > multipart > cos > CosMultipartResolver


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.multipart.cos;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Enumeration JavaDoc;
22
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25
26 import com.oreilly.servlet.MultipartRequest;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 import org.springframework.core.io.Resource;
31 import org.springframework.web.context.ServletContextAware;
32 import org.springframework.web.multipart.MaxUploadSizeExceededException;
33 import org.springframework.web.multipart.MultipartException;
34 import org.springframework.web.multipart.MultipartHttpServletRequest;
35 import org.springframework.web.multipart.MultipartResolver;
36 import org.springframework.web.util.WebUtils;
37
38 /**
39  * {@link MultipartResolver} implementation for Jason Hunter's
40  * <a HREF="http://www.servlets.com/cos">COS (com.oreilly.servlet)</a>.
41  * Works with a COS MultipartRequest underneath.
42  *
43  * <p>Provides "maxUploadSize" and "defaultEncoding" settings as bean properties;
44  * see respective MultipartRequest constructor parameters for details.
45  * Default maximum file size is unlimited; fallback encoding is the platform's default.
46  *
47  * @author Juergen Hoeller
48  * @since 06.10.2003
49  * @see CosMultipartHttpServletRequest
50  * @see com.oreilly.servlet.MultipartRequest
51  */

52 public class CosMultipartResolver implements MultipartResolver, ServletContextAware {
53
54     /**
55      * Constant identifier for the mulipart content type : 'multipart/form-data'.
56      */

57     public static final String JavaDoc MULTIPART_CONTENT_TYPE = "multipart/form-data";
58
59
60     /** Logger available to subclasses */
61     protected final Log logger = LogFactory.getLog(getClass());
62
63     private int maxUploadSize = Integer.MAX_VALUE;
64
65     private String JavaDoc defaultEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
66
67     private File JavaDoc uploadTempDir;
68
69
70     /**
71      * Constructor for use as bean. Determines the servlet container's
72      * temporary directory via the ServletContext passed in as through the
73      * ServletContextAware interface (typically by a WebApplicationContext).
74      * @see #setServletContext
75      * @see org.springframework.web.context.ServletContextAware
76      * @see org.springframework.web.context.WebApplicationContext
77      */

78     public CosMultipartResolver() {
79     }
80
81     /**
82      * Constructor for standalone usage. Determines the servlet container's
83      * temporary directory via the given ServletContext.
84      * @param servletContext the ServletContext to use (must not be <code>null</code>)
85      * @throws IllegalArgumentException if the supplied {@link ServletContext} is <code>null</code>
86      */

87     public CosMultipartResolver(ServletContext JavaDoc servletContext) {
88         this.uploadTempDir = WebUtils.getTempDir(servletContext);
89     }
90
91     /**
92      * Set the maximum allowed size (in bytes) before uploads are refused.
93      * -1 indicates no limit (the default).
94      * @param maxUploadSize the maximum file size allowed
95      */

96     public void setMaxUploadSize(int maxUploadSize) {
97         this.maxUploadSize = maxUploadSize;
98     }
99
100     /**
101      * Return the maximum allowed size (in bytes) before uploads are refused.
102      */

103     protected int getMaxUploadSize() {
104         return maxUploadSize;
105     }
106
107     /**
108      * Set the default character encoding to use for parsing requests,
109      * to be applied to headers of individual parts and to form fields.
110      * Default is ISO-8859-1, according to the Servlet spec.
111      * <p>If the request specifies a character encoding itself, the request
112      * encoding will override this setting. This also allows for generically
113      * overriding the character encoding in a filter that invokes the
114      * ServletRequest.setCharacterEncoding method.
115      * @param defaultEncoding the character encoding to use
116      * @see #determineEncoding
117      * @see javax.servlet.ServletRequest#getCharacterEncoding
118      * @see javax.servlet.ServletRequest#setCharacterEncoding
119      * @see WebUtils#DEFAULT_CHARACTER_ENCODING
120      */

121     public void setDefaultEncoding(String JavaDoc defaultEncoding) {
122         this.defaultEncoding = defaultEncoding;
123     }
124
125     /**
126      * Return the default character encoding to use for parsing requests.
127      */

128     protected String JavaDoc getDefaultEncoding() {
129         return defaultEncoding;
130     }
131
132     /**
133      * Set the temporary directory where uploaded files get stored.
134      * Default is the servlet container's temporary directory for the web application.
135      * @see org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE
136      */

137     public void setUploadTempDir(Resource uploadTempDir) throws IOException JavaDoc {
138         if (!uploadTempDir.exists() && !uploadTempDir.getFile().mkdirs()) {
139             throw new IllegalArgumentException JavaDoc("Given uploadTempDir [" + uploadTempDir + "] could not be created");
140         }
141         this.uploadTempDir = uploadTempDir.getFile();
142     }
143
144     /**
145      * Return the temporary directory where uploaded files get stored.
146      */

147     protected File JavaDoc getUploadTempDir() {
148         return uploadTempDir;
149     }
150
151     public void setServletContext(ServletContext JavaDoc servletContext) {
152         if (this.uploadTempDir == null) {
153             this.uploadTempDir = WebUtils.getTempDir(servletContext);
154         }
155     }
156
157
158     public boolean isMultipart(HttpServletRequest JavaDoc request) {
159         return request.getContentType() != null && request.getContentType().startsWith(MULTIPART_CONTENT_TYPE);
160     }
161
162     public MultipartHttpServletRequest resolveMultipart(HttpServletRequest JavaDoc request) throws MultipartException {
163         try {
164             MultipartRequest multipartRequest = newMultipartRequest(request);
165             if (logger.isDebugEnabled()) {
166                 Enumeration JavaDoc fileNames = multipartRequest.getFileNames();
167                 while (fileNames.hasMoreElements()) {
168                     String JavaDoc fileName = (String JavaDoc) fileNames.nextElement();
169                     File JavaDoc file = multipartRequest.getFile(fileName);
170                     logger.debug("Found multipart file '" + fileName + "' of size " + (file != null ? file.length() : 0) +
171                         " bytes with original filename [" + multipartRequest.getOriginalFileName(fileName) +
172                         "], " + (file != null ? "stored at [" + file.getAbsolutePath() + "]" : "empty"));
173                 }
174             }
175             return new CosMultipartHttpServletRequest(request, multipartRequest);
176         }
177         catch (IOException JavaDoc ex) {
178             // Unfortunately, COS always throws an IOException,
179
// so we need to check the error message here!
180
if (ex.getMessage().indexOf("exceeds limit") != -1) {
181                 throw new MaxUploadSizeExceededException(this.maxUploadSize, ex);
182             }
183             else {
184                 throw new MultipartException("Could not parse multipart request", ex);
185             }
186         }
187     }
188
189     /**
190      * Create a com.oreilly.servlet.MultipartRequest for the given HTTP request.
191      * Can be overridden to use a custom subclass, e.g. for testing purposes.
192      * @param request current HTTP request
193      * @return the new MultipartRequest
194      * @throws IOException if thrown by the MultipartRequest constructor
195      */

196     protected MultipartRequest newMultipartRequest(HttpServletRequest JavaDoc request) throws IOException JavaDoc {
197         String JavaDoc tempPath = this.uploadTempDir.getAbsolutePath();
198         String JavaDoc enc = determineEncoding(request);
199         return new MultipartRequest(request, tempPath, this.maxUploadSize, enc);
200     }
201
202     /**
203      * Determine the encoding for the given request.
204      * Can be overridden in subclasses.
205      * <p>The default implementation checks the request encoding,
206      * falling back to the default encoding specified for this resolver.
207      * @param request current HTTP request
208      * @return the encoding for the request (never <code>null</code>)
209      * @see javax.servlet.ServletRequest#getCharacterEncoding
210      * @see #setDefaultEncoding
211      */

212     protected String JavaDoc determineEncoding(HttpServletRequest JavaDoc request) {
213         String JavaDoc enc = request.getCharacterEncoding();
214         if (enc == null) {
215             enc = this.defaultEncoding;
216         }
217         return enc;
218     }
219
220     public void cleanupMultipart(MultipartHttpServletRequest request) {
221         MultipartRequest multipartRequest = ((CosMultipartHttpServletRequest) request).getMultipartRequest();
222         Enumeration JavaDoc fileNames = multipartRequest.getFileNames();
223         while (fileNames.hasMoreElements()) {
224             String JavaDoc fileName = (String JavaDoc) fileNames.nextElement();
225             File JavaDoc file = multipartRequest.getFile(fileName);
226             if (file != null) {
227                 if (file.exists()) {
228                     if (file.delete()) {
229                         if (logger.isDebugEnabled()) {
230                         logger.debug("Cleaned up multipart file '" + fileName + "' with original filename [" +
231                             multipartRequest.getOriginalFileName(fileName) + "], stored at [" +
232                             file.getAbsolutePath() + "]");
233                         }
234                     }
235                     else {
236                         logger.warn("Could not delete multipart file '" + fileName + "' with original filename [" +
237                             multipartRequest.getOriginalFileName(fileName) + "], stored at [" +
238                             file.getAbsolutePath() + "]");
239                     }
240                 }
241                 else {
242                     if (logger.isDebugEnabled()) {
243                         logger.debug("Multipart file '" + fileName + "' with original filename [" +
244                             multipartRequest.getOriginalFileName(fileName) +
245                             "] has already been moved - no cleanup necessary");
246                     }
247                 }
248             }
249         }
250     }
251
252 }
253
Popular Tags