| 1 | |
package org.webslinger.commons.fileupload; |
| 2 | |
|
| 3 | |
import java.io.IOException; |
| 4 | |
import java.util.ArrayList; |
| 5 | |
import java.util.Enumeration; |
| 6 | |
import java.util.HashMap; |
| 7 | |
import java.util.List; |
| 8 | |
import java.util.Map; |
| 9 | |
import javax.servlet.http.HttpServletRequest; |
| 10 | |
|
| 11 | |
import org.apache.commons.fileupload.FileItem; |
| 12 | |
import org.apache.commons.fileupload.FileItemFactory; |
| 13 | |
import org.apache.commons.fileupload.FileUploadException; |
| 14 | |
import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
| 15 | |
import org.apache.commons.fileupload.servlet.ServletFileUpload; |
| 16 | |
|
| 17 | |
import org.apache.commons.vfs.FileObject; |
| 18 | |
|
| 19 | |
import org.webslinger.io.Charsets; |
| 20 | |
import org.webslinger.io.IOUtil; |
| 21 | |
|
| 22 | |
public class CommonsVfsFileItemFactory implements FileItemFactory { |
| 23 | |
private final FileObject dir; |
| 24 | |
private int count; |
| 25 | |
|
| 26 | 26 | public CommonsVfsFileItemFactory(FileObject dir) { |
| 27 | 26 | this.dir = dir; |
| 28 | 26 | } |
| 29 | |
|
| 30 | |
synchronized FileObject createFile(String contentType) throws IOException { |
| 31 | |
while (true) { |
| 32 | 0 | FileObject file = dir.resolveFile(Integer.toString(count++)); |
| 33 | 0 | if (!file.exists()) { |
| 34 | 0 | file.createFile(); |
| 35 | 0 | file.getContent().setAttribute("content-type", contentType); |
| 36 | 0 | return file; |
| 37 | |
} |
| 38 | 0 | } |
| 39 | |
} |
| 40 | |
|
| 41 | |
void removeFile(FileObject file) throws IOException { |
| 42 | 0 | file.delete(); |
| 43 | 0 | } |
| 44 | |
|
| 45 | |
public FileItem createItem(String fieldName, final String contentType, boolean isFormField, String fileName) { |
| 46 | 0 | FileItem item = new AbstractCommonsVfsFileItem(fileName) { |
| 47 | |
private FileObject file; |
| 48 | |
|
| 49 | |
public synchronized FileObject getFile() throws IOException { |
| 50 | 0 | if (file != null) return file; |
| 51 | 0 | file = createFile(getContentType()); |
| 52 | 0 | return file; |
| 53 | |
} |
| 54 | |
|
| 55 | |
public synchronized void delete() { |
| 56 | 0 | if (file == null) return; |
| 57 | |
try { |
| 58 | 0 | file.delete(); |
| 59 | 0 | removeFile(file); |
| 60 | 0 | } catch (IOException e) { |
| 61 | 0 | throw (IllegalArgumentException) new IllegalArgumentException(e.getMessage()).initCause(e); |
| 62 | 0 | } |
| 63 | 0 | file = null; |
| 64 | 0 | } |
| 65 | |
|
| 66 | |
public String getContentType() { |
| 67 | 0 | return contentType; |
| 68 | |
} |
| 69 | |
}; |
| 70 | 0 | item.setFieldName(fieldName); |
| 71 | 0 | item.setFormField(isFormField); |
| 72 | 0 | return item; |
| 73 | |
} |
| 74 | |
} |