e.g. Calendar Search Help
You must enter a value before pressing Search
spring

Class: org.springframework.web.multipart.cos.CosMultipartResolver   ©

 OK to copy?
001 /*
002  * Copyright 2002-2004 the original author or authors.
003  * 
004  * Licensed under the Apache License, Version 2.0 (the "License");
005  * you may not use this file except in compliance with the License.
006  * You may obtain a copy of the License at
007  * 
008  *      http://www.apache.org/licenses/LICENSE-2.0
009  * 
010  * Unless required by applicable law or agreed to in writing, software
011  * distributed under the License is distributed on an "AS IS" BASIS,
012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013  * See the License for the specific language governing permissions and
014  * limitations under the License.
015  */ 
016 
017 package org.springframework.web.multipart.cos;
018 
019 import java.io.File;
020 import java.io.IOException;
021 import java.util.Enumeration;
022 
023 import javax.servlet.ServletContext;
024 import javax.servlet.http.HttpServletRequest;
025 
026 import com.oreilly.servlet.MultipartRequest;
027 import org.apache.commons.logging.Log;
028 import org.apache.commons.logging.LogFactory;
029 
030 import org.springframework.core.io.Resource;
031 import org.springframework.web.context.ServletContextAware;
032 import org.springframework.web.multipart.MaxUploadSizeExceededException;
033 import org.springframework.web.multipart.MultipartException;
034 import org.springframework.web.multipart.MultipartHttpServletRequest;
035 import org.springframework.web.multipart.MultipartResolver;
036 import org.springframework.web.util.WebUtils;
037 
038 /**
039  * MultipartResolver implementation for Jason Hunter's
040  * <a href="http://www.servlets.com/cos">COS (com.oreilly.servlet)</a>.
041  * Works with a COS MultipartRequest underneath.
042  *
043  * <p>Provides "maxUploadSize" and "defaultEncoding" settings as bean properties;
044  * see respective MultipartRequest constructor parameters for details.
045  * Default maximum file size is unlimited; fallback encoding is the platform's default.
046  *
047  * @author Juergen Hoeller
048  * @since 06.10.2003
049  * @see CosMultipartHttpServletRequest
050  * @see com.oreilly.servlet.MultipartRequest
051  */
052 public class CosMultipartResolver implements MultipartResolver, ServletContextAware {
053 
054     public static final String MULTIPART_CONTENT_TYPE = "multipart/form-data";
055 
056 
057     protected final Log logger = LogFactory.getLog(getClass());
058 
059     private int maxUploadSize = Integer.MAX_VALUE;
060 
061     private String defaultEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
062 
063     private File uploadTempDir;
064 
065 
066     /**
067      * Constructor for use as bean. Determines the servlet container's
068      * temporary directory via the ServletContext passed in as through the
069      * ServletContextAware interface (typically by a WebApplicationContext).
070      * @see #setServletContext
071      * @see org.springframework.web.context.ServletContextAware
072      * @see org.springframework.web.context.WebApplicationContext
073      */
074     public CosMultipartResolver() {
075     }
076 
077     /**
078      * Constructor for standalone usage. Determines the servlet container's
079      * temporary directory via the given ServletContext.
080      * @param servletContext the ServletContext to use
081      */
082     public CosMultipartResolver(ServletContext servletContext) {
083         this.uploadTempDir = WebUtils.getTempDir(servletContext);
084     }
085 
086     /**
087      * Set the maximum allowed size (in bytes) before uploads are refused.
088      * -1 indicates no limit (the default).
089      * @param maxUploadSize the maximum file size allowed
090      */
091     public void setMaxUploadSize(int maxUploadSize) {
092         this.maxUploadSize = maxUploadSize;
093     }
094 
095     /**
096      * Return the maximum allowed size (in bytes) before uploads are refused.
097      */
098     protected int getMaxUploadSize() {
099         return maxUploadSize;
100     }
101 
102     /**
103      * Set the default character encoding to use for parsing requests,
104      * to be applied to headers of individual parts and to form fields.
105      * Default is ISO-8859-1, according to the Servlet spec.
106      * <p>If the request specifies a character encoding itself, the request
107      * encoding will override this setting. This also allows for generically
108      * overriding the character encoding in a filter that invokes the
109      * ServletRequest.setCharacterEncoding method.
110      * @param defaultEncoding the character encoding to use
111      * @see #determineEncoding
112      * @see javax.servlet.ServletRequest#getCharacterEncoding
113      * @see javax.servlet.ServletRequest#setCharacterEncoding
114      * @see WebUtils#DEFAULT_CHARACTER_ENCODING
115      */
116     public void setDefaultEncoding(String defaultEncoding) {
117         this.defaultEncoding = defaultEncoding;
118     }
119 
120     /**
121      * Return the default character encoding to use for parsing requests.
122      */
123     protected String getDefaultEncoding() {
124         return defaultEncoding;
125     }
126 
127     /**
128      * Set the temporary directory where uploaded files get stored.
129      * Default is the servlet container's temporary directory for the web application.
130      * @see org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE
131      */
132     public void setUploadTempDir(Resource uploadTempDir) throws IOException {
133         if (!uploadTempDir.exists() && !uploadTempDir.getFile().mkdirs()) {
134             throw new IllegalArgumentException("Given uploadTempDir [" + uploadTempDir + "] could not be created");
135         }
136         this.uploadTempDir = uploadTempDir.getFile();
137     }
138 
139     /**
140      * Return the temporary directory where uploaded files get stored.
141      */
142     protected File getUploadTempDir() {
143         return uploadTempDir;
144     }
145 
146     public void setServletContext(ServletContext servletContext) {
147         if (this.uploadTempDir == null) {
148             this.uploadTempDir = WebUtils.getTempDir(servletContext);
149         }
150     }
151 
152 
153     public boolean isMultipart(HttpServletRequest request) {
154         return request.getContentType() != null && request.getContentType().startsWith(MULTIPART_CONTENT_TYPE);
155     }
156 
157     public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
158         try {
159             MultipartRequest multipartRequest = newMultipartRequest(request);
160             if (logger.isDebugEnabled()) {
161                 Enumeration fileNames = multipartRequest.getFileNames();
162                 while (fileNames.hasMoreElements()) {
163                     String fileName = (String) fileNames.nextElement();
164                     File file = multipartRequest.getFile(fileName);
165                     logger.debug("Found multipart file '" + fileName + "' of size " + (file != null ? file.length() : 0) +
166                         " bytes with original filename [" + multipartRequest.getOriginalFileName(fileName) +
167                         "], " + (file != null ? "stored at [" + file.getAbsolutePath() + "]" : "empty"));
168                 }
169             }
170             return new CosMultipartHttpServletRequest(request, multipartRequest);
171         }
172         catch (IOException ex) {
173             // Unfortunately, COS always throws an IOException,
174             // so we need to check the error message here!
175             if (ex.getMessage().indexOf("exceeds limit") != -1) {
176                 throw new MaxUploadSizeExceededException(this.maxUploadSize, ex);
177             }
178             else {
179                 throw new MultipartException("Could not parse multipart request", ex);
180             }
181         }
182     }
183 
184     /**
185      * Create a com.oreilly.servlet.MultipartRequest for the given HTTP request.
186      * Can be overridden to use a custom subclass, e.g. for testing purposes.
187      * @param request current HTTP request
188      * @return the new MultipartRequest
189      * @throws IOException if thrown by the MultipartRequest constructor
190      */
191     protected MultipartRequest newMultipartRequest(HttpServletRequest request) throws IOException {
192         String tempPath = this.uploadTempDir.getAbsolutePath();
193         String enc = determineEncoding(request);
194         return new MultipartRequest(request, tempPath, this.maxUploadSize, enc);
195     }
196 
197     /**
198      * Determine the encoding for the given request.
199      * Can be overridden in subclasses.
200      * <p>The default implementation checks the request encoding,
201      * falling back to the default encoding specified for this resolver.
202      * @param request current HTTP request
203      * @return the encoding for the request (never null)
204      * @see javax.servlet.ServletRequest#getCharacterEncoding
205      * @see #setDefaultEncoding
206      */
207     protected String determineEncoding(HttpServletRequest request) {
Rate208         String enc = request.getCharacterEncoding();
209         if (enc == null) {
210             enc = this.defaultEncoding;
211         }
212         return enc;
213     }
214 
215     public void cleanupMultipart(MultipartHttpServletRequest request) {
216         MultipartRequest multipartRequest = ((CosMultipartHttpServletRequest) request).getMultipartRequest();
217         Enumeration fileNames = multipartRequest.getFileNames();
218         while (fileNames.hasMoreElements()) {
219             String fileName = (String) fileNames.nextElement();
220             File file = multipartRequest.getFile(fileName);
221             if (file != null) {
222                 if (file.exists()) {
223                     if (file.delete()) {
224                         if (logger.isDebugEnabled()) {
225                         logger.debug("Cleaned up multipart file '" + fileName + "' with original filename [" +
226                             multipartRequest.getOriginalFileName(fileName) + "], stored at [" +
227                             file.getAbsolutePath() + "]");
228                         }
229                     }
230                     else {
231                         logger.warn("Could not delete multipart file '" + fileName + "' with original filename [" +
232                             multipartRequest.getOriginalFileName(fileName) + "], stored at [" +
233                             file.getAbsolutePath() + "]");
234                     }
235                 }
236                 else {
237                     if (logger.isDebugEnabled()) {
238                         logger.debug("Multipart file '" + fileName + "' with original filename [" +
239                             multipartRequest.getOriginalFileName(fileName) +
240                             "] has already been moved - no cleanup necessary");
241                     }
242                 }
243             }
244         }
245     }
246 
247 }

            
All Examples in File:
Example
Line
Rating (found
useful by...)
208 0% of 0