View Javadoc

1   /**
2    * This file Copyright (c) 2008-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.rendering.renderer;
35  
36  import info.magnolia.cms.core.AggregationState;
37  import info.magnolia.context.MgnlContext;
38  import info.magnolia.jcr.decoration.ContentDecoratorUtil;
39  import info.magnolia.jcr.util.ContentMap;
40  import info.magnolia.jcr.util.NodeUtil;
41  import info.magnolia.jcr.wrapper.ChannelVisibilityContentDecorator;
42  import info.magnolia.jcr.wrapper.HTMLEscapingNodeWrapper;
43  import info.magnolia.jcr.wrapper.I18nNodeWrapper;
44  import info.magnolia.objectfactory.Components;
45  import info.magnolia.objectfactory.MgnlInstantiationException;
46  import info.magnolia.objectfactory.ParameterInfo;
47  import info.magnolia.objectfactory.ParameterResolver;
48  import info.magnolia.rendering.context.RenderingContext;
49  import info.magnolia.rendering.engine.RenderException;
50  import info.magnolia.rendering.engine.RenderingEngine;
51  import info.magnolia.rendering.model.EarlyExecutionAware;
52  import info.magnolia.rendering.model.ModelExecutionFilter;
53  import info.magnolia.rendering.model.RenderingModel;
54  import info.magnolia.rendering.model.RenderingModelImpl;
55  import info.magnolia.rendering.template.RenderableDefinition;
56  
57  import java.lang.reflect.InvocationTargetException;
58  import java.util.HashMap;
59  import java.util.Map;
60  import java.util.Map.Entry;
61  
62  import javax.inject.Inject;
63  import javax.jcr.Node;
64  import javax.jcr.RepositoryException;
65  
66  import org.apache.commons.beanutils.BeanUtils;
67  import org.apache.commons.lang.StringUtils;
68  import org.apache.commons.lang.exception.ExceptionUtils;
69  
70  /**
71   * Abstract renderer with support for typical functionality such as setting context attributes and executing a
72   * rendering model. Sets up the context by providing the following objects:
73   * <ul>
74   * <li>content</li>
75   * <li>def</li>
76   * <li>state</li>
77   * <li>model</li>
78   * <li>actionResult</li>
79   * </ul>
80   */
81  public abstract class AbstractRenderer implements Renderer, RenderingModelBasedRenderer {
82  
83      protected static final String MODEL_ATTRIBUTE = RenderingModel.class.getName();
84  
85      private Map<String, ContextAttributeConfiguration> contextAttributes = new HashMap<String, ContextAttributeConfiguration>();
86  
87      private RenderingEngine renderingEngine = null;
88  
89      /**
90       * @deprecated since 5.0.2, use {@link #AbstractRenderer(RenderingEngine)}
91       */
92      public AbstractRenderer() {
93          this.renderingEngine = Components.getComponent(RenderingEngine.class);
94      }
95  
96      @Inject
97      public AbstractRenderer(RenderingEngine renderingEngine) {
98          this.renderingEngine = renderingEngine;
99      }
100 
101     @Override
102     public void render(RenderingContext renderingCtx, Map<String, Object> contextObjects) throws RenderException {
103 
104         final RenderingModel<?> parentModel = MgnlContext.getAttribute(MODEL_ATTRIBUTE);
105         Node content = renderingCtx.getCurrentContent();
106         RenderableDefinition definition = renderingCtx.getRenderableDefinition();
107 
108         RenderingModel<?> model = null;
109         String actionResult = null;
110 
111         if (content != null) {
112             String uuid;
113             try {
114                 uuid = content.getIdentifier();
115             } catch (RepositoryException e) {
116                 throw new RenderException(e);
117             }
118 
119             model = MgnlContext.getAttribute(ModelExecutionFilter.MODEL_ATTRIBUTE_PREFIX + uuid);
120             if (model != null) {
121                 actionResult = (String) MgnlContext.getAttribute(ModelExecutionFilter.ACTION_RESULT_ATTRIBUTE_PREFIX + uuid);
122                 if (model instanceof EarlyExecutionAware) {
123                     ((EarlyExecutionAware) model).setParent(parentModel);
124                 }
125             }
126         }
127 
128         if (model == null) {
129             model = newModel(content, definition, parentModel);
130             if (model != null) {
131                 actionResult = model.execute();
132                 if (RenderingModel.SKIP_RENDERING.equals(actionResult)) {
133                     return;
134                 }
135             }
136         }
137 
138         String templatePath = resolveTemplateScript(content, definition, model, actionResult);
139         if (templatePath == null) {
140             throw new RenderException("No template script defined for the template definition [" + definition + "]");
141         }
142 
143         final Map<String, Object> ctx = newContext();
144         final Map<String, Object> savedContextState = saveContextState(ctx);
145         setupContext(ctx, content, definition, model, actionResult);
146         ctx.putAll(contextObjects);
147         MgnlContext.setAttribute(MODEL_ATTRIBUTE, model);
148         content = wrapNodeForModel(content);
149         renderingCtx.push(content, definition);
150         try {
151             onRender(content, definition, renderingCtx, ctx, templatePath);
152         } finally {
153             renderingCtx.pop();
154         }
155         MgnlContext.setAttribute(MODEL_ATTRIBUTE, parentModel);
156 
157         restoreContext(ctx, savedContextState);
158     }
159 
160     /**
161      * Hook-method to be overriden when required. Default implementation ignores all arguments except definition.
162      * 
163      * @param definition reference templateScript is retrieved from
164      * @return the templateScript to use
165      */
166     protected String resolveTemplateScript(Node content, RenderableDefinition definition, RenderingModel<?> model, final String actionResult) {
167         return definition.getTemplateScript();
168     }
169 
170     /**
171      * Instantiates the model based on the class defined by the {@link info.magnolia.rendering.template.RenderableDefinition#getModelClass()} property. All the request
172      * parameters are then mapped to the model's properties.
173      */
174     @Override
175     public RenderingModel<?> newModel(final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel) throws RenderException {
176 
177         Class clazz = definition.getModelClass();
178 
179         // if none is set we default to RenderingModelImpl, so there will always be a model available in templates
180         if (clazz == null) {
181             clazz = RenderingModelImpl.class;
182         }
183 
184         final Node wrappedContent = wrapNodeForModel(content);
185 
186         return newModel(clazz, wrappedContent, definition, parentModel);
187     }
188 
189     protected <T extends RenderingModel<?>> T newModel(Class<T> modelClass, final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel) throws RenderException {
190 
191         try {
192 
193             T model = Components.getComponentProvider().newInstanceWithParameterResolvers(modelClass,
194                     new ParameterResolver() {
195                         @Override
196                         public Object resolveParameter(ParameterInfo parameter) {
197                             if (parameter.getParameterType().equals(Node.class)) {
198                                 return content;
199                             }
200                             if (parameter.getParameterType().isAssignableFrom(definition.getClass())) {
201                                 return definition;
202                             }
203                             if (parameter.getParameterType().equals(RenderingModel.class)) {
204                                 return parentModel;
205                             }
206                             return UNRESOLVED;
207                         }
208                     }
209                     );
210 
211             // populate the instance with values given as request parameters
212             final boolean autoPopulateFromRequest = definition.getAutoPopulateFromRequest() != null ? definition.getAutoPopulateFromRequest() : renderingEngine.getAutoPopulateFromRequest();
213             if (!autoPopulateFromRequest) {
214                 return model;
215             }
216 
217             Map<String, String[]> params = MgnlContext.getWebContext().getRequest().getParameterMap();
218             if (params == null || params.isEmpty()) {
219                 return model;
220             }
221 
222             // needed workaround to not break rendering when there is no index between square brackets
223             // see https://issues.apache.org/jira/browse/BEANUTILS-419
224             Map<String, Object> filtered = new HashMap<String, Object>();
225             for (Entry<String, String[]> entry : params.entrySet()) {
226                 String key = entry.getKey();
227                 String[] value = entry.getValue();
228                 if (StringUtils.contains(key, "[")) {
229                     key = StringUtils.substringBefore(key, "[");
230                 }
231                 filtered.put(key, value);
232             }
233 
234             BeanUtils.populate(model, filtered);
235 
236             return model;
237 
238         } catch (MgnlInstantiationException e) {
239             throw new RenderException("Can't instantiate model: " + modelClass, e);
240         } catch (InvocationTargetException e) {
241             throw new RenderException("Can't populate rendering model: " + ExceptionUtils.getRootCauseMessage(e), e);
242         } catch (IllegalAccessException e) {
243             throw new RenderException("Can't populate rendering model: " + ExceptionUtils.getRootCauseMessage(e), e);
244         }
245     }
246 
247     protected Map<String, Object> saveContextState(final Map<String, Object> ctx) {
248         Map<String, Object> state = new HashMap<String, Object>();
249         // save former values
250         saveAttribute(ctx, state, "content");
251         saveAttribute(ctx, state, "def");
252         saveAttribute(ctx, state, "state");
253         saveAttribute(ctx, state, "model");
254         saveAttribute(ctx, state, "actionResult");
255 
256         return state;
257     }
258 
259     protected void saveAttribute(final Map<String, Object> ctx, Map<String, Object> state, String name) {
260         state.put(name, ctx.get(name));
261     }
262 
263     protected void restoreContext(final Map<String, Object> ctx, Map<String, Object> state) {
264         for (Entry<String, Object> entry : state.entrySet()) {
265             setContextAttribute(ctx, entry.getKey(), entry.getValue());
266         }
267     }
268 
269     protected void setupContext(final Map<String, Object> ctx, Node content, RenderableDefinition definition, RenderingModel<?> model, Object actionResult) {
270         final Node mainContent = getMainContentSafely(content);
271 
272         setContextAttribute(ctx, "content", content != null ? new ContentMap(wrapNodeForTemplate(content)) : null);
273         setContextAttribute(ctx, "def", definition);
274         setContextAttribute(ctx, "state", getAggregationStateSafely());
275         setContextAttribute(ctx, "model", model);
276         setContextAttribute(ctx, "actionResult", actionResult);
277 
278         for (Entry<String, ContextAttributeConfiguration> entry : contextAttributes.entrySet()) {
279             setContextAttribute(ctx, entry.getKey(), Components.getComponent(entry.getValue().getComponentClass()));
280         }
281 
282     }
283 
284     /**
285      * Gets the current main content or returns null if aggregation state is not set.
286      */
287     protected Node getMainContentSafely(Node content) {
288         AggregationState state = getAggregationStateSafely();
289         return state == null ? content : state.getMainContentNode();
290     }
291 
292     /**
293      * This gets the aggregation state without throwing an exception if the current context is not a WebContext.
294      */
295     protected AggregationState getAggregationStateSafely() {
296         if (MgnlContext.isWebContext()) {
297             return MgnlContext.getAggregationState();
298         }
299         return null;
300     }
301 
302     /**
303      * Wraps the current content node before passing it to the model.
304      * 
305      * @param content the actual content
306      * @return the wrapped content
307      */
308     protected Node wrapNodeForModel(Node content) {
309         NodeUtil.deepUnwrap(content, HTMLEscapingNodeWrapper.class);
310         content = wrapWithChannelVisibilityWrapper(content);
311         content = wrapWithI18NWrapper(content);
312         return content;
313     }
314 
315     /**
316      * Wraps the current content node for exposing it to the template script as a context attribute.
317      * 
318      * @param content the actual content
319      * @return the wrapped content
320      */
321     protected Node wrapNodeForTemplate(Node content) {
322         content = wrapWithChannelVisibilityWrapper(content);
323         content = wrapWithI18NWrapper(content);
324         content = wrapWithHTMLEscapingWrapper(content);
325         return content;
326     }
327 
328     private Node wrapWithHTMLEscapingWrapper(Node content) {
329         if (!NodeUtil.isWrappedWith(content, HTMLEscapingNodeWrapper.class)) {
330             content = new HTMLEscapingNodeWrapper(content, true);
331         }
332         return content;
333     }
334 
335     private Node wrapWithI18NWrapper(Node content) {
336         if (!NodeUtil.isWrappedWith(content, I18nNodeWrapper.class)) {
337             content = new I18nNodeWrapper(content);
338         }
339         return content;
340     }
341 
342     private Node wrapWithChannelVisibilityWrapper(Node content) {
343         // If it's already wrapped then we don't need to add a new one
344         if (ContentDecoratorUtil.isDecoratedWith(content, ChannelVisibilityContentDecorator.class)) {
345             return content;
346         }
347         AggregationState aggregationState = getAggregationStateSafely();
348         if (aggregationState == null) {
349             return content;
350         }
351         String channel = aggregationState.getChannel().getName();
352         if (StringUtils.isEmpty(channel) || channel.equalsIgnoreCase("all")) {
353             return content;
354         }
355         return new ChannelVisibilityContentDecorator(channel).wrapNode(content);
356     }
357 
358     protected Object setContextAttribute(final Map<String, Object> ctx, final String name, Object value) {
359         return ctx.put(name, value);
360     }
361 
362     public Map<String, ContextAttributeConfiguration> getContextAttributes() {
363         return contextAttributes;
364     }
365 
366     public void setContextAttributes(Map<String, ContextAttributeConfiguration> contextAttributes) {
367         if (this.contextAttributes != null) {
368             this.contextAttributes.putAll(contextAttributes);
369         } else {
370             this.contextAttributes = contextAttributes;
371         }
372     }
373 
374     public void addContextAttribute(String name, ContextAttributeConfiguration contextAttributeConfiguration) {
375         this.contextAttributes.put(name, contextAttributeConfiguration);
376     }
377 
378     /**
379      * Create a new context object which is a map.
380      */
381     protected abstract Map<String, Object> newContext();
382 
383     /**
384      * Finally execute the rendering.
385      */
386     protected abstract void onRender(Node content, RenderableDefinition definition, RenderingContext renderingCtx, Map<String, Object> ctx, String templateScript) throws RenderException;
387 
388 }