KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > filemanager > Filemanager_Engine


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 //
14
// Filemanger_Engine
15
// NK 10.02.2001
16
//
17
//
18

19 package org.jahia.engines.filemanager;
20
21 import java.io.IOException JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Vector JavaDoc;
24
25 import javax.servlet.ServletException JavaDoc;
26 import javax.servlet.http.HttpSession JavaDoc;
27
28 import org.jahia.data.JahiaData;
29 import org.jahia.data.fields.JahiaField;
30 import org.jahia.data.files.JahiaFile;
31 import org.jahia.data.files.JahiaFileField;
32 import org.jahia.engines.EngineToolBox;
33 import org.jahia.engines.JahiaEngine;
34 import org.jahia.exceptions.JahiaException;
35 import org.jahia.exceptions.JahiaSessionExpirationException;
36 import org.jahia.params.ParamBean;
37 import org.jahia.registries.ServicesRegistry;
38 import org.jahia.services.fields.ContentFileField;
39 import org.jahia.services.filemanager.Folder;
40 import org.jahia.services.filemanager.JahiaFileFieldsManager;
41 import org.jahia.tools.files.FileUpload;
42 import org.jahia.utils.JahiaTools;
43
44
45 /**
46  * Handle file upload, download, virtual folder structure
47  *
48  * @author Khue ng
49  * @version 1.0
50  */

51 public class Filemanager_Engine implements JahiaEngine {
52
53     public static final String JavaDoc ENGINE_NAME = "filemanager";
54
55     private static final org.apache.log4j.Logger logger =
56             org.apache.log4j.Logger.getLogger (Filemanager_Engine.class);
57
58     private static Filemanager_Engine instance = null;
59
60     private EngineToolBox toolBox;
61
62     private static final String JavaDoc TEMPLATE_JSP = "filemanager";
63     private static final String JavaDoc FILEUPLOAD_JSP = "filemanager_fileupload";
64     private static final String JavaDoc FILEDELETE_JSP = "filemanager_filedelete";
65     private static final String JavaDoc RELOADPAGE_JSP = "filemanager_reloadpage";
66     private static final String JavaDoc ERROR_JSP = "filemanager_error";
67     private static final String JavaDoc CLOSE_JSP = "filemanager_close";
68
69     /** The requested action * */
70     private final String JavaDoc ACTION_REQ = "actionreq";
71     private final String JavaDoc SUB_ACTION = "subAction";
72
73     private final String JavaDoc ACTION_FM_CREATE = "actionFilemanagerCreate";
74     private final String JavaDoc ACTION_FOLDER_OPEN = "actionFolderOpen";
75     private final String JavaDoc ACTION_FILE_UPLOAD = "actionFileUpload";
76     private final String JavaDoc ACTION_FILE_DOWNLOAD = "actionFileDownload";
77     private final String JavaDoc ACTION_FILE_DELETE = "actionFileDelete";
78     private final String JavaDoc ACTION_FILE_MOVE = "actionFileMove";
79     private final String JavaDoc ACTION_FILE_EDIT = "actionFileEdit";
80     private final String JavaDoc ACTION_FILE_EDITSAVE = "actionFileEditSave";
81     private final String JavaDoc ACTION_FILE_COPY = "actionFileCopy";
82     private final String JavaDoc ACTION_FOLDER_CREATE = "actionFolderCreate";
83     private final String JavaDoc ACTION_FOLDER_DELETE = "actionFolderDelete";
84     private final String JavaDoc ACTION_FOLDER_MOVE = "actionFolderMove";
85     private final String JavaDoc ACTION_FOLDER_RENAME = "actionFolderRename";
86
87     /** form parameter name for folder id * */
88     private final String JavaDoc FORM_FOLDERID = "active_folder_id";
89     /** form parameter name for new folder name * */
90     private final String JavaDoc FORM_NEWFOLDERNAME = "foldername";
91     /** form parameter name for files list * */
92     private final String JavaDoc FORM_FILESLIST = "filesList";
93     /** form parameter name for a file item * */
94     private final String JavaDoc FORM_FILE_ITEM = "fileItem";
95     /** form parameter file url * */
96     private final String JavaDoc FORM_FILE_FILENAME = "filename";
97     /** form parameter file title * */
98     private final String JavaDoc FORM_FILE_TITLE = "fileTitle";
99     /** form parameter file edit action * */
100     private final String JavaDoc FORM_FILE_EDIT_ACTION = "editAction";
101     /** form parameter file move action * */
102     private final String JavaDoc FORM_FILE_MOVE_ACTION = "moveAction";
103     /** form parameter folder sub action * */
104     private final String JavaDoc FORM_FOLDER_SUB_ACTION = "subAction";
105     /** form parameter folder move action * */
106     private final String JavaDoc FORM_FOLDER_MOVE_ACTION = "moveAction";
107     /** form parameter name for file move destination folder * */
108     private final String JavaDoc FORM_FILE_MOVE_DESTINATION_FOLDER = "fileMoveDestinationFolder";
109     /** form parameter name for folder move destination folder * */
110     private final String JavaDoc FORM_FOLDER_MOVE_DESTINATION_FOLDER = "folderMoveDestinationFolder";
111
112     /** display all folder's children * */
113     private final String JavaDoc DEPLOY_ALL_BRANCH = "allBranch";
114
115     /** display only children folders for active folder branch * */
116     private final String JavaDoc DEPLOY_ONLY_ONE_BRANCH = " oneBranch";
117
118
119     /**
120      * constructor
121      */

122     protected Filemanager_Engine () {
123         logger.info (
124                 "***** Starting " + Filemanager_Engine.class.getName () + " engine *****");
125         toolBox = EngineToolBox.getInstance ();
126     }
127
128
129     /**
130      * returns a single instance of the object
131      */

132     public static synchronized Filemanager_Engine getInstance () {
133         if (instance == null) {
134             instance = new Filemanager_Engine ();
135         }
136         return instance;
137     }
138
139
140     /**
141      * authoriseRender
142      */

143     public boolean authoriseRender (ParamBean jParams) {
144         return toolBox.authoriseRender (jParams);
145     }
146
147
148     /**
149      * renderLink
150      */

151     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
152             throws JahiaException {
153
154 // String params = "&mode=display";
155
String JavaDoc params = "?mode=display";
156
157         Vector JavaDoc datas = (Vector JavaDoc) theObj;
158         if (datas != null) {
159
160             String JavaDoc action = (String JavaDoc) datas.get (0);
161
162             if (action != null && (action.length () > 0)) {
163
164                 if (action.equals ("actionFileDownload")) {
165
166                     params = EMPTY_STRING;
167                     //logger.debug (" action is fileDownload");
168

169                     JahiaField theField = (JahiaField) datas.get (1);
170
171                     if (theField != null) {
172
173                         JahiaFileField fField = (JahiaFileField) theField.getObject ();
174                         if (fField != null) {
175                             int fileID = fField.getFileID ();
176                             JahiaFile f = ServicesRegistry.getInstance ()
177                                     .getJahiaFilemanagerService ()
178                                     .getFileDB (fileID, fField.getVersion ());
179                             if (f != null) {
180                                 String JavaDoc escapedFileName = java.net.URLEncoder.encode (
181                                         f.getRealName ());
182                                 // this next line is an ugly hack required because
183
// of the evolution of the use of RFC 1738 to
184
// encoding spaces with %20.
185
escapedFileName = JahiaTools.replacePattern (escapedFileName,
186                                         "+", "%20");
187
188                                 if (jParams.getEntryLoadRequest ().isVersioned ()) {
189                                     params = "/" + ParamBean.ENTRY_STATE_PARAMETER + "/"
190                                             + jParams.getEntryLoadRequest ().getVersionID ();
191                                 }
192                                 params = "/" + escapedFileName + params;
193                                 action += "&fid=" + theField.getID ();
194                             } else {
195                                 action = EMPTY_STRING;
196                             }
197                         } else {
198                             action = EMPTY_STRING;
199                         }
200                     }
201                 }
202
203                 if (action != null & action.length () > 0) {
204                     params += "?" + ACTION_REQ + "=" + action;
205                 }
206             }
207         }
208
209
210         String JavaDoc theUrl = EMPTY_STRING;
211         if (jParams != null) {
212             theUrl = jParams.composeEngineUrl (ENGINE_NAME, params);
213         }
214
215         return theUrl;
216
217     }
218
219
220     /**
221      * needsJahiaData
222      */

223     public boolean needsJahiaData (ParamBean jParams) {
224         return false;
225     }
226
227
228     /**
229      * handdles the engine actions
230      *
231      * @param jParams a ParamBean object
232      * @param jData a JahiaData object (not mandatory)
233      */

234     public void handleActions (ParamBean jParams, JahiaData jData)
235             throws JahiaException {
236
237         HashMap JavaDoc engineMap = initEngineMap (jParams);
238         boolean displayScreen = true;
239
240         String JavaDoc action = jParams.getParameter (ACTION_REQ);
241         //logger.debug ("actionreq= " + action);
242
if (action != null) {
243
244             if (action.equals (ACTION_FILE_UPLOAD)) {
245                 handleFileUpload (jParams, engineMap);
246             } else if (action.equals (ACTION_FILE_DOWNLOAD)) {
247
248                 if (handleFileDownload (jParams, engineMap)) {
249                     displayScreen = false;
250                 }
251
252             } else if (action.equals (ACTION_FILE_DELETE)) {
253                 handleFileDelete (jParams, engineMap);
254             } else {
255                 // the files list for a gived page and all files made public
256
Vector JavaDoc v = ServicesRegistry.getInstance ()
257                         .getJahiaFilemanagerService ()
258                         .getFilesByPage (jParams.getSiteID (), jParams.getPageID (), true);
259
260                 Vector JavaDoc filesList = new Vector JavaDoc ();
261
262                 if (jParams.getUser ().isAdminMember (jParams.getSiteID ())) {
263                     filesList = v;
264                 } else {
265                     int size = v.size ();
266                     JahiaFile jf = null;
267                     for (int i = 0; i < size; i++) {
268                         jf = (JahiaFile) v.get (i);
269                         if (jf.getUploadUser ().equals (jParams.getUser ().getName ())) {
270                             filesList.add (jf);
271                         }
272                     }
273                 }
274                 engineMap.put ("filesList", filesList.elements ());
275
276                 // undefined action
277
engineMap.put ("fmMsg", EMPTY_STRING);
278                 engineMap.put ("jspSource", TEMPLATE_JSP);
279
280             }
281         } else {
282
283             engineMap.put ("fmMsg", "An error occured while processing file download");
284             engineMap.put ("jspSource", RELOADPAGE_JSP);
285
286         }
287
288         JahiaField theField = (JahiaField) engineMap.get ("theField");
289         if (theField != null) {
290             engineMap.put ("fieldID", new Integer JavaDoc (theField.getID ()));
291         } else {
292             // logger.debug ("Couldn't retrieve field named <theField> from engineMap !");
293
}
294
295         if (displayScreen) {
296             // sets engineMap for JSPs
297
jParams.getRequest ().setAttribute ("engineTitle", "Filemanager");
298             jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap", engineMap);
299             // displays the screen
300
toolBox.displayScreen (jParams, engineMap);
301         }
302     }
303
304     /**
305      * Retrieve the engine name.
306      *
307      * @return the engine name.
308      */

309     public final String JavaDoc getName () {
310         return ENGINE_NAME; //To change body of implemented methods use Options | File Templates.
311
}
312
313
314     /**
315      * handle file upload
316      */

317     protected void handleFileUpload (ParamBean jParams,
318                                      HashMap JavaDoc engineMap) throws JahiaException {
319
320         FileUpload fupload = null;
321
322         if (ParamBean.isMultipartRequest (jParams.getRequest ())) {
323
324
325             try {
326                 fupload = ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
327                         .getFileUploadHandler (jParams.getContext (), jParams.getRequest ());
328             } catch (ServletException JavaDoc sex) {
329                 String JavaDoc errorMsg = "Error handling Multipart request : " + sex.getMessage () +
330                         " -> BAILING OUT";
331                 logger.error (errorMsg, sex);
332                 throw new JahiaException ("Error handling Multipart request",
333                         errorMsg, JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
334             } catch (IOException JavaDoc ioe) {
335                 String JavaDoc errorMsg = "Error handling Multipart request : " + ioe.getMessage () +
336                         " -> BAILING OUT";
337                 logger.error (errorMsg, ioe);
338                 throw new JahiaException ("Error handling Multipart request",
339                         errorMsg, JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
340             }
341
342             // Yes, it's a file upload -> specify the FileUpload Object
343
//jParams.specifyRequestObj (fupload);
344
}
345
346         String JavaDoc subAction = fupload.getParameter (SUB_ACTION);
347         if (subAction == null) {
348             // display file upload form
349
engineMap.put ("jspSource", FILEUPLOAD_JSP);
350         } else if (subAction.equals ("save")) {
351             // handle save file upload
352

353
354             // get the active Folder
355
String JavaDoc idStr = fupload.getParameter ("active_folder_id");
356             int folderID = 0;
357             if (idStr != null) {
358                 folderID = Integer.parseInt (idStr);
359             } else {
360
361                 String JavaDoc errorMsg = "Fail initializing active Folder : ";
362                 logger.error (errorMsg + " -> BAILING OUT");
363                 throw new JahiaException (errorMsg, errorMsg, JahiaException.SERVICE_ERROR,
364                         JahiaException.ERROR_SEVERITY);
365             }
366
367             Folder activeFolder = ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
368                     .getFolder (folderID);
369
370             if (activeFolder == null) {
371                 String JavaDoc errorMsg = "Fail initializing active Folder : ";
372                 logger.error (errorMsg + " -> BAILING OUT");
373                 throw new JahiaException (errorMsg, errorMsg, JahiaException.SERVICE_ERROR,
374                         JahiaException.ERROR_SEVERITY);
375             }
376
377             // get is public parameter
378
String JavaDoc strVal = fupload.getParameter ("is_public");
379             if (strVal == null) {
380                 strVal = "0";
381             }
382             int isPublic = Integer.parseInt (strVal);
383
384
385             // get file title
386
String JavaDoc fileTitle = fupload.getParameter ("file_title");
387             if (strVal == null) {
388                 fileTitle = EMPTY_STRING;
389             }
390
391             // get upload user
392
String JavaDoc uploadUser = jParams.getUser ().getName ();
393
394             int fileID = -1;
395
396             try {
397
398                 fileID = ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
399                         .handleFileUpload (jParams,
400                                 fupload,
401                                 activeFolder.getFolderID (),
402                                 fileTitle,
403                                 uploadUser,
404                                 isPublic);
405                 engineMap.put ("jspSource", CLOSE_JSP);
406
407
408             } catch (Throwable JavaDoc e) {
409                 engineMap.put ("fmMsg", "error occured with fileupload");
410                 engineMap.put ("jspSource", ERROR_JSP);
411             }
412
413
414             // active Folder
415
strVal = fupload.getParameter ("active_folder_id");
416             Integer JavaDoc activeFolderID = new Integer JavaDoc (strVal);
417             engineMap.put ("activeFolderID", activeFolderID);
418             engineMap.put ("fileID", new Integer JavaDoc (fileID));
419
420         }
421
422         Vector JavaDoc datas = new Vector JavaDoc ();
423         datas.add (ACTION_FILE_UPLOAD);
424         datas.add (null);
425         engineMap.put ("filemanagerUrl",
426                 Filemanager_Engine.getInstance ().renderLink (jParams, datas));
427
428     }
429
430
431     /**
432      * handle file download
433      */

434     protected boolean handleFileDownload (ParamBean jParams,
435                                           HashMap JavaDoc engineMap) throws JahiaException {
436
437         boolean success = false;
438
439         String JavaDoc strVal = jParams.getRequest ().getParameter ("fid");
440         if (strVal != null) {
441             int fieldID = Integer.parseInt (strVal);
442             JahiaField field = ServicesRegistry.getInstance ().getJahiaFieldService ()
443                     .loadField (
444                             fieldID, jParams);
445             int fileFieldID = -1;
446             try {
447                 ContentFileField contentFileField = (ContentFileField) ContentFileField.getField (
448                         fieldID);
449                 fileFieldID = Integer.parseInt (contentFileField.getValue (jParams));
450                 //fileFieldID = Integer.parseInt(field.getValue());
451
} catch (Throwable JavaDoc t) {
452                 // this can fail in the case of a default value.
453
}
454             if (field != null && field.checkReadAccess (jParams.getUser ())) {
455                 JahiaFileField fileField = JahiaFileFieldsManager.getInstance ()
456                         .getJahiaFileField (fileFieldID);
457                 if (fileField != null) {
458                     // get the file field associated with this file
459
if (!ServicesRegistry.getInstance ()
460                             .getJahiaFilemanagerService ()
461                             .handleFileDownload (jParams.getRequest (),
462                                     jParams.getRealResponse (), fileField.getFileID (),
463                                     fileField.getVersion ())) {
464
465                         engineMap.put ("fmMsg",
466                                 "An error occured while processing file download");
467                         engineMap.put ("jspSource", RELOADPAGE_JSP);
468                         success = false;
469                     }
470                 }
471             }
472             return true;
473         }
474         return success;
475     }
476
477
478     /**
479      * handle file delete
480      */

481     protected boolean handleFileDelete (ParamBean jParams,
482                                         HashMap JavaDoc engineMap) throws JahiaException {
483
484         boolean success = true;
485
486         //System.out.println("handleFileDelete started");
487

488         String JavaDoc strVal = jParams.getRequest ().getParameter (FORM_FILE_ITEM);
489         if (strVal != null) {
490             int fileID = Integer.parseInt (strVal);
491             JahiaFile f = ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
492                     .getFileDB (fileID);
493
494             if (f == null) {
495                 engineMap.put ("fmMsg", "File not found");
496                 engineMap.put ("jspSource", ERROR_JSP);
497             } else {
498
499                 // Check rights
500
boolean canDelete = jParams.getUser ().isAdminMember (jParams.getJahiaID ());
501                 if (!canDelete) {
502                     canDelete = (f.getUploadUser ().equals (jParams.getUser ().getName ()));
503                 }
504
505                 if (!canDelete) {
506                     throw new JahiaException (this.getClass ().getName () + ".handleFileDelete",
507                             "User has no right to delete the file",
508                             JahiaException.SECURITY_ERROR,
509                             JahiaException.ERROR_SEVERITY);
510                 }
511                 String JavaDoc subAction = jParams.getRequest ().getParameter (SUB_ACTION);
512                 if (subAction == null) {
513                     //System.out.println(" subaction not found");
514
engineMap.put ("fmMsg", "Comfirm you want to delete the file");
515                     engineMap.put ("fileItem", f);
516                     engineMap.put ("jspSource", FILEDELETE_JSP);
517                 } else if (subAction.equals ("delete")) {
518                     //System.out.println(" subaction is delete");
519
if (!ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
520                             .deleteFileDB (fileID)) {
521                         engineMap.put ("fmMsg", "An error occured while deleting the file");
522                         engineMap.put ("jspSource", ERROR_JSP);
523                         success = false;
524                     } else {
525                         // delete from disk
526
ServicesRegistry.getInstance ().getJahiaFilemanagerService ()
527                                 .deleteFile (
528                                         f);
529                         // actually, redisplay the file upload form, but in future display the filemanager
530
engineMap.put ("jspSource", CLOSE_JSP);
531                     }
532                 }
533             }
534         } else {
535             success = false;
536         }
537
538         Vector JavaDoc datas = new Vector JavaDoc ();
539         datas.add ("actionFileDelete");
540         datas.add (null);
541         engineMap.put ("filemanagerUrl", renderLink (jParams, datas));
542
543         //engineMap.put( "fileID", new Integer(-1) );
544

545         return success;
546     }
547
548
549     /**
550      * inits the engine map
551      *
552      * @param jParams a ParamBean object (with request and response)
553      *
554      * @return a HashMap object containing all the basic values needed by an engine
555      */

556     private HashMap JavaDoc initEngineMap (ParamBean jParams)
557             throws JahiaException,
558             JahiaSessionExpirationException {
559
560         //logger.debug ("started");
561
String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
562
563         // gets session values
564
//HttpSession theSession = jParams.getRequest().getSession( true );
565
HttpSession JavaDoc theSession = jParams.getSession ();
566
567         HashMap JavaDoc engineMap = null;
568
569         if (theScreen == null) {
570             theScreen = "edit";
571             engineMap = (HashMap JavaDoc) theSession.getAttribute ("jahia_session_engineMap");
572         }
573
574         if (engineMap == null) {
575             engineMap = new HashMap JavaDoc ();
576         }
577
578         // init engine map
579
engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
580         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
581         theSession.setAttribute ("jahia_session_engineMap", engineMap);
582
583         // init map
584
engineMap.put ("screen", theScreen);
585
586         return engineMap;
587     }
588
589 }
590
Popular Tags