KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > servlet > upload > impl > AdaptiveFileUpload


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.servlet.upload.impl;
4
5 import jodd.io.FastByteArrayOutputStream;
6 import jodd.io.FileUtil;
7 import jodd.io.FileNameUtil;
8 import jodd.util.SystemUtil;
9 import jodd.servlet.upload.FileUpload;
10 import jodd.servlet.upload.MultipartRequestInputStream;
11 import jodd.servlet.upload.FileUploadFactory;
12
13 import java.io.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.io.FileOutputStream JavaDoc;
16 import java.io.BufferedOutputStream JavaDoc;
17
18 /**
19  * Smart {@link FileUpload} implementation that defer the action of what to do with uploaded file
20  * for later. Internally, it stores uploaded file either in memory if it is small, or, in all
21  * other cases, it stores them in TEMP folder.
22  */

23 public class AdaptiveFileUpload extends FileUpload {
24
25     public AdaptiveFileUpload(MultipartRequestInputStream input) {
26         super(input);
27     }
28
29     public AdaptiveFileUpload(MultipartRequestInputStream input, int memoryThreshold, File JavaDoc uploadPath, int maxFileSize, boolean breakOnError, String JavaDoc[] extensions, boolean allowed) {
30         super(input);
31         this.memoryThreshold = memoryThreshold;
32         this.uploadPath = uploadPath;
33         this.maxFileSize = maxFileSize;
34         this.breakOnError = breakOnError;
35         this.fileExtensions = extensions;
36         this.allowFileExtensions = allowed;
37     }
38
39     // ---------------------------------------------------------------- settings
40

41     protected int memoryThreshold;
42     protected File JavaDoc uploadPath;
43     protected int maxFileSize;
44     protected boolean breakOnError;
45     protected String JavaDoc[] fileExtensions;
46     public boolean allowFileExtensions;
47
48     public int getMemoryThreshold() {
49         return memoryThreshold;
50     }
51
52     public File JavaDoc getUploadPath() {
53         return uploadPath;
54     }
55
56     public int getMaxFileSize() {
57         return maxFileSize;
58     }
59
60     public boolean isBreakOnError() {
61         return breakOnError;
62     }
63
64     public String JavaDoc[] getFileExtensions() {
65         return fileExtensions;
66     }
67
68     public boolean isAllowFileExtensions() {
69         return allowFileExtensions;
70     }
71
72     // ---------------------------------------------------------------- properties
73

74     protected File JavaDoc tempFile;
75     protected byte[] data;
76     protected boolean valid;
77
78     /**
79      * Returns <code>true</code> if file is valid and passes all the rules.
80      */

81     public boolean isValid() {
82         return valid;
83     }
84
85     /**
86      * Returns <code>true</code> if file upload resides in memory.
87      */

88     public boolean isInMemory() {
89         return data != null;
90     }
91
92     // ---------------------------------------------------------------- process
93

94
95     protected boolean matchFileExtension() throws IOException JavaDoc {
96         String JavaDoc fileNameExtension = FileNameUtil.getExtension(getHeader().getFileName());
97         for (int i = 0; i < fileExtensions.length; i++) {
98             if (fileNameExtension.equalsIgnoreCase(fileExtensions[i]) == true) {
99                 if (allowFileExtensions == false) { // extension matched and it is not allowed
100
if (breakOnError == true) {
101                         throw new IOException JavaDoc("Filename extension of uploaded file in not allowed (" + fileNameExtension + ").");
102                     }
103                     size = input.skipToBoundary();
104                     return false;
105                 } else {
106                     return true; // extension matched and it is allowed.
107
}
108             }
109         }
110         if (allowFileExtensions == true) { // extension is not one of the allowed ones.
111
if (breakOnError == true) {
112                 throw new IOException JavaDoc("Filename extension of uploaded file in not in the list of allowed ones (" + fileNameExtension + ").");
113             }
114             size = input.skipToBoundary();
115             return false;
116         }
117         return true;
118     }
119
120     /**
121      * Determines if upload is allowed.
122      */

123     protected boolean checkUpload() throws IOException JavaDoc {
124         if (fileExtensions != null) {
125             if (matchFileExtension() == false) {
126                 return false;
127             }
128         }
129         return true;
130     }
131
132     protected void processStream() throws IOException JavaDoc {
133         if (checkUpload() == false) {
134             return;
135         }
136         size = 0;
137         if (memoryThreshold > 0) {
138             FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream(memoryThreshold + 1);
139             int written = input.copyMax(fbaos, memoryThreshold + 1);
140             data = fbaos.toByteArray();
141             if (written <= memoryThreshold) {
142                 size = data.length;
143                 return;
144             }
145         }
146
147         // create temp file and write already readed data
148
if (uploadPath == null) {
149             uploadPath = new File JavaDoc(SystemUtil.getTempDir());
150         }
151
152         tempFile = File.createTempFile("upload", ".jodd", uploadPath);
153         BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(tempFile));
154         if (data != null) {
155             size = data.length;
156             out.write(data);
157             data = null; // not needed anymore
158
}
159         boolean deleteTempFile = false;
160         try {
161             if (maxFileSize == -1) {
162                 size += input.copyAll(out);
163             } else {
164                 size += input.copyMax(out, maxFileSize - size + 1); // one more byte to detect larger files
165
if (size > maxFileSize) {
166                     deleteTempFile = true;
167                     valid = false;
168                     if (breakOnError == true) {
169                         throw new IOException JavaDoc("File upload (" + header.getFileName() + ") too big.");
170                     }
171                     input.skipToBoundary();
172                     return;
173                 }
174             }
175         } finally {
176             try {
177                 out.close();
178             } finally {
179                 if (deleteTempFile) {
180                     tempFile.delete();
181                     tempFile = null;
182                 }
183             }
184         }
185
186         valid = true;
187     }
188
189     // ---------------------------------------------------------------- operations
190

191
192     /**
193      * Deletes file uploaded item from disk or memory.
194      */

195     public void delete() {
196         if (tempFile != null) {
197             tempFile.delete();
198         }
199         if (data != null) {
200             data = null;
201         }
202     }
203
204     /**
205      * Writes file uploaded item.
206      */

207     public File JavaDoc write(String JavaDoc destination) throws IOException JavaDoc {
208         return write(new File JavaDoc(destination));
209     }
210
211     /**
212      * Writes file upload item to destination folder or to destination file.
213      * Return the destination file.
214      */

215     public File JavaDoc write(File JavaDoc destination) throws IOException JavaDoc {
216         if (destination.isDirectory() == true) {
217             destination = new File JavaDoc(destination, this.header.getFileName());
218         }
219         if (data != null) {
220             FileUtil.writeBytes(destination, data);
221         } else {
222             if (tempFile != null) {
223                 FileUtil.move(tempFile, destination);
224             }
225         }
226         return destination;
227     }
228
229     /**
230      * Returns the content of file upload item.
231      */

232     public byte[] getData() throws IOException JavaDoc {
233         if (data != null) {
234             return data;
235         }
236         if (tempFile != null) {
237             return FileUtil.readBytes(tempFile);
238         }
239         return null;
240     }
241
242
243     // ---------------------------------------------------------------- factory
244

245     public static class Factory implements FileUploadFactory {
246
247         protected int memoryThreshold = 8192;
248         protected File JavaDoc uploadPath;
249         protected int maxFileSize = 102400;
250         protected boolean breakOnError = false;
251         protected String JavaDoc[] fileExtensions;
252         public boolean allowFileExtensions = true;
253
254         public void setMemoryThreshold(int memoryThreshold) {
255             if (memoryThreshold >= 0) {
256                 this.memoryThreshold = memoryThreshold;
257             }
258         }
259
260         public void setUploadPath(File JavaDoc uploadPath) {
261             this.uploadPath = uploadPath;
262         }
263
264         public void setMaxFileSize(int maxFileSize) {
265             this.maxFileSize = maxFileSize;
266         }
267
268         public void setBreakOnError(boolean breakOnError) {
269             this.breakOnError = breakOnError;
270         }
271
272         /**
273          * Allow or disallow set of file extensions. Only one rule can be active at time,
274          * which means user can only specify extensions that are either allowed or disallowed.
275          * Setting this value to <code>null</code> will turn this feature off.
276          */

277         public void setFileExtensions(String JavaDoc[] fileExtensions, boolean allow) {
278             this.fileExtensions = fileExtensions;
279             this.allowFileExtensions = allow;
280         }
281
282         public FileUpload create(MultipartRequestInputStream input) {
283             return new AdaptiveFileUpload(input, memoryThreshold, uploadPath, maxFileSize, breakOnError, fileExtensions, allowFileExtensions);
284         }
285     }
286
287 }
Popular Tags