View Javadoc

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