KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > templates_deployer > JahiaTemplatesDeployerBaseService


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
// JahiaTemplatesDeployerBaseService
15
//
16
// NK 12.01.2001
17
//
18
//
19

20
21 package org.jahia.services.templates_deployer;
22
23
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 import org.jahia.bin.Jahia;
30 import org.jahia.data.templates.JahiaTemplateDef;
31 import org.jahia.data.templates.JahiaTemplatesPackage;
32 import org.jahia.data.templates.JahiaTemplatesPackageHandler;
33 import org.jahia.exceptions.JahiaException;
34 import org.jahia.exceptions.JahiaInitializationException;
35 import org.jahia.registries.ServicesRegistry;
36 import org.jahia.services.pages.JahiaPageDefinition;
37 import org.jahia.services.sites.JahiaSite;
38 import org.jahia.settings.SettingsBean;
39 import org.jahia.utils.JahiaTools;
40 import org.jahia.utils.zip.JahiaArchiveFileHandler;
41
42
43 /**
44  * This Service Deploy templates packed in a .jar file.
45  *
46  * @author Khue ng
47  * @version 1.0
48  */

49 public class JahiaTemplatesDeployerBaseService extends JahiaTemplatesDeployerService {
50
51     private static org.apache.log4j.Logger logger =
52             org.apache.log4j.Logger.getLogger(JahiaTemplatesDeployerBaseService.class);
53
54     private static JahiaTemplatesDeployerBaseService m_Instance = null;
55
56     /** The Default Visible status for Templates **/
57     private int m_VisibleStatus = 0; // FIXME , where to get it ?
58

59     /** The relative Path to the Template Root Folder **/
60     private static String JavaDoc m_TemplateRootPath = "";
61
62     /** The Shared Templates Path **/
63     private static String JavaDoc m_SharedTemplatesPath = "";
64
65     /** The JSP context path **/
66     private static String JavaDoc m_JspContext = "";
67
68     /** The templates context path **/
69     private static String JavaDoc m_TemplatesContext = "";
70
71     /** The relative Path to the New Template Folder **/
72     private static String JavaDoc m_NewTemplatePath = "";
73
74     /** The classes Root Path **/
75     private static String JavaDoc m_ClassesRootPath;
76
77     /** The templates classe Root Path **/
78     private static String JavaDoc m_TEMPLATES_CLASSES_ROOT_FOLDER = "jahiatemplates";
79
80
81     /** Meta-Inf folder **/
82     protected static final String JavaDoc m_META_INF = "Meta-Inf";
83
84
85
86
87     /**
88      * Constructor
89      */

90     protected JahiaTemplatesDeployerBaseService(){
91         logger.info("***** Starting the Jahia Templates Deployer Base Service *****" );
92     }
93
94
95     /**
96      * Use this method to get an instance of this class
97      *
98      */

99     public static synchronized JahiaTemplatesDeployerBaseService getInstance(){
100
101         if ( m_Instance == null ){
102             m_Instance = new JahiaTemplatesDeployerBaseService();
103         }
104         return m_Instance;
105     }
106
107
108     /***
109      * @param JahiaPrivateSettings jSettings
110      *
111      */

112     public void init( SettingsBean jSettings )
113     throws JahiaInitializationException
114     {
115
116         if (!isInitialized ()) {
117
118
119             Properties JavaDoc props = jSettings.getPropertiesFile();
120             m_TemplateRootPath = jSettings.getJahiaTemplatesDiskPath();
121             m_JspContext = jSettings.getJspContext();
122             m_TemplatesContext = jSettings.getTemplatesContext();
123             m_ClassesRootPath = jSettings.getClassDiskPath() + File.separator + m_TEMPLATES_CLASSES_ROOT_FOLDER;
124             m_NewTemplatePath = jSettings.getJahiaNewTemplatesDiskPath();
125             m_SharedTemplatesPath = jSettings.getJahiaSharedTemplatesDiskPath();
126
127             logger.debug("m_TemplateRootPath=" + m_TemplateRootPath);
128             logger.debug("m_JspContext=" + m_JspContext);
129             logger.debug("m_TemplatesContext" + m_TemplatesContext);
130             logger.debug("m_ClassesRootPath=" + m_ClassesRootPath);
131
132
133
134             // create the temporary folder
135
File JavaDoc f = new File JavaDoc(m_NewTemplatePath);
136             File JavaDoc parent = f.getParentFile();
137             if ( parent != null ){
138                 File JavaDoc tmpFolder = new File JavaDoc(parent.getAbsolutePath() + File.separator + "tmp");
139                 tmpFolder.mkdirs();
140                 if ( tmpFolder == null || !tmpFolder.isDirectory() ){
141                     String JavaDoc errMsg = " cannot create a temporaty folder " ;
142                     logger.error (errMsg + "\n" );
143                     throw new JahiaInitializationException ( errMsg );
144                 }
145                 m_TempFolderDiskPath = tmpFolder.getAbsolutePath();
146             }
147
148             // create the shared templates folder
149
File JavaDoc sTemplates = new File JavaDoc(m_SharedTemplatesPath);
150             sTemplates.mkdirs();
151
152             mIsServiceInitialized = true;
153         }
154
155
156     } // end init
157

158
159     /**
160      * Deploy a template .jar file.
161      * The jar file will be unzipped in the root folder.
162      *
163      * If the RootFolder is equals to an empty string, the Root Folder
164      * is the one described in the templates.xml
165      *
166      * @param (JahiaSite) the site
167      * @param (String) rootFolder, root folder for the template
168      * @param (String) filePath , the full path to the template.jar file
169      * @param (boolean) moveTemplate , if true, move te template package to the deployed directory when done
170      */

171     public boolean deploy(JahiaSite site, String JavaDoc rootFolder, String JavaDoc filePath, boolean moveTemplate) throws JahiaException {
172
173         boolean success = false;
174         String JavaDoc fullPath = null;
175
176         if ( filePath.endsWith(".jar") ){
177
178             JahiaTemplatesPackageHandler ph = null;
179
180             try {
181
182                 logger.debug("Trying to deploy " + filePath + "...");
183
184                 ph = new JahiaTemplatesPackageHandler(filePath);
185
186                 JahiaTemplatesPackage tempPack = ph.getPackage();
187
188                 if ( tempPack == null ){
189                     String JavaDoc errMsg =" cannot create a JahiaTemplatesPackage on file " + filePath ;
190                     logger.debug(errMsg);
191                     throw new JahiaException ("JahiaTemplatesDeployerBaseService::deploy()", "JahiaTemplatesDeployerBaseService" + errMsg ,
192                                  JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
193                 }
194
195                 StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc(1024);
196                 strBuf.append(m_TemplateRootPath);
197                 strBuf.append(File.separator);
198                 strBuf.append(site.getSiteKey());
199                 strBuf.append(File.separator);
200                 if ( rootFolder.equals("") ){
201                     strBuf.append(tempPack.getRootFolder());
202                 } else {
203                     strBuf.append(rootFolder);
204                 }
205
206                 // Full path to the templates root folder
207
fullPath = strBuf.toString();
208
209                 // Check that the root folder for the new template doesn't exist
210
File JavaDoc f = new File JavaDoc(fullPath);
211                 if ( f != null && !f.isDirectory() ){
212                     // create the dir
213
f.mkdirs();
214                 }
215                 logger.debug ("Delete meta-inf folder=" + f.getAbsolutePath());
216                 // Remove the Meta-Inf folder first
217
removeMetaInfFolder(f.getAbsolutePath());
218
219                 ph.unzip(fullPath);
220
221
222                 // extract the classes file
223
if ( tempPack.hasClasses () ){
224                     String JavaDoc classesFilePath = fullPath + File.separator + tempPack.getClassesFile();
225
226                     File JavaDoc tmpFile = new File JavaDoc(classesFilePath);
227                     try{
228                         if ( tmpFile != null && tmpFile.isFile() ){
229                             JahiaArchiveFileHandler arch = new JahiaArchiveFileHandler(classesFilePath);
230                             arch.unzip(m_ClassesRootPath);
231                         } else {
232                             success = false;
233                         }
234                     } catch ( IOException JavaDoc ioe ){
235                         String JavaDoc errMsg = "Failed creating JahiaArchiveFileHandler on classes file " ;
236                         logger.error(errMsg, ioe);
237                         throw new JahiaException ("JahiaTemplatesDeployerBaseService::deploy()", "JahiaTemplatesDeployerBaseService" + errMsg ,
238                                JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
239                     }
240                 }
241                 success = true;
242             } catch ( Throwable JavaDoc t ) {
243
244                 String JavaDoc errMsg = "Failed handling templates file " ;
245                 logger.debug(errMsg, t);
246                 throw new JahiaException ("JahiaTemplatesDeployerBaseService::deploy()", "JahiaTemplatesDeployerBaseService" + errMsg ,
247                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, t);
248             } finally {
249                 if ( ph != null ){
250                     ph.closeArchiveFile();
251                 }
252             }
253
254             if (success && moveTemplate){
255
256                 // move the template package into the template root folder
257
File JavaDoc fileItem = new File JavaDoc (filePath);
258                 fileItem.renameTo(new File JavaDoc(fullPath + File.separator + fileItem.getName()));
259             }
260         }
261
262         return success;
263     }
264
265
266     /**
267      * Undeploy a template
268      *
269      * @param (JahiaPageDefinition) template
270      */

271     public boolean undeploy(JahiaPageDefinition template) throws JahiaException {
272
273         /*
274         if ( template != null ){
275
276             File f = new File(m_JspContext + File.sepatator
277
278             // Delete physically the directory on disk
279             JahiaTools.deleteFile(new File(m_WebAppRootPath + app.getContext()));
280             return true;
281         }
282         */

283         return false;
284
285     }
286
287
288     /**
289      * Deploy a Vector of .jar templates files
290      *
291      * @param (JahiaSite) the site
292      * @param (Vector) files, a vector of .jar templates package file
293      * @return (boolean) false on exception
294      */

295     public boolean deploy(JahiaSite site, Vector JavaDoc files) {
296
297         synchronized (files) {
298
299             if ( site == null ) {
300                 return false;
301             }
302             // Check first if JahiaPageDefinitionsRegistry is loaded
303
if (!ServicesRegistry.getInstance().getJahiaPageTemplateService().isInitialized()) {
304                 return false;
305             }
306
307             if ( !Jahia.isInitiated() ){
308                 return false;
309             }
310
311             int size = files.size();
312             File JavaDoc fileItem = null;
313
314             for ( int i=0 ; i<size ; i++ ){
315
316                 fileItem = (File JavaDoc)files.get(i);
317
318                 if ( fileItem.isFile() && fileItem.getName().endsWith(".jar") ){
319
320                     /*
321                     logger.debug(" JahiaTemplatesDeployerBaseService found new template: "
322                                             + fileItem.getName() );
323                     */

324                     try {
325
326                         int templateLimit = Jahia.getTemplateLimit();
327
328                         if ( site.getTemplatesAutoDeployMode() ){
329                             JahiaTemplatesPackage pack = loadTemplatesInfo(fileItem.getAbsolutePath());
330                             if ( pack != null ) {
331
332                                 // check for license limitation
333
int nbTemplates = ServicesRegistry.getInstance()
334                                                                     .getJahiaPageTemplateService()
335                                                                     .getNbPageTemplates(site.getID());
336
337                                 if ( (Jahia.getTemplateLimit() != -1)
338                                      && (nbTemplates + pack.getTemplates().size()) >
339                                         templateLimit ){
340                                     site.setTemplatesAutoDeployMode(false);
341
342                                     ServicesRegistry.getInstance().getJahiaSitesService().updateSite(site);
343
344                                     addNewFile(site,fileItem.getAbsolutePath());
345                                 } else {
346
347                                     if ( deploy(site,"",fileItem.getAbsolutePath(),true) ){
348                                         // register in Jahia
349
registerTemplates(site, pack);
350                                         deletePackage(site,fileItem.getAbsolutePath());
351                                     } else {
352                                         fileItem.delete();
353                                         deletePackage(site,fileItem.getAbsolutePath());
354                                         return false;
355                                     }
356                                 }
357
358                             } else {
359                                 try {
360                                     File JavaDoc newFile = new File JavaDoc(fileItem.getAbsolutePath()+"_error");
361                                     //newFile.createNewFile();
362
fileItem.renameTo(newFile);
363                                 } catch ( Throwable JavaDoc t ){
364                                     //logger.debug("Exception while trying to rename error file ");
365
}
366                             }
367                         } else {
368                             addNewFile(site,fileItem.getAbsolutePath());
369                         }
370                     } catch ( JahiaException e ) {
371                         String JavaDoc errMsg = "Failed deploying file " ;
372                         logger.error(errMsg, e);
373                         fileItem.delete();
374                         return false;
375                     }
376
377                 }
378             }
379             return true;
380         }
381     }
382
383
384     /**
385      * Try to load info from a .jar template file or an unzipped directory
386      * Informations are read from the templates.xml file
387      *
388      * @param (String) full path to a file or directory
389      * @return a JahiaTemplatesPackage object or null
390      */

391     public JahiaTemplatesPackage loadTemplatesInfo(String JavaDoc path) {
392
393         JahiaTemplatesPackage pack = null;
394
395         // check for case sensitive
396
if ( !JahiaTools.checkFileNameCaseSensitive(path) ){
397             return null;
398         }
399
400         File JavaDoc f = new File JavaDoc(path);
401
402         try {
403             // wait while the file is still modified
404
long fLength = f.length();
405             Thread.sleep(500);
406             while ( fLength != f.length() ){
407                 fLength = f.length();
408                 Thread.sleep(500);
409             }
410         } catch ( Throwable JavaDoc tr ){
411             return null;
412         }
413
414
415         if ( f != null && ( f.isFile() || f.isDirectory() ) ){
416
417             JahiaTemplatesPackageHandler ph = null;
418             try {
419                 ph = new JahiaTemplatesPackageHandler(path);
420                 pack = ph.getPackage();
421                 return pack;
422             } catch ( JahiaException je ){
423                 // FIXME not critial
424
//logger.debug("Error scanning template in " + path + " , " + je.getMessage());
425
return null;
426             } finally {
427                 if ( ph != null ){
428                     ph.closeArchiveFile();
429                 }
430             }
431         }
432
433         return pack;
434     }
435
436
437
438     /**
439      * Register templates in Jahia
440      *
441      * @param int site id , which site
442      * @param JahiaTemplatesPackage the templates package
443      */

444     public void registerTemplates(JahiaSite site, JahiaTemplatesPackage pack ) throws JahiaException {
445
446         //logger.debug("registerTemplates(), started ");
447

448
449         //logger.debug("registerTemplates(), for site " + site.getServerName() );
450

451         // save definition in db
452
int size = pack.getTemplates().size();
453
454         StringBuffer JavaDoc tempFullPath = new StringBuffer JavaDoc (1024);
455         tempFullPath.append(m_TemplatesContext);
456         tempFullPath.append(site.getSiteKey());
457         tempFullPath.append("/") ;
458         tempFullPath.append(pack.getRootFolder());
459         tempFullPath.append("/") ;
460
461         for ( int i=0 ; i<size ; i++ ) {
462
463             JahiaTemplateDef tempDef = (JahiaTemplateDef)pack.getTemplates().get(i);
464
465             //logger.debug("try to add template " + tempDef.getDisplayName());
466

467             JahiaPageDefinition pageDef = ServicesRegistry.getInstance().getJahiaPageTemplateService().
468                                             getPageTemplateBySourcePath(site.getID(),tempFullPath.toString() + tempDef.getFileName());
469
470             if ( pageDef == null || ( !pageDef.getName().equals(tempDef.getDisplayName()) ) ){
471
472                 ServicesRegistry.getInstance().getJahiaPageTemplateService().
473                         createPageTemplate (
474
475                                             site.getID(),
476                                             tempDef.getDisplayName(),
477                                             tempFullPath.toString() + tempDef.getFileName(),
478                                             tempDef.isVisible(),
479                                             "", // no image
480
site.getAclID());
481
482                 logger.debug ("Added template " + tempDef.getFileName() );
483             }
484         }
485     }
486
487
488     //-------------------------------------------------------------------------
489
/**
490      * Return the template root path
491      *
492      * @return String the template root path
493      */

494     public String JavaDoc getTemplateRootPath(){
495         return m_TemplateRootPath;
496     }
497
498
499     //-------------------------------------------------------------------------
500
/**
501      * Return the template jsp context
502      *
503      * @return String the template jsp context
504      */

505     public String JavaDoc getTemplatesContext(){
506         return m_TemplatesContext;
507     }
508
509
510     //-------------------------------------------------------------------------
511
/**
512      * Return the new templates root path
513      *
514      * @return String the new templates root path
515      */

516     public String JavaDoc getNewTemplatesPath(){
517         return m_NewTemplatePath;
518     }
519
520
521     //-------------------------------------------------------------------------
522
/**
523      * Return the shared templates folder disk path
524      *
525      * @return String the shared templates folder disk path
526      */

527     public String JavaDoc getSharedTemplatesPath(){
528         return m_SharedTemplatesPath;
529     }
530
531
532     //-------------------------------------------------------------------------
533
/**
534      * Search and remove the Meta-Inf folder
535      * @param String parentPath, the path of the parent Folder
536      * @return (boolean) true if successfull
537      */

538     protected boolean removeMetaInfFolder(String JavaDoc parentPath){
539
540         if ( parentPath == null ){
541             return false;
542         }
543
544         File JavaDoc f = new File JavaDoc(parentPath);
545         File JavaDoc[] files = f.listFiles();
546         for (int i=0 ; i<files.length ; i++){
547             if ( files[i].getName().equalsIgnoreCase(m_META_INF) ){
548                 try {
549                     return JahiaTools.deleteFile(files[i],false);
550                 }catch ( Throwable JavaDoc t ){
551                     t.printStackTrace();
552                     return false;
553                 }
554             }
555         }
556
557         return false;
558     }
559
560 }
561
562
Popular Tags