KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > business > FileManagerImpl


1 package org.roller.business;
2
3 import java.io.File JavaDoc;
4 import java.io.FileOutputStream JavaDoc;
5 import java.io.InputStream JavaDoc;
6 import java.io.OutputStream JavaDoc;
7 import java.math.BigDecimal JavaDoc;
8 import java.util.Map JavaDoc;
9 import org.apache.commons.lang.StringUtils;
10
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.roller.RollerException;
14 import org.roller.config.RollerConfig;
15 import org.roller.model.FileManager;
16 import org.roller.model.Roller;
17 import org.roller.model.RollerFactory;
18 import org.roller.pojos.RollerPropertyData;
19 import org.roller.pojos.WebsiteData;
20 import org.roller.util.RollerMessages;
21
22 /**
23  * Responsible for managing website resources. This base implementation
24  * writes resources to a filesystem.
25  *
26  * @author David M Johnson
27  * @author Allen Gilliland
28  */

29 public class FileManagerImpl implements FileManager
30 {
31     private String JavaDoc upload_dir = null;
32     private String JavaDoc upload_url = null;
33     
34     private static Log mLogger =
35         LogFactory.getFactory().getInstance(FileManagerImpl.class);
36     
37     
38     /**
39      * Create file manager.
40      * @param roller Roller instance.
41      * @param realPath Path to Servlet context directory
42      */

43     public FileManagerImpl()
44     {
45         String JavaDoc uploaddir = RollerConfig.getProperty("uploads.dir");
46         String JavaDoc uploadurl = RollerConfig.getProperty("uploads.url");
47         
48         if(uploaddir == null || uploaddir.trim().length() < 1)
49             uploaddir = "${user.home}"+File.separator+"roller_data"+File.separator+"uploads";
50         
51         if(uploaddir.startsWith("${user.home}"))
52             uploaddir = System.getProperty("user.home") + uploaddir.substring(12);
53         
54         if( ! uploaddir.endsWith(File.separator))
55             uploaddir += File.separator;
56         
57         if(uploadurl == null || uploadurl.trim().length() < 1)
58             uploadurl = File.separator+"resources";
59         
60         this.upload_dir = uploaddir.replace('/',File.separatorChar);
61         this.upload_url = uploadurl;
62     }
63     
64     
65     /**
66      * Get the upload directory being used by this file manager
67      **/

68     public String JavaDoc getUploadDir() {
69         return this.upload_dir;
70     }
71     
72     /**
73      * Get the upload path being used by this file manager
74      **/

75     public String JavaDoc getUploadUrl() {
76         return this.upload_url;
77     }
78     
79     
80     /**
81      * Determine if file can be saved given current RollerConfig settings.
82      */

83     public boolean canSave(
84             WebsiteData site, String JavaDoc name, long size, RollerMessages messages)
85             throws RollerException
86     {
87         Roller mRoller = RollerFactory.getRoller();
88         Map JavaDoc config = mRoller.getPropertiesManager().getProperties();
89         
90         if (!((RollerPropertyData)config.get("uploads.enabled")).getValue().equalsIgnoreCase("true")) {
91             messages.addError("error.upload.disabled");
92             return false;
93         }
94         
95         String JavaDoc allows = ((RollerPropertyData)config.get("uploads.types.allowed")).getValue();
96         String JavaDoc forbids = ((RollerPropertyData)config.get("uploads.types.forbid")).getValue();
97         String JavaDoc[] allowFiles = StringUtils.split(StringUtils.deleteWhitespace(allows), ",");
98         String JavaDoc[] forbidFiles = StringUtils.split(StringUtils.deleteWhitespace(forbids), ",");
99         if (!checkFileType(allowFiles, forbidFiles, name)) {
100             messages.addError("error.upload.forbiddenFile", allows);
101             return false;
102         }
103         
104         BigDecimal JavaDoc maxDirMB = new BigDecimal JavaDoc(
105                 ((RollerPropertyData)config.get("uploads.dir.maxsize")).getValue());
106         int maxDirBytes = (int)(1024000 * maxDirMB.doubleValue());
107         int userDirSize = getUserDirSize(site.getUser().getUserName(), this.upload_dir);
108         if (userDirSize + size > maxDirBytes) {
109             messages.addError("error.upload.dirmax", maxDirMB.toString());
110             return false;
111         }
112         
113         BigDecimal JavaDoc maxFileMB = new BigDecimal JavaDoc(
114                 ((RollerPropertyData)config.get("uploads.file.maxsize")).getValue());
115         int maxFileBytes = (int)(1024000 * maxFileMB.doubleValue());
116         mLogger.debug(""+maxFileBytes);
117         mLogger.debug(""+size);
118         if (size > maxFileBytes) {
119             messages.addError("error.upload.filemax", maxFileMB.toString());
120             return false;
121         }
122         
123         return true;
124     }
125
126     /**
127      * Get collection files in website's resource directory.
128      * @param site Website
129      * @return Collection of files in website's resource directory
130      */

131     public File JavaDoc[] getFiles(WebsiteData site) throws RollerException
132     {
133         String JavaDoc dir = this.upload_dir + site.getUser().getUserName();
134         File JavaDoc uploadDir = new File JavaDoc(dir);
135         return uploadDir.listFiles();
136     }
137
138     /**
139      * Delete named file from website's resource area.
140      */

141     public void deleteFile(WebsiteData site, String JavaDoc name)
142             throws RollerException
143     {
144         String JavaDoc dir = this.upload_dir + site.getUser().getUserName();
145         File JavaDoc f = new File JavaDoc(dir + File.separator + name);
146         f.delete();
147     }
148
149     /**
150      * Save file to website's resource directory.
151      * @param site Website to save to
152      * @param name Name of file to save
153      * @param size Size of file to be saved
154      * @param is Read file from input stream
155      */

156     public void saveFile(WebsiteData site, String JavaDoc name, long size, InputStream JavaDoc is)
157             throws RollerException
158     {
159         if (!canSave(site, name, size, new RollerMessages()))
160         {
161             throw new RollerException("ERROR: upload denied");
162         }
163         
164         byte[] buffer = new byte[8192];
165         int bytesRead = 0;
166         String JavaDoc dir = this.upload_dir;
167         String JavaDoc userName = site.getUser().getUserName();
168
169         File JavaDoc dirPath = new File JavaDoc(dir + File.separator + userName);
170         if (!dirPath.exists())
171         {
172             dirPath.mkdirs();
173         }
174         OutputStream JavaDoc bos = null;
175         try
176         {
177             bos = new FileOutputStream JavaDoc(
178                     dirPath.getAbsolutePath() + File.separator + name);
179             while ((bytesRead = is.read(buffer, 0, 8192)) != -1)
180             {
181                 bos.write(buffer, 0, bytesRead);
182             }
183         }
184         catch (Exception JavaDoc e)
185         {
186             throw new RollerException("ERROR uploading file", e);
187         }
188         finally
189         {
190             try
191             {
192                 bos.flush();
193                 bos.close();
194             }
195             catch (Exception JavaDoc ignored) {}
196         }
197         if (mLogger.isDebugEnabled())
198         {
199             mLogger.debug("The file has been written to \"" + dir + userName + "\"");
200         }
201     }
202
203     /**
204      * Get upload directory path.
205      * @return Upload directory path.
206      * @throws RollerException
207      */

208     /* old method ... no longer used -- Allen G
209     private String getUploadDir() throws RollerException
210     {
211         if(this.upload_dir != null)
212         {
213             return this.upload_dir;
214         }
215         else
216         {
217             Roller mRoller = RollerFactory.getRoller();
218             RollerConfigData config = RollerFactory.getRoller().getConfigManager().getRollerConfig();
219             String dir = config.getUploadDir();
220             if (dir == null || dir.trim().length()==0)
221             {
222                 dir = mRealPath + File.separator + USER_RESOURCES;
223             }
224             
225             return dir;
226         }
227     }
228     */

229     
230     /**
231      * Returns current size of file uploads owned by specified user.
232      * @param username User
233      * @param dir Upload directory
234      * @return Size of user's uploaded files in bytes.
235      */

236     private int getUserDirSize(String JavaDoc username, String JavaDoc dir)
237     {
238         int userDirSize = 0;
239         File JavaDoc d = new File JavaDoc(dir + File.separator + username);
240         if (d.mkdirs() || d.exists())
241         {
242             File JavaDoc[] files = d.listFiles();
243             long dirSize = 0l;
244             for (int i=0; i<files.length; i++)
245             {
246                 if (!files[i].isDirectory())
247                 {
248                     dirSize = dirSize + files[i].length();
249                 }
250             }
251             userDirSize = new Long JavaDoc(dirSize).intValue();
252         }
253         return userDirSize;
254     }
255
256     /**
257      * Return true if file is allowed to be uplaoded given specified allowed and
258      * forbidden file types.
259      * @param allowFiles File types (i.e. extensions) that are allowed
260      * @param forbidFiles File types that are forbidden
261      * @param fileName Name of file to be uploaded
262      * @return True if file is allowed to be uploaded
263      */

264     private boolean checkFileType(
265             String JavaDoc[] allowFiles, String JavaDoc[] forbidFiles, String JavaDoc fileName)
266     {
267         // default to false
268
boolean allowFile = false;
269         
270         // if this person hasn't listed any allows, then assume they want
271
// to allow *all* filetypes, except those listed under forbid
272
if(allowFiles == null || allowFiles.length < 1)
273             allowFile = true;
274         
275         // check for allowed types
276
if (allowFiles != null && allowFiles.length > 0)
277         {
278             for (int y=0; y<allowFiles.length; y++)
279             {
280                 if (fileName.toLowerCase().endsWith(
281                         allowFiles[y].toLowerCase()))
282                 {
283                     allowFile = true;
284                     break;
285                 }
286             }
287         }
288         
289         // check for forbidden types ... this overrides any allows
290
if (forbidFiles != null && forbidFiles.length > 0)
291         {
292             for (int x=0; x<forbidFiles.length; x++)
293             {
294                 if (fileName.toLowerCase().endsWith(
295                         forbidFiles[x].toLowerCase()))
296                 {
297                     allowFile = false;
298                     break;
299                 }
300             }
301         }
302
303         return allowFile;
304     }
305
306     /* (non-Javadoc)
307      * @see org.roller.model.FileManager#release()
308      */

309     public void release()
310     {
311         // TODO Auto-generated method stub
312

313     }
314 }
315
Popular Tags