KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > files > factories > FileFactory


1 package com.dotmarketing.portlets.files.factories;
2
3 import java.io.IOException JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.List JavaDoc;
6
7 import javax.servlet.http.HttpServletRequest JavaDoc;
8
9 import com.dotmarketing.beans.Host;
10 import com.dotmarketing.beans.Identifier;
11 import com.dotmarketing.beans.Inode;
12 import com.dotmarketing.beans.PermissionAsset;
13 import com.dotmarketing.beans.Tree;
14 import com.dotmarketing.cache.LiveCache;
15 import com.dotmarketing.cache.PermissionCache;
16 import com.dotmarketing.cache.WorkingCache;
17 import com.dotmarketing.db.DotHibernate;
18 import com.dotmarketing.exception.DotRuntimeException;
19 import com.dotmarketing.factories.HostFactory;
20 import com.dotmarketing.factories.IdentifierFactory;
21 import com.dotmarketing.factories.InodeFactory;
22 import com.dotmarketing.factories.PermissionFactory;
23 import com.dotmarketing.factories.TreeFactory;
24 import com.dotmarketing.factories.WebAssetFactory;
25 import com.dotmarketing.menubuilders.RefreshMenus;
26 import com.dotmarketing.portlets.files.model.File;
27 import com.dotmarketing.portlets.folders.model.Folder;
28 import com.dotmarketing.util.Config;
29 import com.dotmarketing.util.Logger;
30 import com.dotmarketing.util.UtilMethods;
31 import com.dotmarketing.util.WebKeys;
32 import com.liferay.portal.model.Role;
33 import com.liferay.portal.model.User;
34 import com.liferay.portal.struts.ActionException;
35 import com.liferay.portlet.ActionRequestImpl;
36 import com.liferay.util.servlet.SessionMessages;
37
38 /**
39  *
40  * @author will
41  */

42 public class FileFactory {
43
44     public static File getChildImage(Inode i) {
45
46         return (File) InodeFactory.getChildOfClassbyCondition(i, File.class,
47                 "(file_name like '%.jpg' or file_name like '%.gif')");
48
49     }
50
51     public static java.util.List JavaDoc getLiveFiles() {
52         DotHibernate dh = new DotHibernate(File.class);
53         dh.setQuery("from inode in class com.dotmarketing.portlets.files.model.File where live = "
54                 + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
55                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse());
56         return dh.list();
57     }
58
59     public static java.util.List JavaDoc getWorkingFiles() {
60         DotHibernate dh = new DotHibernate(File.class);
61         dh.setQuery("from inode in class com.dotmarketing.portlets.files.model.File where working = "
62                 + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
63                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse());
64         return dh.list();
65     }
66
67     public static File getChildMP3(Inode i) {
68         return (File) InodeFactory.getChildOfClassbyCondition(i, File.class, "file_name like '%.mp3'");
69
70     }
71
72     public static java.util.List JavaDoc getChildrenFilesByOrder(Inode i) {
73
74         return InodeFactory.getChildrenClassByOrder(i, File.class, "sort_order");
75
76     }
77
78     public static java.util.List JavaDoc getFileChildrenByCondition(Inode i, String JavaDoc condition) {
79
80         return InodeFactory.getChildrenClassByConditionAndOrderBy(i, File.class, condition, "file_name, sort_order");
81
82     }
83     
84     public static java.util.List JavaDoc getFileChildrenByConditionAndOrder(Inode i, String JavaDoc condition,String JavaDoc order) {
85
86         return InodeFactory.getChildrenClassByConditionAndOrderBy(i, File.class, condition, order);
87
88     }
89
90     public static java.util.List JavaDoc getFileChildren(Inode i) {
91
92         return InodeFactory.getChildrenClassByOrder(i, File.class, "inode, sort_order");
93
94     }
95
96     public static boolean existsFileName(Inode parent, String JavaDoc fileName) {
97
98         Logger.debug(FileFactory.class, "UtilMethods.sqlify(fileName)" + UtilMethods.sqlify(fileName));
99         File f = (File) InodeFactory.getChildOfClassbyCondition(parent, File.class, "file_name = '"
100                 + UtilMethods.sqlify(fileName) + "'");
101
102         return (f.getInode() > 0);
103     }
104
105     public static File getFileByURI(String JavaDoc uri, Host host, boolean live) {
106         return getFileByURI(uri, host.getInode(), live);
107     }
108
109     public static File getFileByURI(String JavaDoc uri, long hostId, boolean live) {
110
111         uri = uri.replaceAll(Config.getStringProperty("VIRTUAL_FILE_PREFIX"), "");
112         Logger.debug(FileFactory.class, "getFileByURI=" + uri);
113         Identifier i = IdentifierFactory.getIdentifierByURI(uri, hostId);
114         return getFileByIdentifier(i, live);
115
116     }
117
118     public static File getFileByIdentifier(Identifier i, boolean live) {
119
120         if (live) {
121             return (File) InodeFactory.getChildOfClassbyCondition(i, File.class, "live = "
122                     + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
123                     + com.dotmarketing.db.DbConnectionFactory.getDBFalse());
124
125         } else {
126             return (File) InodeFactory.getChildOfClassbyCondition(i, File.class, "working = "
127                     + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
128                     + com.dotmarketing.db.DbConnectionFactory.getDBFalse());
129
130         }
131
132     }
133
134     public static String JavaDoc getVirtualFileURI(File file) {
135
136         Identifier identifier = (Identifier) InodeFactory.getParentOfClass(file, Identifier.class);
137         if (identifier.getInode() > 0) {
138             return (Config.getStringProperty("VIRTUAL_FILE_PREFIX") + identifier.getURI()).intern();
139         }
140         return null;
141     }
142
143     public static String JavaDoc getVersionFileURI(File file) {
144
145         return Config.getStringProperty("VERSION_FILE_PREFIX") + file.getInode() + "."
146                 + UtilMethods.getFileExtension(file.getFileName()).intern();
147
148     }
149
150     public static String JavaDoc getRelativeAssetPath(Inode inode) {
151         String JavaDoc _inode = Long.toString(inode.getInode());
152         return getRelativeAssetPath(_inode, UtilMethods.getFileExtension(((com.dotmarketing.portlets.files.model.File) inode).getFileName())
153                             .intern());
154     }
155
156     public static String JavaDoc getRelativeAssetPath(String JavaDoc inode, String JavaDoc ext) {
157         String JavaDoc _inode = inode;
158         String JavaDoc path = "";
159
160         path = Config.getStringProperty("ASSET_PATH") + java.io.File.separator + _inode.charAt(0)
161                 + java.io.File.separator + _inode.charAt(1) + java.io.File.separator + _inode + "." + ext;
162
163         return path;
164     }
165
166     public static String JavaDoc getRealAssetPath(Inode inode) {
167         String JavaDoc _inode = Long.toString(inode.getInode());
168         return getRealAssetPath (_inode, UtilMethods.getFileExtension(((com.dotmarketing.portlets.files.model.File) inode).getFileName())
169                 .intern());
170     }
171
172     public static String JavaDoc getRealAssetPath(String JavaDoc inode, String JavaDoc ext) {
173         String JavaDoc _inode = inode;
174         String JavaDoc path = "";
175
176         String JavaDoc realPath = Config.getStringProperty("ASSET_REAL_PATH");
177         if (UtilMethods.isSet(realPath) && !realPath.endsWith(java.io.File.separator))
178             realPath = realPath + java.io.File.separator;
179
180         String JavaDoc assetPath = Config.getStringProperty("ASSET_PATH");
181         if (UtilMethods.isSet(assetPath) && !assetPath.endsWith(java.io.File.separator))
182             assetPath = assetPath + java.io.File.separator;
183         
184         path = ((!UtilMethods.isSet(realPath)) ? assetPath : realPath)
185                 + _inode.charAt(0) + java.io.File.separator + _inode.charAt(1)
186                 + java.io.File.separator + _inode + "." + ext;
187
188         if (!UtilMethods.isSet(realPath))
189             return Config.CONTEXT.getRealPath(path);
190         else
191             return path;
192     }
193
194     public static String JavaDoc getRelativeAssetsRootPath() {
195         String JavaDoc path = "";
196
197         path = Config.getStringProperty("ASSET_PATH");
198
199         return path;
200     }
201
202     public static String JavaDoc getRealAssetsRootPath() {
203         String JavaDoc realPath = Config.getStringProperty("ASSET_REAL_PATH");
204         if (UtilMethods.isSet(realPath) && !realPath.endsWith(java.io.File.separator))
205             realPath = realPath + java.io.File.separator;
206         if (!UtilMethods.isSet(realPath))
207             return Config.CONTEXT.getRealPath(getRelativeAssetsRootPath());
208         else
209             return realPath;
210     }
211
212     // remove the uri from a single cache
213
/*
214      * Never used methods
215      *
216      * private synchronized static void removeURI(Object key, java.util.Map map) {
217      * map.remove(key); }
218      *
219      * private static long howBigIsCache(java.util.Map map) {
220      *
221      * long size = 0;
222      *
223      * for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry
224      * me = (Map.Entry) it.next(); size += me.getKey().toString().length(); size +=
225      * me.getValue().toString().length(); } return size; }
226      */

227
228     public static java.util.List JavaDoc getFilesPerRoleAndCondition(Host host, Role[] roles, String JavaDoc condition) {
229         return getFilesPerRoleAndCondition(host.getInode(), roles, condition);
230     }
231
232     public static java.util.List JavaDoc getFilesPerRoleAndCondition(long hostId, Role[] roles, String JavaDoc condition) {
233         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
234         java.util.List JavaDoc folders = com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersByParent(hostId);
235         return com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersAndEntriesByRoles(folders, entries,
236                 roles, File.class, condition);
237     }
238
239     public static java.util.List JavaDoc getFilesPerRole(long hostId, Role[] roles) {
240         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
241         java.util.List JavaDoc folders = com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersByParent(hostId);
242         return com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersAndEntriesByRoles(folders, entries,
243                 roles, File.class);
244     }
245
246     public static java.util.List JavaDoc getFilesByCondition(String JavaDoc condition) {
247
248         DotHibernate dh = new DotHibernate(File.class);
249         dh.setQuery("from inode in class class com.dotmarketing.portlets.files.model.File where " + condition
250                 + " order by file_name, sort_order");
251         return dh.list();
252     }
253
254     public static java.util.List JavaDoc<PermissionAsset> getFilesAndPermissionsPerRoleAndCondition(Role[] roles,
255             String JavaDoc condition, int limit, int offset, String JavaDoc orderby) {
256
257         java.util.List JavaDoc<PermissionAsset> entries = new java.util.ArrayList JavaDoc<PermissionAsset>();
258         orderby = "file_asset." + orderby;
259         java.util.List JavaDoc elements = WebAssetFactory.getAssetsPerConditionWithPermission(condition, File.class, roles,
260                 limit, offset, orderby, 0);
261         java.util.Iterator JavaDoc elementsIter = elements.iterator();
262
263         while (elementsIter.hasNext()) {
264
265             File file = (File) elementsIter.next();
266             Folder folderParent = (Folder) InodeFactory.getParentOfClass(file, Folder.class);
267
268             java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(file, roles);
269
270             PermissionAsset permAsset = new PermissionAsset();
271             permAsset.setPathToMe(folderParent.getPath());
272             permAsset.setPermissions(permissions);
273             permAsset.setAsset(file);
274             entries.add(permAsset);
275         }
276
277         return entries;
278
279     }
280
281     public static java.util.List JavaDoc getFilesPerRoleAndParent(Role[] roles,
282             com.dotmarketing.portlets.folders.model.Folder folderParent) {
283
284         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
285         java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(folderParent, roles);
286         if (permissions.contains(Config.getStringProperty("PERMISSION_READ"))) {
287             // read permission
288
entries = InodeFactory.getChildrenClass(folderParent, File.class);
289         }
290         return entries;
291     }
292
293     public static java.util.List JavaDoc getFilesPerRoleParentAndCondition(Role[] roles,
294             com.dotmarketing.portlets.folders.model.Folder folderParent, String JavaDoc condition) {
295
296         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
297         java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(folderParent, roles);
298         if (permissions.contains(Config.getStringProperty("PERMISSION_READ"))) {
299             // read permission
300
entries = InodeFactory.getChildrenClassByCondition(folderParent, File.class, condition);
301         }
302         return entries;
303     }
304     
305     public static java.util.List JavaDoc getFilesByParentFolderPerRoleAndCondition(Role[] roles,
306             Folder folderParent, String JavaDoc condition) {
307
308         List JavaDoc<File> entries = new ArrayList JavaDoc();
309         
310         List JavaDoc<File> elements = InodeFactory.getChildrenClassByCondition(folderParent, File.class, condition);;
311         for(File file : elements){
312             List JavaDoc permissions = PermissionCache
313             .getPermissionIdsByRolesFromCache(file, roles);
314             
315             if (permissions.contains(Config
316                     .getStringProperty("PERMISSION_READ"))) {
317                 // read permission
318

319                 entries.add(file);
320             }
321         }
322         
323         return entries;
324     }
325
326     /**
327      * Move a file into the given directory
328      *
329      * @param file
330      * File to be moved
331      * @param parent
332      * Destination Folder
333      * @return true if move success, false otherwise
334      */

335     public static boolean moveFile(File file, Folder parent) {
336     
337         Identifier identifier = com.dotmarketing.factories.IdentifierFactory.getParentIdentifier(file);
338
339         // gets working container
340
File workingWebAsset = (File) IdentifierFactory.getWorkingChildOfClass(identifier, File.class);
341         // gets live container
342
File liveWebAsset = (File) IdentifierFactory.getLiveChildOfClass(identifier, File.class);
343
344         // checks if another identifer with the same name exists in the same
345
// folder
346
if (FileFactory.existsFileName(parent, file.getFileName())) {
347             return false;
348         }
349
350         // assets cache
351
if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
352             LiveCache.removeAssetFromCache(liveWebAsset);
353         }
354         WorkingCache.removeAssetFromCache(workingWebAsset);
355
356         // gets old parent
357
Folder oldParent = (Folder) InodeFactory.getParentOfClass(workingWebAsset, Folder.class);
358
359         oldParent.deleteChild(workingWebAsset);
360         if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
361             oldParent.deleteChild(liveWebAsset);
362         }
363         //add new Parent
364
parent.addChild(workingWebAsset);
365         if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
366             parent.addChild(liveWebAsset);
367         }
368
369         // gets identifier for this webasset and changes the uri and
370
// persists it
371
Host newHost = HostFactory.getParentHost(parent);
372         identifier.setHostInode(newHost.getInode());
373         identifier.setURI(workingWebAsset.getURI(parent));
374         InodeFactory.saveInode(identifier);
375
376         // Add to Preview and Live Cache
377
if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
378             LiveCache.addToLiveAssetToCache(liveWebAsset);
379         }
380         WorkingCache.addToWorkingAssetToCache(workingWebAsset);
381
382         if (file.isShowOnMenu()) {
383             //existing folder with different show on menu ... need to regenerate menu
384
RefreshMenus.deleteMenus();
385         }
386         
387         return true;
388     
389     }
390     
391     /**
392      * Copy a file into the given directory
393      *
394      * @param file
395      * File to be copied
396      * @param parent
397      * Destination Folder
398      * @return true if copy success, false otherwise
399      */

400     public static File copyFile(File file, Folder parent) {
401
402         File newFile = new File();
403         try {
404
405             newFile.copy(file);
406             newFile.setLocked(false);
407             newFile.setLive(false);
408             newFile.setFriendlyName(file.getFriendlyName() + " (COPY) ");
409
410             // gets filename before extension
411
String JavaDoc fileName = com.dotmarketing.util.UtilMethods.getFileName(file.getFileName());
412             // gets file extension
413
String JavaDoc fileExtension = com.dotmarketing.util.UtilMethods.getFileExtension(file.getFileName());
414
415             // Setting file name
416
if (FileFactory.existsFileName(parent, file.getFileName())) {
417                 // adds "copy" word to the filename
418
newFile.setFileName(fileName + "_copy." + fileExtension);
419             } else {
420                 newFile.setFileName(fileName + "." + fileExtension);
421             }
422
423             // persists the webasset
424
InodeFactory.saveInode(newFile);
425
426             // ////BEGINS SAVING FILE CONTENTS TO NEW FILE
427
// gets the real path to the assets directory
428
String JavaDoc filePath = getRealAssetsRootPath();
429             // creates the path where to save this file based on the inode
430
String JavaDoc fileInodePath = String.valueOf(newFile.getInode());
431             if (fileInodePath.length() == 1) {
432                 fileInodePath = fileInodePath + "0";
433             }
434             // creates the path with inode{1} + inode{2}
435
fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2);
436             // creates directory for first level directory in case it doesn't
437
// exist
438
new java.io.File JavaDoc(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir();
439             // creates directory for second level directory in case it doesn't
440
// exist
441
new java.io.File JavaDoc(filePath + java.io.File.separator + fileInodePath).mkdir();
442
443             // creates the new file as inode{1}/inode{2}/inode.file_extension
444
java.io.File JavaDoc newF = new java.io.File JavaDoc(filePath + java.io.File.separator + fileInodePath
445                     + java.io.File.separator + newFile.getInode() + "." + fileExtension);
446
447             fileInodePath = String.valueOf(file.getInode());
448             if (fileInodePath.length() == 1) {
449                 fileInodePath = fileInodePath + "0";
450             }
451             // creates the path with inode{1} + inode{2}
452
fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2);
453             // creates the current file as
454
// inode{1}/inode{2}/inode.file_extension
455
java.io.File JavaDoc currF = new java.io.File JavaDoc(filePath + java.io.File.separator + fileInodePath
456                     + java.io.File.separator + file.getInode() + "." + fileExtension);
457
458             // gets outputstream from the file
459
java.io.FileOutputStream JavaDoc fout = new java.io.FileOutputStream JavaDoc(newF);
460             // gets buffered outputstrem to write the data in the file
461
java.io.BufferedOutputStream JavaDoc bout = new java.io.BufferedOutputStream JavaDoc(fout);
462             // gets input stream from the data from the uploaded file
463
java.io.FileInputStream JavaDoc is = new java.io.FileInputStream JavaDoc(currF);
464             // gets bufferedinput stream to read data
465
java.io.BufferedInputStream JavaDoc bin = new java.io.BufferedInputStream JavaDoc(is);
466
467             int bytedata;
468             // writes all data from input in output
469
while ((bytedata = bin.read()) != -1) {
470                 bout.write(bytedata);
471             }
472             // closes all streams
473
bout.flush();
474             bout.close();
475             bin.close();
476
477             // ////ENDS SAVING FILE CONTENTS TO NEW FILE
478

479             // Adding to the parent folder
480
parent.addChild(newFile);
481
482             // creates new identifier for this webasset and persists it
483
Identifier newIdentifier = IdentifierFactory.createNewIdentifier(newFile, parent);
484
485             Logger.debug(FileFactory.class, "identifier=" + newIdentifier.getURI());
486
487             WorkingCache.addToWorkingAssetToCache(newFile);
488             LiveCache.addToLiveAssetToCache(newFile);
489
490             // Copy permissions
491
PermissionFactory.copyPermissions(file, newFile);
492         } catch (IOException JavaDoc e) {
493             throw new DotRuntimeException("An error ocurred trying to copy the file.", e);
494         }
495         return newFile;
496
497
498     }
499
500     public static boolean renameFile (File file, String JavaDoc newName, User user) throws Exception JavaDoc {
501
502         // Checking permissions
503
if (!PermissionFactory.doesUserHavePermission(file, Config.getIntProperty("PERMISSION_WRITE"), user))
504             throw new ActionException(WebKeys.USER_PERMISSIONS_EXCEPTION);
505
506         //getting old file properties
507
String JavaDoc oldFileName = file.getFileName();
508         String JavaDoc ext = UtilMethods.getFileExtension(oldFileName);
509         Folder folder = (Folder)InodeFactory.getParentOfClass(file, Folder.class);
510
511         Identifier ident = IdentifierFactory.getIdentifierByInode(file);
512
513         String JavaDoc newFileName = newName + "." + ext;
514
515         if(FileFactory.existsFileName(folder, newFileName) || file.isLocked())
516             return false;
517
518         List JavaDoc<File> versions = IdentifierFactory.getVersionsandLiveandWorkingChildrenOfClass(ident, File.class);
519         
520         for (File f : versions) {
521
522             // sets filename for this new file
523
f.setFileName(newFileName);
524             f.setFriendlyName(newFileName);
525
526             if (f.isLive())
527                 LiveCache.addToLiveAssetToCache(f);
528             if (f.isWorking())
529                 WorkingCache.addToWorkingAssetToCache(f);
530                 
531             InodeFactory.saveInode(f);
532
533         }
534         
535         ident.setURI(file.getURI(folder));
536         InodeFactory.saveInode(ident);
537         
538         RefreshMenus.deleteMenus();
539
540         return true;
541
542     }
543 }
544
Popular Tags