View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.templating;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.ItemType;
38  import info.magnolia.cms.beans.config.ObservedManager;
39  import info.magnolia.content2bean.Content2BeanException;
40  import info.magnolia.content2bean.Content2BeanUtil;
41  import info.magnolia.objectfactory.Components;
42  
43  import javax.jcr.RepositoryException;
44  import java.util.ArrayList;
45  import java.util.Collection;
46  import java.util.Hashtable;
47  import java.util.Iterator;
48  import java.util.List;
49  import java.util.Map;
50  
51  
52  /**
53   * Manages the templates of the system
54   * @author philipp
55   */
56  public class TemplateManager extends ObservedManager {
57  
58      /**
59       * The cached templates
60       */
61      private Map<String, Template> cachedContent = new Hashtable<String, Template>();
62  
63      /**
64       * The templates visible in the templates selection
65       */
66      private List<Template> visibleTemplates = new ArrayList<Template>();
67  
68      /**
69       * Called by the ObservedManager
70       */
71      protected void onRegister(Content node) {
72          try {
73              log.info("Loading Template info from {}", node.getHandle()); //$NON-NLS-1$
74  
75              // It makes possibly to use templates defined within subfolders of /module/templating/Templates
76              Collection<Content> children = collectChildren(node);
77  
78              if ((children != null) && !(children.isEmpty())) {
79                  Iterator<Content> templates = children.iterator();
80                  cacheContent(templates);
81              }
82  
83              log.debug("Template info loaded from {}", node.getHandle()); //$NON-NLS-1$
84          }
85          catch (Exception re) {
86              log.error("Failed to load Template info from " + node.getHandle() + ": " + re.getMessage(), re);
87          }
88  
89      }
90  
91      protected void onClear() {
92          this.cachedContent.clear();
93          this.visibleTemplates.clear();
94      }
95  
96      /**
97       * Returns the cached content of the requested template. TemplateInfo properties:
98       * <ol>
99       * <li> title - title describing template</li>
100      * <li> type - jsp / servlet</li>
101      * <li> path - jsp / servlet path</li>
102      * <li> description - description of a template</li>
103      * </ol>
104      * @return TemplateInfo
105      * @deprecated since 4.0 Use {@link #getTemplateDefinition(String)} instead
106      */
107     public Template getInfo(String key) {
108         return getTemplateDefinition(key);
109     }
110 
111     /**
112      * Returns the cached content of the requested template. TemplateInfo properties:
113      * <ol>
114      * <li> title - title describing template</li>
115      * <li> type - jsp / servlet</li>
116      * <li> path - jsp / servlet path</li>
117      * <li> description - description of a template</li>
118      * </ol>
119      * @return TemplateInfo
120      */
121     public Template getTemplateDefinition(String key) {
122         return cachedContent.get(key);
123     }
124 
125     /**
126      * Returns the cached content of the requested template. TemplateInfo properties:
127      * <ol>
128      * <li> title - title describing template</li>
129      * <li> type - jsp / servlet</li>
130      * <li> path - jsp / servlet path</li>
131      * <li> description - description of a template</li>
132      * </ol>
133      * @return TemplateInfo
134      */
135     public Template getInfo(String key, String extension) {
136         Template template = cachedContent.get(key);
137 
138         if (template == null) {
139             return null;
140         }
141         Template subtemplate = template.getSubTemplate(extension);
142         if (subtemplate != null) {
143             return subtemplate;
144         }
145 
146         return template;
147     }
148 
149     /**
150      * Adds templates definition to TemplatesInfo cache.
151      * @param templates iterator as read from the repository
152      * @param visibleTemplates List in with all visible templates will be added
153      */
154     private void addTemplatesToCache(Iterator<Content> templates, List<Template> visibleTemplates) {
155         while (templates.hasNext()) {
156             Content c = templates.next();
157 
158             try {
159                 Template ti = (Template) Content2BeanUtil.toBean(c, true, Template.class);
160                 cachedContent.put(ti.getName(), ti);
161                 if (ti.isVisible()) {
162                     visibleTemplates.add(ti);
163                 }
164 
165                 log.debug("Registering template [{}]", ti.getName());
166             }
167             catch (Content2BeanException e) {
168                 log.error("Can't register template ["+c.getName()+"]",e);
169             }
170 
171         }
172     }
173 
174     /**
175      * Load content of this template info page in a hash table caching at the system load, this will save lot of time on
176      * every request while matching template info.
177      */
178     private void cacheContent(Iterator<Content> templates) {
179         if (templates != null) {
180             addTemplatesToCache(templates, visibleTemplates);
181         }
182     }
183 
184     /**
185      * Recursive search for content nodes contains template data (looks up subfolders)
186      * @author <a href="mailto:tm@touk.pl">Tomasz Mazan</a>
187      * @param cnt current folder to look for template's nodes
188      * @return collection of template's content nodes from current folder and descendants
189      */
190     private Collection<Content> collectChildren(Content cnt) {
191         // Collect template's content node - children of current node
192         Collection<Content> children = cnt.getChildren(ItemType.CONTENTNODE);
193 
194         // Look into subfolders
195         Collection<Content> subFolders = cnt.getChildren(ItemType.CONTENT);
196         if ((subFolders != null) && !(subFolders.isEmpty())) {
197 
198             for (Content subCnt : subFolders) {
199                 Collection<Content> grandChildren = collectChildren(subCnt);
200 
201                 if ((grandChildren != null) && !(grandChildren.isEmpty())) {
202                     children.addAll(grandChildren);
203                 }
204             }
205 
206         }
207 
208         return children;
209     }
210 
211     public Iterator<Template> getAvailableTemplates(Content node) {
212         List<Template> templateList = new ArrayList<Template>();
213         for (Template template : visibleTemplates) {
214             
215             if (template.isAvailable(node)) {
216                 templateList.add(template);
217             }
218         }
219         return templateList.iterator();
220     }
221 
222     /**
223      * Get templates collection.
224      * @return Collection list containing templates as Template objects
225      */
226     public Iterator<Template> getAvailableTemplates() {
227         return visibleTemplates.iterator();
228     }
229 
230     public Template getDefaultTemplate(Content node) {
231         Template tmpl;
232         try {
233             // try to use the same as the parent
234             tmpl = this.getTemplateDefinition(node.getParent().getTemplate());
235             if(tmpl != null && tmpl.isAvailable(node)){
236                 return tmpl;
237             }
238             // otherwise use the first available template
239             else{
240                 Iterator<Template> templates = getAvailableTemplates(node);
241                 if (templates.hasNext()) {
242                     return templates.next();
243                 }
244             }
245         }
246         catch (RepositoryException e) {
247             log.error("Can't resolve default template for node " + node.getHandle(), e);
248         }
249         return null;
250     }
251 
252     /**
253      * @return Returns the instance.
254      */
255     public static TemplateManager getInstance() {
256         return Components.getSingleton(TemplateManager.class);
257     }
258 
259 }