KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > admin > filemanager > FileUpload


1 /*
2  Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4  This library is free software; you can redistribute it and/or modify it under the terms
5  of the GNU Lesser General Public License as published by the Free Software Foundation;
6  either version 2.1 of the License, or (at your option) any later version.
7
8  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10  See the GNU Lesser General Public License for more details.
11  */

12
13 /*
14  * FileUploadAction.java
15  *
16  * Created on July 31, 2002, 11:41 AM
17  */

18 package com.openedit.modules.admin.filemanager;
19
20 import java.io.IOException JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26
27 import org.apache.commons.fileupload.FileItem;
28 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
29 import org.apache.commons.fileupload.servlet.ServletFileUpload;
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.openedit.repository.ContentItem;
33 import org.openedit.repository.InputStreamItem;
34
35 import com.openedit.OpenEditException;
36 import com.openedit.WebPageRequest;
37 import com.openedit.page.Page;
38 import com.openedit.page.manage.PageManager;
39 import com.openedit.util.PathUtilities;
40
41 /**
42  * DOCUMENT ME!
43  *
44  * @author cnelson
45  */

46 public class FileUpload
47 {
48     protected PageManager fieldPageManager;
49
50     /** Defaults to 1MB */
51     public static final int BUFFER_SIZE = 1000000;
52
53     private static final Log log = LogFactory.getLog(FileUpload.class);
54
55     /* (non-Javadoc)
56      * @see com.openedit.action.Command#execute(java.util.Map, java.util.Map)
57      */

58     public Map JavaDoc uploadFile(WebPageRequest inContext) throws OpenEditException
59     {
60         if (inContext.getUser() == null && inContext.getUser().hasPermission("oe.edit"))
61         {
62             throw new OpenEditException("You must be logged in to upload files");
63         }
64
65         Map JavaDoc props = parseArguments(inContext);
66         if( props == null)
67         {
68             return null;
69         }
70         String JavaDoc fullpath = (String JavaDoc)props.get("fullpath");
71         String JavaDoc path = (String JavaDoc)props.get("path");
72         
73         if (path == null && fullpath == null)
74         {
75             log.error("No path specified in multipart form");
76             throw new OpenEditException("No path passed in with the upload");
77         }
78         String JavaDoc home = (String JavaDoc)inContext.getPageValue("home");
79         if( home != null && home.length() > 0 && path.startsWith(home))
80         {
81             path = path.substring(home.length());
82         }
83         
84         FileItem fileItem = (FileItem)props.get("file");
85         
86         String JavaDoc finalpath = null;
87         if ( fullpath != null )
88         {
89             finalpath = fullpath;
90         }
91         else
92         {
93             //TODO: Check to see if it is already a directory or ends with /
94
String JavaDoc name = fileItem.getName();
95             name = name = name.replace('\\','/');
96             name = PathUtilities.extractFileName(name);
97             
98             if( path.endsWith("/"))
99             {
100                 finalpath = path + name;
101             }
102             else
103             {
104                 Page page = getPageManager().getPage(path);
105                 if ( page.isFolder() ) //upload to an exising folder
106
{
107                     finalpath = path + "/" + name;
108                 }
109                 else
110                 {
111                     finalpath = path;
112                 }
113             }
114         }
115         finalpath = finalpath.replaceAll(" ","");
116         
117         Page page = saveFile( props, finalpath, inContext );
118         props.put("savedas",page);
119         inContext.setRequestParameter("path", page.getPath());
120         return props;
121     }
122
123
124     /**
125      * inPath is full filename
126      * @param inProps
127      */

128     public Page saveFile(Map JavaDoc inProps, String JavaDoc inPath, WebPageRequest inContext) throws OpenEditException
129     {
130         //From now on we are going to assume people always upload to a directory
131

132         //now put the file there
133
if (inPath.indexOf("..") > -1)
134         {
135             throw new OpenEditException("Illegal path name");
136         }
137         final String JavaDoc path = PathUtilities.resolveRelativePath( inPath, "/");
138         Page page = getPageManager().getPage( path );
139         final FileItem fileItem = (FileItem)inProps.get("file");
140         InputStreamItem revision = new InputStreamItem();
141     // final Date lastModified = new Date();
142
if ( inContext.getUser() == null)
143         {
144             throw new IllegalArgumentException JavaDoc("No user logged in");
145         }
146         revision.setAuthor( inContext.getUser().getUserName() );
147         revision.setType( ContentItem.TYPE_ADDED );
148         revision.setMessage( "Uploaded file");
149         revision.setPath(path);
150         try
151         {
152             revision.setInputStream(fileItem.getInputStream() );
153         } catch ( IOException JavaDoc ex)
154         {
155             throw new OpenEditException(ex);
156         }
157         page.setContentItem(revision);
158         getPageManager().putPage(page);
159         
160         inContext.putPageValue("path",path);
161         inContext.setRequestParameter("path",path);
162         
163         return page;
164     }
165     
166
167
168     /**
169      * @param inContext
170      * @return
171      */

172     public Map JavaDoc parseArguments(WebPageRequest inContext) throws OpenEditException
173     {
174         if ( inContext.getRequest() == null) //used in unit tests
175
{
176             return inContext.getPageMap();
177         }
178         String JavaDoc type = inContext.getRequest().getContentType();
179         if ( type == null || !type.startsWith("multipart"))
180         {
181             return null;
182         }
183         
184         ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
185         //upload.setSizeThreshold(BUFFER_SIZE);
186

187         HttpServletRequest JavaDoc req = inContext.getRequest();
188         String JavaDoc encode = req.getCharacterEncoding();
189         if ( encode == null)
190         {
191             log.info("Encoding not set.");
192             encode = "UTF-8";
193         }
194         log.info("Encoding is set to " + encode);
195         upload.setHeaderEncoding(encode);
196         
197         //upload.setHeaderEncoding()
198
//Content-Transfer-Encoding: binary
199
//upload.setRepositoryPath(repository.pathToFile("admin
200
upload.setSizeMax(-1);
201
202         List JavaDoc fileItems;
203
204         try
205         {
206             fileItems = upload.parseRequest(inContext.getRequest());
207         }
208         catch (Exception JavaDoc e)
209         {
210             throw new OpenEditException(e);
211         }
212
213
214         // This is a multipart MIME-encoded request, so the request
215
// parameters must all be parsed from the POST body, not
216
// gotten directly off the HttpServletRequest.
217
Map JavaDoc props = new HashMap JavaDoc();
218         for (int i = 0; i < fileItems.size(); i++)
219         {
220             FileItem tmp = (FileItem) fileItems.get(i);
221             if (tmp.getFieldName().equals("file"))
222             {
223                 props.put(tmp.getFieldName(),tmp);
224                 props.put("filepath", tmp.getName());
225             }
226             else
227             {
228                 props.put(tmp.getFieldName(),tmp.getString());
229             }
230         }
231         return props;
232     }
233     public PageManager getPageManager()
234     {
235         return fieldPageManager;
236     }
237     public void setPageManager( PageManager pageManager )
238     {
239         fieldPageManager = pageManager;
240     }
241 }
242
Popular Tags