View Javadoc

1   /**
2    * This file Copyright (c) 2003-2014 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.freemarker.models;
35  
36  import info.magnolia.context.Context;
37  import info.magnolia.freemarker.FreemarkerConfig;
38  import info.magnolia.jcr.util.ContentMap;
39  
40  import java.util.ArrayList;
41  import java.util.Calendar;
42  import java.util.List;
43  
44  import freemarker.ext.util.ModelFactory;
45  import freemarker.template.DefaultObjectWrapper;
46  import freemarker.template.SimpleDate;
47  import freemarker.template.TemplateDateModel;
48  import freemarker.template.TemplateModel;
49  import freemarker.template.TemplateModelException;
50  
51  /**
52   * A FreeMarker ObjectWrapper that knows about Magnolia specific objects.
53   *
54   * @author Chris Miner
55   * @author gjoseph
56   * @version $Revision: $ ($Author: $)
57   */
58  public class MagnoliaObjectWrapper extends DefaultObjectWrapper {
59      private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MagnoliaObjectWrapper.class);
60  
61      private final static List<MagnoliaModelFactory> DEFAULT_MODEL_FACTORIES = new ArrayList<MagnoliaModelFactory>() {{
62          add(NodeDataModelFactory.INSTANCE);
63          add(ContentModel.FACTORY);
64          add(ContentMapModel.FACTORY);
65          add(CalendarModel.FACTORY);
66          add(UserModel.FACTORY);
67          add(ContextModelFactory.INSTANCE);
68      }};
69  
70      private final FreemarkerConfig freemarkerConfig;
71  
72      public MagnoliaObjectWrapper(FreemarkerConfig freemarkerConfig) {
73          super();
74          this.freemarkerConfig = freemarkerConfig;
75      }
76  
77      /**
78       * Unwraps our custom wrappers, let the default wrapper do the rest.
79       */
80      @Override
81      public Object unwrap(TemplateModel model, Class hint) throws TemplateModelException {
82          // all our models implement either AdapterTemplateModel or a already handled by super.unwrap() (boolean, string, ..)
83          return super.unwrap(model, hint);
84      }
85  
86      @Override
87      public TemplateModel wrap(Object obj) throws TemplateModelException {
88          if (obj instanceof Context) {
89              // bypass the default SimpleHash wrapping, we need a MapModel.
90              // handleUnknownType() will relay to our ContextModelFactory.
91              return handleUnknownType(obj);
92          }
93  
94          // wrap enums
95          // can't do this later, as the Class instance passed to getModelFactory() lost the information about its enum.
96          if (obj != null && (obj instanceof Class) && ((Class) obj).isEnum()) {
97              final String enumClassName = ((Class) obj).getName();
98              return getEnumModels().get(enumClassName);
99          }
100 
101         // since we implement Map FM will always try to use SimpleHash if passed through
102         if (obj != null && (obj instanceof ContentMap)) {
103             return handleUnknownType(obj);
104         }
105         return super.wrap(obj);
106     }
107 
108     /**
109      * Checks the ModelFactory instances registered in FreemarkerConfig, then
110      * the default ones. If no appropriate ModelFactory was found, delegates to
111      * Freemarker's implementation. This is called by {@link freemarker.ext.beans.BeansModelCache},
112      * which is itself called by {@link freemarker.ext.beans.BeansWrapper#wrap}.
113      * These factories are cached by Freemarker, so this method only gets called
114      * once per type of object.
115      *
116      * @see #DEFAULT_MODEL_FACTORIES
117      * @see info.magnolia.freemarker.FreemarkerConfig
118      */
119     @Override
120     protected ModelFactory getModelFactory(Class clazz) {
121         final List<MagnoliaModelFactory> registeredModelFactories = freemarkerConfig.getModelFactories();
122         ModelFactory modelFactory = getModelFactory(clazz, registeredModelFactories);
123 
124         if (modelFactory == null) {
125             modelFactory = getModelFactory(clazz, DEFAULT_MODEL_FACTORIES);
126         }
127         if (modelFactory == null) {
128             modelFactory = super.getModelFactory(clazz);
129         }
130         return modelFactory;
131     }
132 
133     private ModelFactory getModelFactory(Class clazz, List<MagnoliaModelFactory> factories) {
134         for (MagnoliaModelFactory factory : factories) {
135             if (factory.factoryFor().isAssignableFrom(clazz)) {
136                 return factory;
137             }
138         }
139         return null;
140     }
141 
142     /**
143      * Exposes a Calendar as a SimpleDate.
144      * @deprecated since 4.3 use CalendarModel instead.
145      */
146     @Deprecated
147     protected SimpleDate handleCalendar(Calendar cal) {
148         return new SimpleDate(cal.getTime(), TemplateDateModel.DATETIME);
149     }
150 
151 }