KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > pages > JahiaPageTemplateBaseService


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  * ----- BEGIN LICENSE BLOCK -----
15  * Version: JCSL 1.0
16  *
17  * The contents of this file are subject to the Jahia Community Source License
18  * 1.0 or later (the "License"); you may not use this file except in
19  * compliance with the License. You may obtain a copy of the License at
20  * http://www.jahia.org/license
21  *
22  * Software distributed under the License is distributed on an "AS IS" basis,
23  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
24  * for the rights, obligations and limitations governing use of the contents
25  * of the file. The Original and Upgraded Code is the Jahia CMS and Portal
26  * Server. The developer of the Original and Upgraded Code is JAHIA Ltd. JAHIA
27  * Ltd. owns the copyrights in the portions it created. All Rights Reserved.
28  *
29  * The Shared Modifications are Jahia View Helper.
30  *
31  * The Developer of the Shared Modifications is Jahia Solution S�rl.
32  * Portions created by the Initial Developer are Copyright (C) 2002 by the
33  * Initial Developer. All Rights Reserved.
34  *
35  * Contributor(s):
36  * 28-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
37  *
38  * ----- END LICENSE BLOCK -----
39  */

40
41
42 package org.jahia.services.pages;
43
44 import java.util.Enumeration JavaDoc;
45 import java.util.TreeMap JavaDoc;
46 import java.util.Vector JavaDoc;
47
48 import org.apache.log4j.Logger;
49 import org.jahia.data.JahiaDOMObject;
50 import org.jahia.exceptions.JahiaException;
51 import org.jahia.exceptions.JahiaInitializationException;
52 import org.jahia.exceptions.JahiaTemplateNotFoundException;
53 import org.jahia.registries.ServicesRegistry;
54 import org.jahia.services.acl.ACLNotFoundException;
55 import org.jahia.services.acl.ACLResource;
56 import org.jahia.services.acl.JahiaACLEntry;
57 import org.jahia.services.acl.JahiaBaseACL;
58 import org.jahia.services.cache.Cache;
59 import org.jahia.services.cache.CacheFactory;
60 import org.jahia.services.cache.CacheListener;
61 import org.jahia.services.sites.JahiaSite;
62 import org.jahia.services.usermanager.JahiaGroup;
63 import org.jahia.services.usermanager.JahiaGroupManagerService;
64 import org.jahia.services.usermanager.JahiaUser;
65 import org.jahia.settings.SettingsBean;
66
67
68 /**
69  * @author
70  * @version
71  */

72 public class JahiaPageTemplateBaseService extends JahiaPageTemplateService
73                                           implements CacheListener {
74
75     /** logging */
76     private static final Logger logger = Logger.getLogger (JahiaPageTemplateBaseService.class);
77
78     /** the unique instance of this class */
79     private static JahiaPageTemplateBaseService instance = null;
80
81     // the Page Templates cache name.
82
public static final String JavaDoc PAGE_TEMPLATE_CACHE = "PageTemplateCache";
83     /** the template cache */
84     private static Cache templateCache = null;
85
86     private JahiaPageTemplateDB mTemplateDB = null;
87
88
89     /**
90      * Default constructor, creates a new <code>JahiaPageTemplateBaseService</code> instance.
91      */

92     protected JahiaPageTemplateBaseService () {
93     }
94
95
96     /**
97      * Create a new page template.
98      *
99      * @param siteID The jahia site ID.
100      * @param name The page template name.
101      * @param sourcePath The page template source path.
102      * @param isAvailable <code>true</code> is the page template is Available in edition
103      * mode or <code>false</code> if it should be hidden.
104      * @param image Image path.
105      * @param parentAclID The parent acl id
106      *
107      * @return Return a new page template instanciation.
108      *
109      * @throws org.jahia.exceptions.JahiaException
110      * when any error occured in the page template creation process.
111      */

112     public JahiaPageDefinition createPageTemplate (
113             int siteID,
114             String JavaDoc name,
115             String JavaDoc sourcePath,
116             boolean isAvailable,
117             String JavaDoc image,
118             int parentAclID) throws JahiaException {
119         // We need the Group Manager Service, before instanciating anything, check
120
// if the service is available.
121

122         JahiaGroupManagerService grpService;
123         if (ServicesRegistry.getInstance () != null) {
124             grpService = ServicesRegistry.getInstance ().getJahiaGroupManagerService ();
125
126             if (grpService == null) {
127                 logger.warn (
128                         "Could not access to the Group Manager Service instance. Stopping page template creation.");
129                 throw new JahiaException ("Could not access the Group Manager Service",
130                         "JahiaGroupManagerService.getInstance() returned null!!!",
131                         JahiaException.PAGE_ERROR, JahiaException.CRITICAL_SEVERITY);
132             }
133
134         } else {
135             logger.warn (
136                     "Could not access to the Service Registry instance. Stopping page template creation.");
137             throw new JahiaException ("Could not access the Service Registry",
138                     "ServicesRegistry.getInstance() returned null!!!",
139                     JahiaException.PAGE_ERROR, JahiaException.CRITICAL_SEVERITY);
140
141         }
142
143         // check if the service is running
144
checkService ();
145
146         // get the next available page template ID
147
/**
148          * rollback fix on JAHIA-240 because it causes migration problems.
149          */

150         // int newID = ServicesRegistry.getInstance().getJahiaIncrementorsDBService().autoIncrement("jahia_pages_def");
151
int newID = mTemplateDB.getNextID();
152
153         // Create a new ACL.
154
JahiaBaseACL acl = new JahiaBaseACL ();
155         if (acl != null) {
156             try {
157                 acl.create (parentAclID);
158             } catch (ACLNotFoundException ex) {
159                 throw new JahiaException ("Could not create the page def.",
160                         "The parent ACL ID [" + parentAclID + "] could not be found," +
161                         " while trying to create a new page def.",
162                         JahiaException.TEMPLATE_ERROR, JahiaException.ERROR_SEVERITY);
163             }
164         } else {
165             throw new JahiaException ("Could not create page def.",
166                     "Could not instanciate a new ACL object while trying to create a new page def.",
167                     JahiaException.TEMPLATE_ERROR, JahiaException.CRITICAL_SEVERITY);
168         }
169
170         // instanciate the new page template
171
JahiaPageDefinition template = new JahiaPageDefinition (newID, siteID,
172                 name, sourcePath, isAvailable, image);
173
174         if (template == null) {
175             throw new JahiaException ("Could not create page template",
176                     "Could not instanciate a new JahiaPageDefinition object.",
177                     JahiaException.PAGE_ERROR, JahiaException.CRITICAL_SEVERITY);
178         }
179
180         template.setACL (acl.getID ());
181
182         // Add the page template in the database.
183
if (!mTemplateDB.insertPageTemplate (template)) {
184             throw new JahiaException ("Could not create page template",
185                     "Could not insert the page template into the database.",
186                     JahiaException.PAGE_ERROR, JahiaException.CRITICAL_SEVERITY);
187         }
188
189
190         // set the template default permissions
191
// enable guest users to view the template
192
JahiaACLEntry aclEntry = new JahiaACLEntry (1, 0);
193         JahiaGroup guestGroup = grpService.getGuestGroup (siteID);
194         acl.setGroupEntry (guestGroup, aclEntry);
195
196         // Finally add it into the cache and return the template
197
templateCache.put (new Integer JavaDoc (template.getID ()), template);
198         return template;
199     }
200
201
202     /**
203      * Deletes the specified page template.
204      *
205      * @param defID the page template identification number
206      *
207      * @throws JahiaException when the service is not available, or a general failure occured while
208      * removing the page template.
209      */

210     public synchronized void deletePageTemplate (int defID)
211             throws JahiaException {
212         // check if the service is running
213
checkService ();
214
215         JahiaPageDefinition pageTemplate = lookupPageTemplate (defID);
216
217         JahiaBaseACL pageTemplateACL = pageTemplate.getACL ();
218         pageTemplateACL.delete ();
219
220         mTemplateDB.deletePageTemplate (defID);
221
222         // Finally remove it from the cache
223
templateCache.remove (new Integer JavaDoc (defID));
224
225     }
226
227
228     /**
229      * Retrieve all the page template identification numbers.
230      *
231      * @return the page template identification numbers.
232      *
233      * @throws JahiaException when a database access could not be preformed.
234      */

235     public Vector JavaDoc getAllPageTemplateIDs ()
236             throws JahiaException {
237         checkService ();
238         return mTemplateDB.getAllPageTemplateIDs ();
239     }
240
241
242     /**
243      * Returns the unique instance of the page template service
244      */

245     public static synchronized JahiaPageTemplateBaseService getInstance () {
246         if (instance == null) {
247             instance = new JahiaPageTemplateBaseService ();
248         }
249         return instance;
250     }
251
252
253     public JahiaPageDefinition getPageTemplateBySourcePath (int siteID, String JavaDoc path)
254             throws JahiaException, JahiaTemplateNotFoundException {
255         // check if the service is running
256
checkService ();
257
258         JahiaPageDefinition template = null;
259         int templateID = mTemplateDB.getPageTemplateIDMatchingSourcePath (siteID, path);
260
261         if (templateID != -1) {
262             template = lookupPageTemplate (templateID);
263         }
264         return template;
265     }
266
267
268     /**
269      * Retrieve the requested page template related to the <code>user</code> and the
270      * jahia <code>siteID</code> site identification number.
271      *
272      * @param user the user reference
273      * @param siteID the site identification number
274      * @param availableOnly <code>true</code> to retrieve only the current available
275      * page templates. <code>false</code> to retrieve all the page
276      * templates the user has access to.
277      *
278      * @return an enumeration of page templates
279      *
280      * @throws JahiaException when a general failure occured
281      */

282     public Enumeration JavaDoc getPageTemplates (JahiaUser user, int siteID, boolean availableOnly)
283             throws JahiaException {
284         // check if the service is running
285
checkService ();
286
287
288         TreeMap JavaDoc tm = new TreeMap JavaDoc ();
289         Object JavaDoc[] templates = templateCache.keys ();
290         for (int i = 0; i < templates.length; i++) {
291             JahiaPageDefinition template = (JahiaPageDefinition) templateCache.get (
292                     templates[i]);
293             if (template.getJahiaID () == siteID &&
294                     (!availableOnly || template.isAvailable ()) &&
295                     ACLResource.checkReadAccess (template, user)) {
296                 tm.put (template.getName (), template);
297             }
298         }
299         Vector JavaDoc theList = new Vector JavaDoc (tm.values ());
300         return theList.elements ();
301     }
302
303
304     /**
305      * Retireve all the page templates related to the site identification number
306      * <code>siteID</code>.
307      *
308      * @param siteID the site identification number
309      * @param availableOnly <code>true</code> to retrieve only the current available
310      * page templates. <code>false</code> to retrieve all the page
311      * templates the user has access to.
312      *
313      * @return an enumeration of page templates
314      *
315      * @throws JahiaException when a general failure occured
316      */

317     public Enumeration JavaDoc getPageTemplates (int siteID, boolean availableOnly)
318             throws JahiaException {
319         // check if the service is running
320
checkService ();
321
322         TreeMap JavaDoc tm = new TreeMap JavaDoc ();
323         Object JavaDoc[] templates = templateCache.keys ();
324         for (int i = 0; i < templates.length; i++) {
325             JahiaPageDefinition template = (JahiaPageDefinition) templateCache.get (
326                     templates[i]);
327
328             if (template.getJahiaID () == siteID) {
329                 if (!availableOnly || template.isAvailable ()) {
330                     tm.put (template.getName (), template);
331                 }
332             }
333         }
334
335         Vector JavaDoc theList = new Vector JavaDoc (tm.values ());
336         return theList.elements ();
337     }
338
339
340     /**
341      * Initialize the service.
342      *
343      * @throws JahiaInitializationException when the service could not be initialized
344      */

345     public synchronized void init (SettingsBean settings)
346             throws JahiaInitializationException {
347         logger.debug ("** Initializing the Page Template Service ...");
348         // do not allow initialization when the service is still running
349
if (!isInitialized ()) {
350
351             // Initialize the page template cache
352
logger.debug (" - Instanciate the page template cache ...");
353             templateCache = CacheFactory.createCache (PAGE_TEMPLATE_CACHE);
354             if (templateCache != null)
355                 templateCache.registerListener (this);
356
357
358             // get the page template DB access instance
359
logger.debug (" - Instanciate the database page template tools ...");
360             mTemplateDB = JahiaPageTemplateDB.getInstance ();
361
362
363             // Verify if the needed classes could be successfully instanciated.
364
if ((templateCache != null) && (mTemplateDB != null)) {
365
366                 mIsServiceInitialized = true;
367                 logger.debug ("** Page Template Service successfully initialized!");
368
369             } else {
370                 // invalidate the previous initializations
371
mTemplateDB = null;
372                 templateCache = null;
373
374                 // and raise an exception :(
375
throw new JahiaInitializationException (
376                         "Page Template Service could not be initialized successfully.");
377             }
378
379             try {
380                 loadAllPageTemplates ();
381             } catch (JahiaException je) {
382                 throw new JahiaInitializationException (
383                         "Error while loading all page templates from database", je);
384             }
385         }
386     }
387
388
389     private synchronized void loadAllPageTemplates ()
390             throws JahiaException {
391         Vector JavaDoc templateIDs = mTemplateDB.getAllPageTemplateIDs ();
392         for (int i = 0; i < templateIDs.size (); i++) {
393             int templateID = ((Integer JavaDoc) templateIDs.elementAt (i)).intValue ();
394
395             // the template which could not be found in the database are not
396
// loaded.
397
try {
398                 JahiaPageDefinition template = lookupPageTemplate (templateID);
399                 if (template != null) {
400                     templateCache.put (new Integer JavaDoc (template.getID ()), template);
401                 }
402
403             } catch (JahiaTemplateNotFoundException ex) {
404                 logger.warn(ex);
405                 // the page template could not be found, don't add it into the
406
// database.
407

408                 // This exception should theoreticaly not happen, if it does, the DB
409
// is unconsistent.
410
}
411         }
412     }
413
414
415     public JahiaPageDefinition lookupPageTemplate (int templateID)
416             throws JahiaException, JahiaTemplateNotFoundException {
417         // check if the service is running
418
checkService ();
419
420         // Try to read the page template out of the cache
421
JahiaPageDefinition template =
422                 (JahiaPageDefinition) templateCache.get (new Integer JavaDoc (templateID));
423
424         // if the template is not present in the cache, read it
425
// from the database.
426
if (template == null) {
427             template = mTemplateDB.loadPageTemplate (templateID);
428
429             // if the page template is not in the database, raise an
430
// exception
431
if (template != null) {
432                 templateCache.put (new Integer JavaDoc (template.getID ()), template);
433
434             } else {
435                 throw new JahiaTemplateNotFoundException (templateID);
436             }
437         }
438         return template;
439     }
440
441
442     public JahiaPageDefinition lookupPageTemplateByName (String JavaDoc name, int siteID)
443             throws JahiaException,
444             JahiaTemplateNotFoundException {
445         // check if the service is running
446
checkService ();
447
448         Object JavaDoc[] templates = templateCache.keys ();
449         for (int i = 0; i < templates.length; i++) {
450
451             JahiaPageDefinition template =
452                     (JahiaPageDefinition) templateCache.get (templates[i]);
453
454             if ((template.getName ().equals (name)) &&
455                     (template.getJahiaID () == siteID)) {
456                 return template;
457             }
458         }
459         throw new JahiaTemplateNotFoundException (name);
460     }
461
462
463     public synchronized void shutdown () {
464         //////////////////////////////////////////////////////////////////////////////////////
465
// FIXME -Fulco- :
466
// before shutting down the service, a check should be done to know
467
// if a page has an update-lock active. If any active update-lock is
468
// active, the system can not be shutdown !
469
// If the shutdown process can be forced, a message should indicate the editing
470
// user the service is in shutdown process, as soon as he does an action.
471
//////////////////////////////////////////////////////////////////////////////////////
472

473         if (isInitialized ()) {
474             templateCache.flush ();
475
476             // the service is not down!
477
mIsServiceInitialized = false;
478         }
479     }
480
481
482     // FH 2 May 2001
483
// javadocs automaticaly imported.
484
//
485
public int getNbPageTemplates ()
486             throws JahiaException {
487         return mTemplateDB.getNbPageTemplates (-1);
488     }
489
490
491     // NK 17 May 2001
492
// javadocs automaticaly imported.
493
//
494
public int getNbPageTemplates (int siteID)
495             throws JahiaException {
496         return mTemplateDB.getNbPageTemplates (siteID);
497     }
498
499
500     /**
501      * returns a DOM representation of all page def of a site
502      *
503      * @param siteID
504      */

505     public JahiaDOMObject getPageDefsAsDOM (int siteID) throws JahiaException {
506
507         return JahiaPageTemplateDB.getInstance ().getPageDefsAsDOM (siteID);
508
509     }
510
511     /**
512      * returns a DOM representation of all page def props of a site
513      *
514      * @param siteID
515      */

516     public JahiaDOMObject getPageDefPropsAsDOM (int siteID) throws JahiaException {
517
518         return JahiaPageDefinitionPropDB.getPageDefPropsAsDOM (siteID);
519
520     }
521
522     /**
523      * Returns a vector of all page templates' Acl ID of this site
524      * Need this for site extraction
525      *
526      * @param siteID
527      */

528     public Vector JavaDoc getAclIDs (int siteID)
529             throws JahiaException {
530         return JahiaPageDefinitionPropDB.db_get_all_acl_id (siteID);
531     }
532
533     // Patch ---------------------------------------------------
534
// 30.01.2002 : NK patch for old databases containing templates without ACL
535
// Do create ACL for them.
536
public final void patchTemplateWithoutACL () throws JahiaException {
537
538         JahiaSite site = null;
539         JahiaPageDefinition template = null;
540
541         Object JavaDoc[] ids = templateCache.keys ();
542         Integer JavaDoc I = null;
543         for (int i = 0; i < ids.length; i++) {
544             I = (Integer JavaDoc) ids[i];
545             template = (JahiaPageDefinition) templateCache.get (I);
546
547             if (template.getAclID () == -1) {
548                 site =
549                         ServicesRegistry.getInstance ().getJahiaSitesService ().getSite (
550                                 template.getJahiaID ());
551                 if (site != null) {
552                     // Create a new ACL.
553
JahiaBaseACL acl = new JahiaBaseACL ();
554                     if (acl != null) {
555                         try {
556                             acl.create (site.getAclID ());
557
558                             template.setACL (acl.getID ());
559
560                             // set the template default permissions
561
// enable guest users to view the template
562
JahiaACLEntry aclEntry = new JahiaACLEntry (1, 0);
563                             JahiaGroup guestGroup = ServicesRegistry.getInstance ()
564                                     .getJahiaGroupManagerService ()
565                                     .getGuestGroup (site.getID ());
566                             acl.setGroupEntry (guestGroup, aclEntry);
567
568                             template.commitChanges ();
569                             logger.debug ("Patch : ACL [" + template.getAclID () +
570                                     "] has been created for the template :" +
571                                     template.getName ());
572
573                         } catch (ACLNotFoundException ex) {
574                             logger.warn (ex);
575                             throw new JahiaException ("Could not patch ACL for the page def.",
576                                     "The parent ACL ID [" + site.getAclID () +
577                                     "] could not be found," +
578                                     " while trying to patch ACL ( create a new one ) for page def [" +
579                                     template.getID () + "]",
580                                     JahiaException.TEMPLATE_ERROR,
581                                     JahiaException.ERROR_SEVERITY);
582                         }
583                     } else {
584                         logger.debug ("Could not patch ACL for page def.");
585                     }
586                 }
587             }
588         }
589     }
590
591     // End Patch -----------------------------------------------
592

593
594     /**
595      * This method is called each time the cache flushes its items.
596      *
597      * @param cacheName the name of the cache which flushed its items.
598      */

599     public void onCacheFlush(String JavaDoc cacheName) {
600         try {
601             if (PAGE_TEMPLATE_CACHE.equals(cacheName)) {
602                 logger.debug("Page template cache has been flushed, reload the page templates!");
603                 templateCache.flush(false);
604                 loadAllPageTemplates();
605             }
606
607         } catch (JahiaException ex) {
608             logger.warn (ex);
609         }
610     }
611
612     public void onCachePut(String JavaDoc cacheName, Object JavaDoc entryKey) {
613         // do nothing;
614
}
615
616     /**
617      * Update page template in database and cache.
618      * @param thePageTemplate JahiaPageDefinition
619      * @throws JahiaException
620      */

621     public void updatePageTemplate(JahiaPageDefinition thePageTemplate)
622         throws JahiaException {
623         mTemplateDB.updatePageTemplate(thePageTemplate);
624         templateCache.put(new Integer JavaDoc(thePageTemplate.getID()), thePageTemplate);
625     }
626
627 }
628
629
630
631
632
Popular Tags