KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > filemanager > JahiaFilemanagerBaseService


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
// JahiaFilemanagerBaseService
15
//
16
// NK 02.02.2001
17
//
18
//
19

20 package org.jahia.services.filemanager;
21
22 import org.jahia.data.JahiaDBDOMObject;
23 import org.jahia.data.JahiaDOMObject;
24 import org.jahia.data.fields.JahiaField;
25 import org.jahia.data.fields.LoadFlags;
26 import org.jahia.data.files.JahiaFile;
27 import org.jahia.data.files.JahiaFileField;
28 import org.jahia.exceptions.JahiaException;
29 import org.jahia.exceptions.JahiaInitializationException;
30 import org.jahia.params.ParamBean;
31 import org.jahia.registries.ServicesRegistry;
32 import org.jahia.services.sites.JahiaSite;
33 import org.jahia.services.usermanager.JahiaUser;
34 import org.jahia.settings.SettingsBean;
35 import org.jahia.tools.files.FileDownload;
36 import org.jahia.tools.files.FileUpload;
37 import org.jahia.utils.FileUtils;
38 import org.jahia.utils.JahiaChrono;
39 import org.jahia.utils.JahiaTools;
40 import org.jahia.utils.keygenerator.JahiaKeyGen;
41
42 import javax.servlet.ServletContext JavaDoc;
43 import javax.servlet.ServletException JavaDoc;
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.http.HttpServletResponse JavaDoc;
46 import java.io.*;
47 import java.sql.*;
48 import java.util.Enumeration JavaDoc;
49 import java.util.Properties JavaDoc;
50 import java.util.Vector JavaDoc;
51
52
53 /**
54  * Class JahiaFilemanagerBaseService
55  * Handle files stored on disk.
56  *
57  * @author Khue ng
58  * @version 1.0
59  */

60 public class JahiaFilemanagerBaseService extends JahiaFilemanagerService {
61
62     private static org.apache.log4j.Logger logger =
63             org.apache.log4j.Logger.getLogger (JahiaFilemanagerBaseService.class);
64
65     private static final String JavaDoc CLASS_NAME = JahiaFilemanagerBaseService.class.getName ();
66
67     private static JahiaFilemanagerBaseService m_instance = null;
68
69     /** debug flag * */
70     public static boolean m_DebugQuery = true;
71
72     /** the real path to the storage root directory * */
73     private static String JavaDoc m_FileRepositoryDiskpath = null;
74
75     /** the file max size for file upload * */
76     private static int m_FileUploadMaxSize = 50485760; // ~50MB
77

78     /** the Prefix Name to use when creating new Directory * */
79     private static String JavaDoc m_DIR_PREFIX_NAME = "JAHIAFM";
80
81     /** the Prefix Name to use when creating new temp Directory * */
82     private static String JavaDoc m_TMP_DIR_PREFIX_NAME = "TMP_JAHIAFM";
83
84     /** the default Jahia Filemanager owner id * */
85     private int m_DEFAULT_JAHIA_ID = 1; // FIXME load from properties file ?
86

87     /** the file repository attribute name in the properties file * */
88     public final static String JavaDoc PROP_FILE_REPOSITORY_ROOT_PATH = "files.repositoryRootPath";
89     /** the file max size for upload attribute name in the properties file * */
90     public final static String JavaDoc PROP_FILE_FILEUPLOAD_MAXSIZE = "files.fileUploadMaxSize";
91
92
93     /** the instance of FilemanagerDB * */
94     private FilemanagerDB m_FilemanagerDB;
95
96     /** the instance of FolderDB * */
97     private FolderDB m_FolderDB;
98
99     /** the mime types * */
100     private Properties JavaDoc m_MimeTypes;
101
102     /**
103      * Constructor
104      */

105     protected JahiaFilemanagerBaseService () {
106     }
107
108
109     /**
110      * Method getInstance
111      *
112      * @return a reference to the unique instance ofthis class
113      */

114     public static synchronized JahiaFilemanagerBaseService getInstance () {
115         if (m_instance == null) {
116             m_instance = new JahiaFilemanagerBaseService ();
117         }
118         return m_instance;
119     }
120
121
122     /**
123      * init
124      * NK 31.10.2000
125      * NK 18.11.2000 setting passed through parameters
126      *
127      * @param JahiaPrivateSettings jSettings
128      */

129     public void init (SettingsBean jSettings)
130             throws JahiaInitializationException {
131
132         m_FileRepositoryDiskpath = jSettings.getJahiaFileRepositoryDiskPath ();
133         m_FileUploadMaxSize = jSettings.getJahiaFileUploadMaxSize ();
134         m_MimeTypes = jSettings.getMimeTypes ();
135         if (m_MimeTypes == null)
136             m_MimeTypes = new Properties JavaDoc ();
137
138         // init file repository directory
139
File repositoryFile = new File (m_FileRepositoryDiskpath);
140         if (!repositoryFile.exists ()) {
141             repositoryFile.mkdirs ();
142             if (!repositoryFile.isDirectory ()) {
143                 logger.debug ("Error Creating repository Folder");
144                 throw new JahiaInitializationException (
145                         "Error Creating File Repository Directory");
146             }
147         }
148
149         m_FilemanagerDB = FilemanagerDB.getInstance ();
150         m_FolderDB = FolderDB.getInstance ();
151
152
153     } // end init
154

155
156
157     //--------------------------------------------------------------------------
158
//
159
// Jahia File Field Section
160
//
161
//--------------------------------------------------------------------------
162

163     /**
164      * @param int the siteID
165      * @param pageID
166      * @param publicFile
167      *
168      * @return Vector of available files
169      */

170     public Vector JavaDoc getFilesByPage (int siteID, int pageID, boolean publicFile) {
171
172         Filemanager fmng = getFilemanagerByOwner (siteID);
173
174         String JavaDoc sqlStr = null;
175
176         if (fmng != null) {
177
178             sqlStr = " where pageid_jahia_file=" + pageID;
179             if (publicFile) {
180                 sqlStr +=
181                         " or ( filemgrid_jahia_file=" + fmng.getFilemanagerID () + " and is_public_jahia_file=1 )";
182             }
183
184             sqlStr += " order by realname_jahia_file ";
185         }
186
187         return getFilesDB (sqlStr); // actually select all files
188
}
189
190     /**
191      * Change the field value with new file ID
192      *
193      * @param int fieldID
194      * @param int fileID
195      */

196     public void changeFile (int fieldID, int fileID)
197             throws JahiaException {
198
199         JahiaField fieldItem = ServicesRegistry.getInstance ().getJahiaFieldService ()
200                 .loadField (fieldID, LoadFlags.NOTHING);
201         Integer JavaDoc val = new Integer JavaDoc (fileID);
202         fieldItem.setValue (val.toString ());
203         // 0 for parentAclID in saveField, because field already exists
204
// -> field already has an aclID
205
// -> no need to create a new one
206
ServicesRegistry.getInstance ().getJahiaFieldService ().saveField (fieldItem, 0, null);
207
208     }
209
210
211
212     //--------------------------------------------------------------------------
213
//
214
// Disk Storage Section
215
//
216
//--------------------------------------------------------------------------
217

218
219     /**
220      * Get the File Repository Root Path
221      */

222     public String JavaDoc getFileRepositoryRootPath () {
223         return JahiaFilemanagerBaseService.m_FileRepositoryDiskpath;
224     }
225
226     /**
227      * Set the FileRepositoryRootPath
228      *
229      * @param path the FileRepositoryRootPath
230      */

231     protected void setFileRepositoryRootPath (String JavaDoc path) {
232         if (path.length () > 0) {
233             JahiaFilemanagerBaseService.m_FileRepositoryDiskpath = path;
234         }
235     }
236
237
238     /**
239      * Get the Dir Prefix Name
240      */

241     public String JavaDoc getDirPrefixName () {
242         return JahiaFilemanagerBaseService.m_DIR_PREFIX_NAME;
243     }
244
245     /**
246      * Set the Dir Prefix Name
247      *
248      * @param path the prefixName
249      */

250     public void setDirPrefixName (String JavaDoc prefixName) {
251         JahiaFilemanagerBaseService.m_DIR_PREFIX_NAME = prefixName;
252     }
253
254
255     /**
256      * Get the File Upload Max Size
257      */

258     public int getFileUploadMaxSize () {
259         return JahiaFilemanagerBaseService.m_FileUploadMaxSize;
260     }
261
262     /**
263      * Set the FileUploadMaxSize
264      *
265      * @param maxSize the file Upload Max Size
266      */

267     public void setFileUploadMaxSize (int maxSize) {
268         JahiaFilemanagerBaseService.m_FileUploadMaxSize = maxSize;
269     }
270
271
272     /**
273      * Create a new directory in the File Repository Root Directory<br>
274      * The Directory name is randomly generated
275      *
276      * @return the abstract File for the created directory else null on error
277      *
278      * @author Khue ng
279      */

280     public File createDirectory () {
281
282         File tmpFile = null;
283
284         File rootFile = new File (getFileRepositoryRootPath ());
285         if (rootFile != null && rootFile.isDirectory () && rootFile.canWrite ()) {
286             String JavaDoc dirName = getUniqueDirName ();
287             tmpFile =
288                     new File (
289                             getFileRepositoryRootPath () + File.separator + getDirPrefixName () + dirName);
290             tmpFile.mkdir ();
291         } else {
292             // error with root file repository
293
toConsole (
294                     "createDirectory, File repository Root Path is not accessible or doesn't exists");
295         }
296         return tmpFile;
297     }
298
299
300     /**
301      * Create a new directory in the File Repository Root Directory<br>
302      * The Directory name is the site key
303      *
304      * @param JahiaSite the site for which to create the file repository directory
305      *
306      * @return the abstract File for the created directory else null on error
307      *
308      * @author Khue ng
309      */

310     public File createDirectory (JahiaSite site) {
311
312         File tmpFile = null;
313
314         File rootFile = new File (getFileRepositoryRootPath ());
315         if (rootFile != null && rootFile.isDirectory () && rootFile.canWrite ()) {
316             String JavaDoc dirName = site.getSiteKey ();
317             tmpFile = new File (getFileRepositoryRootPath () + File.separator + dirName);
318             tmpFile.mkdir ();
319         } else {
320             // error with root file repository
321
toConsole (
322                     "createDirectory, File repository Root Path is not accessible or doesn't exists");
323         }
324         return tmpFile;
325     }
326
327
328     /**
329      * Create a new directory in the File Repository Root Directory<br>
330      *
331      * @param dirName The name of the directory to create
332      * @param overwrite if true overwrite existing directory with same name
333      *
334      * @return the abstract File for the created directory else null on error
335      */

336     public File createDirectory (String JavaDoc dirName, boolean overwrite) {
337
338         File tmpFile = null;
339
340         File rootFile = new File (getFileRepositoryRootPath ());
341         if (rootFile != null && rootFile.isDirectory () && rootFile.canWrite ()) {
342
343             tmpFile = new File (getFileRepositoryRootPath () + File.separator + dirName);
344
345             if (overwrite) {
346                 if ((tmpFile != null) && tmpFile.isDirectory () && tmpFile.canWrite ()) {
347                     tmpFile.delete (); // delete first
348
tmpFile.mkdir (); // recreate again
349
} else {
350                     tmpFile.mkdir (); // create new
351
}
352             } else if ((tmpFile == null) && !tmpFile.isDirectory ()) {
353                 tmpFile.mkdir (); // create new
354
}
355         } else {
356             // error with root file repository
357
toConsole (
358                     "createDirectory, File repository Root Path is not accessible or doesn't exists");
359         }
360         return tmpFile;
361     }
362
363
364     /**
365      * @throws ServletException
366      * @throws IOException
367      */

368     public File getRealFile (JahiaFile jahiaFile) {
369
370         if (jahiaFile != null) {
371
372             Filemanager fmng = getFilemanager (jahiaFile.getFilemanagerID ());
373
374             if (fmng != null) {
375                 String JavaDoc path = getFileRepositoryRootPath () + File.separator + fmng.getStoragePath () + File.separator + jahiaFile.getStorageName ();
376                 File f = new File (path);
377                 if (f.isFile ()) {
378                     return f;
379                 }
380             }
381         }
382         return null;
383     }
384
385     /**
386      * Handle file download
387      *
388      * @throws ServletException
389      * @throws IOException
390      */

391     public boolean handleFileDownload (
392             HttpServletRequest JavaDoc req,
393             HttpServletResponse JavaDoc res,
394             int fileID, String JavaDoc versionID
395             ) {
396         //logger.debug("started");
397
JahiaFile fileItem = (JahiaFile) ServicesRegistry.getInstance ()
398                 .getJahiaFilemanagerService ()
399                 .getFileDB (fileID, versionID);
400
401         if (fileItem != null) {
402
403             Filemanager fmng = getFilemanager (fileItem.getFilemanagerID ());
404
405             if (fmng != null) {
406                 String JavaDoc path = getFileRepositoryRootPath () + File.separator + fmng.getStoragePath () + File.separator + fileItem.getStorageName ();
407                 //logger.debug("file is " + path);
408

409                 File f = new File (path);
410                 String JavaDoc mimeType = "";
411                 if (f != null && f.isFile ()) {
412                     try {
413                         //logger.debug("file is " + path);
414

415                         JahiaChrono chrono = JahiaChrono.getInstance ();
416                         long startTime = chrono.start ();
417                         // logger.debug("Start time "+startTime);
418
FileDownload fdwn = null;
419
420                         mimeType = getMimeTypeFromFilename (fileItem.getRealName ());
421                         if (mimeType == null || mimeType.trim ().equals (""))
422                             mimeType = fileItem.getType ();
423
424                         logger.debug ("Mime type= " + mimeType);
425
426                         fdwn =
427                                 new FileDownload (req, res, fileItem.getRealName (), path,
428                                         mimeType);
429
430                         chrono.toConsole (startTime,
431                                 "JahiaFileManagerBaseService.handleFileDownload> FileDownload serving time");
432                         // logger.debug("Stop time "+chrono.start());
433
fdwn.writeFileContentToResponse ();
434                     } catch (IOException ioe) {
435                         logger.error ("Exception :", ioe);
436                         return false;
437                     }
438                 } else {
439                     return false;
440                 }
441             } else {
442                 return false;
443             }
444         } else {
445             return false;
446         }
447
448         return true;
449     }
450
451     /**
452      * return a FileUpload Handler object
453      * * Files uploaded are stored in a temporary directory with a random generated name
454      *
455      * @param context ServletContext
456      * @param req HttpServletRequest
457      *
458      * @return a FileUpload object or null
459      *
460      * @throws ServletException
461      * @throws IOException
462      */

463     public FileUpload getFileUploadHandler (
464             ServletContext JavaDoc context,
465             HttpServletRequest JavaDoc req
466             ) throws ServletException JavaDoc, IOException {
467         toConsole (" getFileUploadHandler started ");
468
469         FileUpload fupload = null;
470
471         File tmpDir = createTmpDirectory ();
472         if (tmpDir != null && tmpDir.isDirectory () && tmpDir.canWrite ()) {
473
474             fupload =
475                     new FileUpload (context, req,
476                             m_FileRepositoryDiskpath + File.separator + tmpDir.getName (),
477                             m_FileUploadMaxSize);
478             return fupload;
479         } else {
480             toConsole (" Error occured while creating temporaty directory");
481             throw new IOException (
482                     "ServicesRegistry.getInstance().getJahiaFileStorageService()::getFileUploadHandler fail creating temporary folder");
483         }
484     }
485
486
487     /**
488      * Handle file upload of new files, save them in the filemanager assotiated with
489      * the current JahiaID
490      *
491      * @return the id of the new file or -1 on error
492      *
493      * @throws ServletException
494      * @throws IOException
495      */

496     public int handleFileUpload (
497             ParamBean jParams,
498             FileUpload fupload,
499             int folderID,
500             String JavaDoc fileTitle,
501             String JavaDoc uploadUser,
502             int isPublic
503
504             ) throws ServletException JavaDoc, IOException, JahiaException {
505         toConsole (" handleFileUpload started ");
506
507         int fileID = -1;
508         int pageID = jParams.getPageID ();
509
510         // init filemanager
511
Filemanager fmng = getFilemanagerByOwner (jParams.getJahiaID ());
512
513         if (fmng == null) {
514             String JavaDoc errorMsg = "Fail initializing the requested filemanager : ";
515             logger.debug (errorMsg);
516             throw new JahiaException (errorMsg, errorMsg, JahiaException.SERVICE_ERROR,
517                     JahiaException.ERROR_SEVERITY);
518         }
519
520
521         if (fupload != null) {
522
523
524             // get files name
525
Enumeration JavaDoc filesName = fupload.getFileNames ();
526
527             String JavaDoc name;
528             String JavaDoc filename;
529             String JavaDoc contentType;
530             String JavaDoc storageName;
531             long size;
532             long lastModified;
533             JahiaFile aFile;
534             int nbError = 0;
535
536             File parent = null;
537
538             while (filesName.hasMoreElements ()) {
539
540                 name = (String JavaDoc) filesName.nextElement ();
541                 filename = fupload.getFileSystemName (name);
542                 //contentType = fupload.getFileContentType(name);
543

544                 contentType = getMimeTypeFromFilename (name);
545                 if (contentType == null || contentType.trim ().equals (""))
546                     contentType = fupload.getFileContentType (name);
547
548                 File f = fupload.getFile (name);
549                 if (f != null && f.exists () && f.canWrite ()) {
550
551                     // get parent folder
552
if (parent == null) {
553                         parent = f.getParentFile ();
554                     }
555
556                     size = f.length ();
557                     lastModified = f.lastModified ();
558                     storageName = "FILE" + JahiaKeyGen.getKey (10) + filename;
559                     String JavaDoc fullFilePath = getFileRepositoryRootPath () + File.separator + fmng.getStoragePath () + File.separator + storageName;
560                     toConsole (" New StoragePath = " + fullFilePath);
561                     File tmpFile = new File (fullFilePath);
562                     f.renameTo (tmpFile);
563
564
565                     aFile = new JahiaFile (fmng.getFilemanagerID (),
566                             folderID,
567                             uploadUser,
568                             filename,
569                             storageName,
570                             lastModified,
571                             size,
572                             contentType,
573                             fileTitle,
574                             "",
575                             String.valueOf (ServicesRegistry.getInstance ()
576                             .getJahiaVersionService ().getCurrentVersionID ()), // version
577
JahiaFile.STATE_ACTIVE);
578
579                     aFile.setPageID (pageID);
580                     aFile.setPublic (isPublic);
581
582                     toConsole (
583                             " file name :" + aFile.getRealName () + ",size=" + aFile.getSize () + ",lastModified=" + aFile.getLastModifDate () + ",type=" + aFile.getType ());
584
585                     fileID = insertFileDB (aFile);
586                     if ((fileID < 0)) {
587                         toConsole (" fail inserting file to db");
588                         f.delete ();
589                         nbError += 1;
590                     }
591                 } else {
592                     nbError += 1;
593                 }
594             }
595
596             if (parent != null) {
597                 parent.delete ();
598             }
599         }
600
601         return fileID;
602     }
603
604     /**
605      * Create a copy a a JahiaFile
606      *
607      * @return the id of the new file or -1 on error
608      *
609      * @throws ServletException
610      * @throws IOException
611      */

612     public int copyJahiaFile (JahiaFile jahiaFile,
613                               ParamBean jParams,
614                               String JavaDoc fileTitle,
615                               int isPublic,
616                               String JavaDoc filePrefixName
617                               ) throws ServletException JavaDoc, IOException, JahiaException {
618
619         int fileID = -1;
620
621         // init filemanager
622
Filemanager fmng = getFilemanagerByOwner (jahiaFile.getFilemanagerID ());
623
624         if (fmng == null) {
625             String JavaDoc errorMsg = "Fail initializing the requested filemanager : ";
626             logger.debug (errorMsg + " -> BAILING OUT");
627             throw new JahiaException (errorMsg, errorMsg, JahiaException.SERVICE_ERROR,
628                     JahiaException.ERROR_SEVERITY);
629         }
630
631         File f = new File (getFileRepositoryRootPath ()
632                 + File.separator
633                 + fmng.getStoragePath ()
634                 + File.separator
635                 + jahiaFile.getStorageName ());
636
637         String JavaDoc storageName = filePrefixName + "FILE" + JahiaKeyGen.getKey (10) + jahiaFile.getRealName ();
638         String JavaDoc fullFilePath = getFileRepositoryRootPath ()
639                 + File.separator
640                 + fmng.getStoragePath ()
641                 + File.separator
642                 + storageName;
643         File newf = new File (fullFilePath);
644         if (!newf.exists ()) {
645             newf.createNewFile ();
646             newf = null;
647         }
648         try {
649             FileUtils.getInstance ().copyFile (f.getAbsolutePath (), fullFilePath);
650             JahiaFile newFile = new JahiaFile (fmng.getFilemanagerID (),
651                     jahiaFile.getFolderID (),
652                     jahiaFile.getUploadUser (),
653                     jahiaFile.getRealName (),
654                     storageName,
655                     jahiaFile.getLastModifDate (),
656                     jahiaFile.getSize (),
657                     jahiaFile.getType (),
658                     fileTitle,
659                     jahiaFile.getDescr (),
660                     String.valueOf (ServicesRegistry.getInstance ()
661                     .getJahiaVersionService ().getCurrentVersionID ()), // version
662
JahiaFile.STATE_ACTIVE);
663
664             newFile.setPageID (jahiaFile.getPageID ());
665             newFile.setPublic (isPublic);
666
667             fileID = insertFileDB (newFile);
668
669         } catch (Throwable JavaDoc t) {
670         }
671
672         if ((fileID < 0)) {
673             toConsole (" fail inserting file to db");
674             f.delete ();
675         }
676         return fileID;
677     }
678
679     /**
680      * Delete a file from disk
681      *
682      * @param JahiaFile the abstract file
683      */

684     public boolean deleteFile (JahiaFile fileItem) {
685
686         Filemanager fmng = getFilemanager (fileItem.getFilemanagerID ());
687         if (fmng != null) {
688             StringBuffer JavaDoc buff = new StringBuffer JavaDoc (getFileRepositoryRootPath ());
689             buff.append (File.separator);
690             buff.append (fmng.getStoragePath ());
691             buff.append (File.separator);
692             buff.append (fileItem.getStorageName ());
693             File f = new File (buff.toString ());
694             return f.delete ();
695         }
696         return false;
697     }
698
699
700     /**
701      * Duplicate a file on disk
702      *
703      * @param in the source file
704      * @param out the copy abstract file object
705      *
706      * @return false on any exception
707      */

708     protected boolean copyFile (File in, File out) {
709
710         boolean success = false;
711         FileInputStream fis;
712         FileOutputStream fos;
713
714         try {
715             fis = new FileInputStream (in);
716             fos = new FileOutputStream (out);
717
718             byte[] buffer = new byte[1024];
719             int i = 0;
720             while ((i = fis.read (buffer)) != -1) {
721                 fos.write (buffer, 0, i);
722             }
723             success = true;
724             fis.close ();
725             fos.close ();
726         } catch (FileNotFoundException fnfex) {
727             toConsole (" copyFile, file not found :" + fnfex.getMessage ());
728         } catch (IOException ioe) {
729             toConsole (" copyFile, IOException :" + ioe.getMessage ());
730         } finally {
731             return success;
732         }
733     }
734
735
736     /**
737      * Method createTmpDirectory<br>
738      * Create a temporaty directory with a unique name which will be used
739      * to store temporarily uploaded files<br>
740      *
741      * @return the abstract File for the created directory else null on error
742      */

743     protected File createTmpDirectory () {
744
745         File tmpDir = null;
746
747         File rootFile = new File (getFileRepositoryRootPath ());
748         if (rootFile != null && rootFile.isDirectory () && rootFile.canWrite ()) {
749             String JavaDoc tmpDirName = m_TMP_DIR_PREFIX_NAME + getUniqueDirName ();
750             tmpDir = new File (getFileRepositoryRootPath () + File.separator + tmpDirName);
751             tmpDir.mkdir ();
752         } else {
753             // error with root file repository
754
toConsole (
755                     "createTmpDirectory, File repository path is not accessible or doesn't exists");
756         }
757         return tmpDir;
758     }
759
760
761     /**
762      * Method getUniqueFileName
763      * Return a random and unique String that can be
764      * used as storage name for file
765      *
766      * @return a unique string file name
767      */

768     protected String JavaDoc getUniqueFileName () {
769
770         return (JahiaKeyGen.getKey (10));
771     }
772
773
774     /**
775      * Method getUniqueDirName
776      * Return a random and unique String that can be used
777      * as directory name
778      *
779      * @return a unique directory name
780      */

781     protected String JavaDoc getUniqueDirName () {
782
783         return (JahiaKeyGen.getKey (15));
784     }
785
786
787
788
789     //--------------------------------------------------------------------------
790
//
791
//
792
// Jahia Filemanager DB Handling Section
793
//
794
//
795
//--------------------------------------------------------------------------
796

797     /**
798      * create a filemanager for a gived owner
799      */

800     public boolean createFilemanager (int ownerID) {
801
802         Filemanager fmng = new Filemanager ();
803         return fmng.create (ownerID);
804     }
805
806
807     /**
808      * Delete a filemanager and all its contents
809      */

810     public boolean deleteFilemanager (JahiaUser user, int ownerID)
811             throws JahiaException {
812
813         if (!user.isAdminMember (0)) {
814             throw new JahiaException ("JahiaFilemanagerBaseService.deleteFilemanager",
815                     "User has no right to delete the filemanager",
816                     JahiaException.ACL_ERROR,
817                     JahiaException.ERROR_SEVERITY);
818         }
819
820         Filemanager fmng = getFilemanagerByOwner (ownerID);
821         if (fmng == null) {
822             return false;
823         }
824
825         // delete the files
826
Folder rootFolder = fmng.getRootFolder ();
827         fmng.deleteFolder (rootFolder);
828
829         // delete the filemanager
830
return m_FilemanagerDB.delete (fmng.getFilemanagerID ());
831     }
832
833
834     /**
835      * Method getFilemanager<br>
836      * Return a filemanager
837      *
838      * @param filemanagerID the filemanager id
839      *
840      * @return filemanager or null
841      */

842     public Filemanager getFilemanager (int filemanagerID) {
843
844         Filemanager fmng = new Filemanager ();
845
846         if (!fmng.initialize (filemanagerID)) {
847             fmng = null;
848         }
849         return fmng;
850     }
851
852     /**
853      * Method getFilemanagerByOwner<br>
854      * Return a filemanager
855      *
856      * @param filemanagerID the filemanager id
857      *
858      * @return filemanager or null
859      */

860     public Filemanager getFilemanagerByOwner (int ownerID) {
861
862         Filemanager fmng = new Filemanager ();
863
864         if (!fmng.initializeWithOwner (ownerID)) {
865             fmng = null;
866         }
867         return fmng;
868     }
869
870
871
872
873
874     //--------------------------------------------------------------------------
875
//
876
//
877
// File DB Handling Section
878
//
879
//
880
//--------------------------------------------------------------------------
881

882
883     /**
884      * @param the file object to create
885      *
886      * @return the fileID or -1 on errors
887      */

888     public int insertFileDB (JahiaFileField aFile) throws JahiaException {
889         //System.out.println("insertFile(JahiaFileField)");
890

891         int fileID = insertFileDB ((JahiaFile) aFile);
892         if (fileID >= 0) {
893
894             Connection dbConn = null;
895             Statement stmt = null;
896
897             // update jahia file fields entries
898
JahiaFileFieldsManager.getInstance ().insertJahiaFileField (aFile);
899         }
900         return fileID;
901     }
902
903
904     /**
905      * Insert new row in jahia_filemgr_files table
906      *
907      * @param the file object to create
908      *
909      * @return the fileID of the new file or -1 on error
910      */

911     public int insertFileDB (JahiaFile aFile) throws JahiaException {
912         //System.out.println("insertFile(JahiaFile)");
913

914         int fileID = ServicesRegistry.getInstance ().getJahiaIncrementorsDBService ()
915                 .autoIncrement ("jahia_filemgr_files");
916         Connection dbConn = null;
917         Statement stmt = null;
918
919         try {
920             // get a connection to the db
921
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
922
923             // execute the query
924
String JavaDoc query = " insert into jahia_filemgr_files (id_jahia_file, filemgrid_jahia_file, fldid_jahia_file, uploaduser_jahia_file, pageid_jahia_file, is_public_jahia_file, realname_jahia_file, storagename_jahia_file, lastmodifdate_jahia_file, size_jahia_file, type_jahia_file, title_jahia_file, descr_jahia_file, version_jahia_file, state_jahia_file)" +
925                     " values(" +
926                     fileID + "," +
927                     aFile.getFilemanagerID () + "," +
928                     aFile.getFolderID () + "," +
929                     "'" + aFile.getUploadUser () + "'," +
930                     aFile.getPageID () + "," +
931                     aFile.getPublic () + "," +
932                     "'" + JahiaTools.quote (aFile.getRealName ()) + "'," +
933                     "'" + JahiaTools.quote (aFile.getStorageName ()) + "'," +
934                     (new Long JavaDoc (aFile.getLastModifDate ())).toString () + "," +
935                     (new Long JavaDoc (aFile.getSize ())).toString () + "," +
936                     "'" + JahiaTools.quote (aFile.getType ()) + "'," +
937                     "'" + JahiaTools.quote (aFile.getTitle ()) + "'," +
938                     "'" + JahiaTools.quote (aFile.getDescr ()) + "','" +
939                     aFile.getVersion () + "'," +
940                     aFile.getState () + ")";
941
942
943             stmt = dbConn.createStatement ();
944             debugQuery (query);
945             stmt.execute (query);
946             aFile.setFileID (fileID);
947         } catch (SQLException ex) {
948             processSQLException ("JahiaFilemanagerBaseService::insert()", ex);
949             fileID = -1;
950         } finally {
951             try {
952
953                 if (stmt != null) stmt.close ();
954             } catch (SQLException ex) {
955                 processSQLException (
956                         "JahiaFilemanagerBaseService:: insert() freeing connection fails", ex);
957             }
958         }
959
960         return fileID;
961     }
962
963
964     /**
965      * Update a row in jahia_filemgr_files table
966      *
967      * @param a file object
968      * @param oldVersion
969      *
970      * @return true if no exception occurs
971      */

972     public boolean updateFileDB (JahiaFile aFile, String JavaDoc oldVersion) {
973         boolean success = false;
974         Connection dbConn = null;
975         Statement stmt = null;
976
977         try {
978
979             // get a connection to the db
980
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
981
982             // execute the query
983
String JavaDoc query = " update jahia_filemgr_files set " +
984                     "filemgrid_jahia_file=" + aFile.getFilemanagerID () + "," +
985                     "fldid_jahia_file=" + aFile.getFolderID () + "," +
986                     "uploaduser_jahia_file='" + aFile.getUploadUser () + "'," +
987                     "pageid_jahia_file='" + aFile.getPageID () + "," +
988                     "is_public_jahia_file='" + aFile.getPublic () + "," +
989                     "realname_jahia_file='" + JahiaTools.quote (aFile.getRealName ()) + "'," +
990                     "storagename_jahia_file='" + JahiaTools.quote (aFile.getStorageName ()) + "'," +
991                     "lastmodifdate_jahia_file=" + (new Long JavaDoc (aFile.getLastModifDate ())).toString () + "," +
992                     "size_jahia_file=" + (new Long JavaDoc (aFile.getSize ())).toString () + "," +
993                     "type_jahia_file='" + JahiaTools.quote (aFile.getType ()) + "'," +
994                     "title_jahia_file='" + JahiaTools.quote (aFile.getTitle ()) + "'," +
995                     "descr_jahia_file='" + JahiaTools.quote (aFile.getDescr ()) + "'," +
996                     "version_jahia_file='" + aFile.getVersion () + "'," +
997                     "state_jahia_file=" + aFile.getState () +
998                     " where id_jahia_file=" + aFile.getFileID () +
999                     " and version_jahia_file='" + oldVersion + "'";
1000
1001            stmt = dbConn.createStatement ();
1002            debugQuery (query);
1003            stmt.executeUpdate (query);
1004            success = true;
1005        } catch (SQLException ex) {
1006            processSQLException ("JahiaFilemanagerBaseService::update()", ex);
1007        } finally {
1008            try {
1009                if (stmt != null) stmt.close ();
1010
1011            } catch (SQLException ex) {
1012                processSQLException (
1013                        "JahiaFilemanagerBaseService:: update() freeing connection fails", ex);
1014            }
1015        }
1016
1017        return success;
1018
1019    }
1020
1021    /**
1022     * Delete all row in jahia_filemgr_files table for a given file ID
1023     *
1024     * @param fileID
1025     *
1026     * @return false on any error else true
1027     */

1028    public boolean deleteFileDB (int fileID) {
1029        boolean success = false;
1030
1031        Connection dbConn = null;
1032        Statement stmt = null;
1033
1034        try {
1035
1036            // get a connection to the db
1037
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1038
1039            // execute the query
1040
String JavaDoc query = " delete from jahia_filemgr_files where id_jahia_file=" + fileID;
1041
1042            stmt = dbConn.createStatement ();
1043            debugQuery (query);
1044            stmt.execute (query);
1045            success = true;
1046        } catch (SQLException ex) {
1047            processSQLException ("JahiaFilemanagerBaseService::delete()", ex);
1048        } finally {
1049            try {
1050                if (stmt != null) stmt.close ();
1051
1052            } catch (SQLException ex) {
1053                processSQLException (
1054                        "JahiaFilemanagerBaseService:: delete() freeing connection fails", ex);
1055            }
1056        }
1057
1058        return success;
1059
1060    }
1061
1062    /**
1063     * Delete all row in jahia_filemgr_files table for a given file ID and a version
1064     *
1065     * @param fileID
1066     * @param version
1067     *
1068     * @return false on any error else true
1069     */

1070    public boolean deleteFileDB (int fileID, String JavaDoc version) {
1071        boolean success = false;
1072
1073        Connection dbConn = null;
1074        Statement stmt = null;
1075
1076        try {
1077
1078            // get a connection to the db
1079
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1080
1081            // execute the query
1082
String JavaDoc query = " delete from jahia_filemgr_files where id_jahia_file="
1083                    + fileID + " and version_jahia_file='" + version + "'";
1084
1085            stmt = dbConn.createStatement ();
1086            debugQuery (query);
1087            stmt.execute (query);
1088            success = true;
1089        } catch (SQLException ex) {
1090            processSQLException ("JahiaFilemanagerBaseService::delete(fileID, version)", ex);
1091        } finally {
1092            try {
1093                if (stmt != null) stmt.close ();
1094
1095            } catch (SQLException ex) {
1096                processSQLException (
1097                        "JahiaFilemanagerBaseService:: delete(fileID, version) freeing connection fails",
1098                        ex);
1099            }
1100        }
1101
1102        return success;
1103
1104    }
1105
1106    /**
1107     * delete all files in a gived folder
1108     *
1109     * @param folderID
1110     *
1111     * @return the false on error
1112     */

1113    public boolean deleteFilesDB (int folderID) throws JahiaException {
1114        boolean success = false;
1115        Connection dbConn = null;
1116        Statement stmt = null;
1117
1118        try {
1119
1120            // get a connection to the db
1121
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1122
1123            // execute the query
1124
String JavaDoc query = " delete from jahia_filemgr_files where fldid_jahia_file=" + folderID;
1125
1126            stmt = dbConn.createStatement ();
1127            debugQuery (query);
1128            stmt.executeUpdate (query);
1129            success = true;
1130        } catch (SQLException ex) {
1131            processSQLException ("FolderDB::executeQuery()", ex);
1132        } finally {
1133            try {
1134
1135                if (stmt != null) stmt.close ();
1136            } catch (SQLException ex) {
1137                processSQLException ("FolderDB:: executeQuery() freeing connection fails", ex);
1138            }
1139        }
1140
1141        return success;
1142    }
1143
1144    /**
1145     * Method getFile
1146     * Return a file object looking at it's id and state = 1 ( active )
1147     *
1148     * @param file id
1149     *
1150     * @return a file object else null
1151     */

1152    public JahiaFile getFileDB (int fileID) {
1153        return getFileDB (fileID, "0");
1154
1155    }
1156
1157
1158    /**
1159     * Method getFile
1160     * Return a file object looking at it's id and state = 1 ( active )
1161     *
1162     * @param file id
1163     *
1164     * @return a file object else null
1165     */

1166    public JahiaFile getFileDB (int fileID, String JavaDoc versionID) {
1167
1168        JahiaFile aFile = null;
1169        Connection dbConn = null;
1170        PreparedStatement stmt = null;
1171        ResultSet rs = null;
1172
1173        try {
1174
1175            // get a connection to the db
1176
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1177
1178            /*
1179            // execute the query
1180            String query = " select * from jahia_filemgr_files where id_jahia_file=" + fileID;
1181            if ( "0".equals(versionID) ){
1182                query += " and state_jahia_file=" + JahiaFile.STATE_ACTIVE;
1183            } else {
1184                query += " and version_jahia_file='" + JahiaTools.quote(versionID) + "'";
1185            }
1186            */

1187
1188            String JavaDoc query = null;
1189            if ("0".equals (versionID)) {
1190                query =
1191                        "select * from jahia_filemgr_files where id_jahia_file=? and state_jahia_file=?";
1192                stmt = dbConn.prepareStatement (query);
1193                stmt.setInt (1, fileID);
1194                stmt.setInt (2, JahiaFile.STATE_ACTIVE);
1195            } else {
1196                query =
1197                        "select * from jahia_filemgr_files where id_jahia_file=? and version_jahia_file=?";
1198                stmt = dbConn.prepareStatement (query);
1199                stmt.setInt (1, fileID);
1200                stmt.setString (2, versionID);
1201            }
1202
1203            debugQuery (query);
1204            rs = stmt.executeQuery ();
1205            while (rs.next ()) {
1206                int filemanagerID = rs.getInt ("filemgrid_jahia_file");
1207                int folderID = rs.getInt ("fldid_jahia_file");
1208                String JavaDoc uploadUser = rs.getString ("uploaduser_jahia_file");
1209                int pageID = rs.getInt ("pageid_jahia_file");
1210                int isPublic = rs.getInt ("is_public_jahia_file");
1211                String JavaDoc realName = rs.getString ("realname_jahia_file");
1212                String JavaDoc storageName = rs.getString ("storagename_jahia_file");
1213                long lastModifDate = rs.getLong ("lastmodifdate_jahia_file");
1214                long size = rs.getLong ("size_jahia_file");
1215                String JavaDoc type = rs.getString ("type_jahia_file");
1216                String JavaDoc title = rs.getString ("title_jahia_file");
1217                String JavaDoc descr = rs.getString ("descr_jahia_file");
1218                String JavaDoc version = rs.getString ("version_jahia_file");
1219                int state = rs.getInt ("state_jahia_file");
1220
1221                aFile = new JahiaFile (filemanagerID,
1222                        folderID,
1223                        uploadUser,
1224                        realName,
1225                        storageName,
1226                        lastModifDate,
1227                        size,
1228                        type,
1229                        title,
1230                        descr,
1231                        version,
1232                        state);
1233
1234                aFile.setFileID (fileID);
1235                aFile.setPageID (pageID);
1236                aFile.setPublic (isPublic);
1237            }
1238        } catch (SQLException ex) {
1239            processSQLException ("JahiaFilemanagerBaseService::getFile(fileID)", ex);
1240        } finally {
1241            try {
1242
1243                if (rs != null) rs.close ();
1244                if (stmt != null) stmt.close ();
1245            } catch (SQLException ex) {
1246                processSQLException (
1247                        "JahiaFilemanagerBaseService:: getFile(fileID) freeing connection fails",
1248                        ex);
1249            }
1250        }
1251        return aFile;
1252
1253    }
1254
1255
1256    /**
1257     * Method getFiles
1258     * Return a Vectors of Files objects depending of a sql where condition
1259     *
1260     * @param sqlWhere
1261     *
1262     * @return a Vector of Files object else null
1263     */

1264    public Vector JavaDoc getFilesDB (String JavaDoc sqlWhere) {
1265
1266        Vector JavaDoc files = new Vector JavaDoc ();
1267        JahiaFile aFile = null;
1268        Connection dbConn = null;
1269        Statement stmt = null;
1270        ResultSet rs = null;
1271
1272        try {
1273
1274            // get a connection to the db
1275
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1276
1277            // execute the query
1278
String JavaDoc query = " select * from jahia_filemgr_files " + sqlWhere;
1279
1280            stmt = dbConn.createStatement ();
1281            debugQuery (query);
1282            rs = stmt.executeQuery (query);
1283            while (rs.next ()) {
1284                int fileID = rs.getInt ("id_jahia_file");
1285                int filemanagerID = rs.getInt ("filemgrid_jahia_file");
1286                int folderID = rs.getInt ("fldid_jahia_file");
1287                String JavaDoc uploadUser = rs.getString ("uploaduser_jahia_file");
1288                int pageID = rs.getInt ("pageid_jahia_file");
1289                int isPublic = rs.getInt ("is_public_jahia_file");
1290                String JavaDoc realName = rs.getString ("realname_jahia_file");
1291                String JavaDoc storageName = rs.getString ("storagename_jahia_file");
1292                long lastModifDate = rs.getLong ("lastmodifdate_jahia_file");
1293                long size = rs.getLong ("size_jahia_file");
1294                String JavaDoc type = rs.getString ("type_jahia_file");
1295                String JavaDoc title = rs.getString ("title_jahia_file");
1296                String JavaDoc descr = rs.getString ("descr_jahia_file");
1297                String JavaDoc version = rs.getString ("version_jahia_file");
1298                int state = rs.getInt ("state_jahia_file");
1299
1300                aFile = new JahiaFile (filemanagerID,
1301                        folderID,
1302                        uploadUser,
1303                        realName,
1304                        storageName,
1305                        lastModifDate,
1306                        size,
1307                        type,
1308                        title,
1309                        descr,
1310                        version,
1311                        state);
1312
1313                aFile.setFileID (fileID);
1314                aFile.setPageID (pageID);
1315                aFile.setPublic (isPublic);
1316
1317                files.add (aFile);
1318            }
1319        } catch (SQLException ex) {
1320            processSQLException ("JahiaFilemanagerBaseService::getFiles(sqlWhere)", ex);
1321        } finally {
1322            try {
1323
1324                if (rs != null) rs.close ();
1325                if (stmt != null) stmt.close ();
1326            } catch (SQLException ex) {
1327                processSQLException (
1328                        "JahiaFilemanagerBaseService:: getFile(sqlWhere) freeing connection fails",
1329                        ex);
1330            }
1331        }
1332
1333        return files;
1334    }
1335
1336
1337    /**
1338     * Method getFilesByFolder
1339     * Return a Vector of files for a gived folderID
1340     *
1341     * @param folder id
1342     * @param orderSql an optional sql order command
1343     *
1344     * @return a Vector of link objects else null
1345     */

1346    public Vector JavaDoc getFilesByFolderDB (int folderID, String JavaDoc orderSql) {
1347
1348        JahiaFile aFile = null;
1349        Vector JavaDoc files = new Vector JavaDoc ();
1350        Connection dbConn = null;
1351        Statement stmt = null;
1352        ResultSet rs = null;
1353
1354        if (orderSql == null) {
1355            orderSql = "";
1356        }
1357
1358        try {
1359
1360            // get a connection to the db
1361
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1362
1363            // execute the query
1364
String JavaDoc query = "select * from jahia_filemgr_files where fldid_jahia_file=" + folderID + " " + orderSql;
1365
1366            stmt = dbConn.createStatement ();
1367            debugQuery (query);
1368            rs = stmt.executeQuery (query);
1369            while (rs.next ()) {
1370                int fileID = rs.getInt ("id_jahia_file");
1371                int filemanagerID = rs.getInt ("filemgrid_jahia_file");
1372                String JavaDoc uploadUser = rs.getString ("uploaduser_jahia_file");
1373                int pageID = rs.getInt ("pageid_jahia_file");
1374                int isPublic = rs.getInt ("is_public_jahia_file");
1375                String JavaDoc realName = rs.getString ("realname_jahia_file");
1376                String JavaDoc storageName = rs.getString ("storagename_jahia_file");
1377                long lastModifDate = rs.getLong ("lastmodifdate_jahia_file");
1378                long size = rs.getLong ("size_jahia_file");
1379                String JavaDoc type = rs.getString ("type_jahia_file");
1380                String JavaDoc title = rs.getString ("title_jahia_file");
1381                String JavaDoc descr = rs.getString ("descr_jahia_file");
1382                String JavaDoc version = rs.getString ("version_jahia_file");
1383                int state = rs.getInt ("state_jahia_file");
1384
1385                aFile = new JahiaFile (filemanagerID,
1386                        folderID,
1387                        uploadUser,
1388                        realName,
1389                        storageName,
1390                        lastModifDate,
1391                        size,
1392                        type,
1393                        title,
1394                        descr,
1395                        version,
1396                        state);
1397
1398                aFile.setFileID (fileID);
1399                files.add (aFile);
1400            }
1401        } catch (SQLException ex) {
1402            processSQLException ("JahiaFilemanagerBaseService::getFilesByFolder(folderid)", ex);
1403        } finally {
1404            try {
1405
1406                if (stmt != null) stmt.close ();
1407            } catch (SQLException ex) {
1408                processSQLException (
1409                        "FileDB:: getFilesByFolder(folderID) freeing connection fails", ex);
1410            }
1411        }
1412
1413        return files;
1414
1415    }
1416
1417
1418    //--------------------------------------------------------------------------
1419
//
1420
//
1421
// Folder DB Section
1422
//
1423
//
1424
//--------------------------------------------------------------------------
1425

1426
1427    /**
1428     * Method getFilemanager<br>
1429     * Return a filemanager
1430     *
1431     * @param filemanagerID the filemanager id
1432     *
1433     * @return filemanager or null
1434     */

1435    public Folder getFolderByFile (int fileID) {
1436
1437        return FolderDB.getInstance ().getFolderByFile (fileID);
1438
1439    }
1440
1441
1442    /**
1443     * Method getFolder<br>
1444     * Return a folder
1445     *
1446     * @param folderID the folder id
1447     *
1448     * @return folder or null
1449     */

1450    public Folder getFolder (int folderID) {
1451
1452        Folder folder = FolderDB.getInstance ().getFolder (folderID);
1453        return folder;
1454    }
1455
1456
1457
1458
1459
1460    //--------------------------------------------------------------------------
1461
//
1462
//
1463
// DOM Representation Section
1464
//
1465
//
1466
//--------------------------------------------------------------------------
1467

1468
1469    //--------------------------------------------------------------------------
1470
/**
1471     * returns a DOM representation of the filemanager of a site
1472     *
1473     * @param int siteID
1474     *
1475     * @auhtor NK
1476     */

1477    public JahiaDOMObject getFileMgrAsDOM (int siteID)
1478            throws JahiaException {
1479
1480        return FilemanagerDB.getInstance ().getFileMgrAsDOM (siteID);
1481
1482    }
1483
1484
1485    //--------------------------------------------------------------------------
1486
/**
1487     * returns a DOM representation of the filemanager folders of a site
1488     *
1489     * @param int siteID
1490     *
1491     * @auhtor NK
1492     */

1493    public JahiaDOMObject getFileMgrFoldersAsDOM (int siteID)
1494            throws JahiaException {
1495
1496        return FolderDB.getInstance ().getFileMgrFoldersAsDOM (siteID);
1497
1498    }
1499
1500
1501    //--------------------------------------------------------------------------
1502
/**
1503     * returns a DOM representation of the filemanager files of a site
1504     *
1505     * @param int siteID
1506     *
1507     * @auhtor NK
1508     */

1509    public JahiaDOMObject getFileMgrFilesAsDOM (int siteID)
1510            throws JahiaException {
1511        return FilemanagerDB.getInstance ().getFileMgrFilesAsDOM (siteID);
1512    }
1513
1514    //--------------------------------------------------------------------------
1515
/**
1516     * return a DOM document of the Filemanager file fields of a site
1517     *
1518     * @param int the site id
1519     *
1520     * @return JahiaDOMObject a DOM representation of this object
1521     *
1522     * @author NK
1523     */

1524    public JahiaDOMObject getFileMgrFileFieldsAsDOM (int siteID)
1525            throws JahiaException {
1526
1527        Connection dbConn = null;
1528        Statement statement = null;
1529
1530        String JavaDoc output = null;
1531        JahiaDBDOMObject dom = null;
1532
1533
1534        try {
1535
1536            String JavaDoc sqlQuery = "SELECT DISTINCT jahia_file_fields.fieldid_jahia_filefield,"
1537                    + "jahia_file_fields.fileid_jahia_filefield,jahia_file_fields.title_jahia_filefield"
1538                    + " FROM jahia_file_fields,jahia_fields_data WHERE jahia_file_fields.fieldid_jahia_filefield="
1539                    + "jahia_fields_data.id_jahia_fields_data AND jahia_fields_data.jahiaid_jahia_fields_data=" + siteID;
1540
1541
1542            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1543            statement = dbConn.createStatement ();
1544            if (statement != null) {
1545                ResultSet rs = statement.executeQuery (sqlQuery);
1546                if (rs != null) {
1547                    dom = new JahiaDBDOMObject ();
1548                    dom.addTable ("jahia_file_fields", rs);
1549                    return dom;
1550                }
1551            }
1552        } catch (SQLException se) {
1553            String JavaDoc errorMsg = "Error in getFileMgrFileFieldsAsDOM(int siteID) : " + se.getMessage ();
1554            logger.debug (errorMsg);
1555            throw new JahiaException ("Cannot load filemanager file fields from the database",
1556                    errorMsg, JahiaException.DATABASE_ERROR,
1557                    JahiaException.CRITICAL_SEVERITY);
1558        } finally {
1559            try {
1560
1561                if (statement != null) statement.close ();
1562            } catch (SQLException ex) {
1563                processSQLException (
1564                        "JahiaFilemanagerBaseService::getFileMgrFileFieldsAsDOM error freeing connection fails",
1565                        ex);
1566            }
1567        }
1568
1569        return dom;
1570
1571    }
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584    //--------------------------------------------------------------------------
1585
/**
1586     * Return a mime type looking at full file name
1587     *
1588     * @param String the file name
1589     *
1590     * @return String the mime type or "" if not found
1591     */

1592    private String JavaDoc getMimeTypeFromFilename (String JavaDoc filename) {
1593
1594        if ((m_MimeTypes == null)
1595                || (filename == null)
1596                || (filename.lastIndexOf (".") == -1))
1597            return "";
1598
1599        String JavaDoc mimeType = "";
1600        String JavaDoc ext = filename.substring (filename.lastIndexOf (".") + 1,
1601                filename.length ());
1602
1603        return getMimeTypeFromExt (ext);
1604    }
1605
1606    //--------------------------------------------------------------------------
1607
/**
1608     * Return a mime type looking at the file extension without "."
1609     *
1610     * @param String the extension
1611     *
1612     * @return String the mime type or "" if not found
1613     */

1614    private String JavaDoc getMimeTypeFromExt (String JavaDoc extension) {
1615
1616        if ((m_MimeTypes == null)
1617                || (extension == null))
1618            return "";
1619
1620        String JavaDoc mimeType = "";
1621
1622        logger.debug ("extension=" + extension);
1623
1624        mimeType = m_MimeTypes.getProperty (extension.toLowerCase ());
1625        if (mimeType == null)
1626            mimeType = "";
1627
1628        return mimeType;
1629    }
1630
1631
1632    /**
1633     * Method filter
1634     * Filter special caracters like ',"
1635     *
1636     * @param input String to filter
1637     *
1638     * @return a filtered string
1639     */

1640    protected static String JavaDoc filter (String JavaDoc input) {
1641        StringBuffer JavaDoc filtered = new StringBuffer JavaDoc (input.length ());
1642        char c;
1643        for (int i = 0; i < input.length (); i++) {
1644            c = input.charAt (i);
1645            if (c == '\'') {
1646                filtered.append ("&#39;");
1647            } else if (c == '"') {
1648                filtered.append ("&#34;");
1649            } else {
1650                filtered.append (c);
1651            }
1652        }
1653        return (filtered.toString ());
1654    }
1655
1656
1657    /**
1658     * Method toConsole
1659     * For debuggin purpose
1660     * Write any msg to the console
1661     *
1662     * @param msg the message to display
1663     */

1664    protected void toConsole (String JavaDoc msg) {
1665        if (false) {
1666            //System.out.println(msg);
1667
}
1668    }
1669
1670
1671    /**
1672     * Method debugQuery
1673     * Outout the query for debug purpose
1674     *
1675     * @param query
1676     */

1677    protected static void debugQuery (String JavaDoc query) {
1678        if (m_DebugQuery) {
1679            logger.debug (query);
1680        }
1681    }
1682
1683
1684    /**
1685     * Method processSQLException
1686     * For debug purpose
1687     *
1688     * @param func the name of the calling method
1689     * @param the SQLException
1690     */

1691    protected void processSQLException (String JavaDoc func, SQLException ex) {
1692        if (m_DebugQuery) {
1693            while (ex != null) {
1694                logger.debug (
1695                        "SQL EXCEPTION in function [" + func + "]: SqlState = " + ex.getSQLState () + " Error code = " + ex.getErrorCode () + " Error msg = " + ex.toString (),
1696                        ex);
1697                ex = ex.getNextException ();
1698            }
1699        }
1700    }
1701
1702
1703} // end Class JahiaFilemanagerBaseService
Popular Tags