View Javadoc
1   /**
2    * This file Copyright (c) 2011-2018 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.templating.elements;
35  
36  import info.magnolia.cms.beans.config.ServerConfiguration;
37  import info.magnolia.context.MgnlContext;
38  import info.magnolia.context.WebContext;
39  import info.magnolia.i18nsystem.I18nizer;
40  import info.magnolia.i18nsystem.LocaleProvider;
41  import info.magnolia.i18nsystem.TranslationService;
42  import info.magnolia.jcr.util.NodeTypes;
43  import info.magnolia.objectfactory.Components;
44  import info.magnolia.rendering.context.RenderingContext;
45  import info.magnolia.rendering.engine.RenderException;
46  
47  import java.util.HashMap;
48  import java.util.Map;
49  import java.util.Map.Entry;
50  
51  import javax.jcr.Node;
52  import javax.jcr.RepositoryException;
53  
54  import org.apache.commons.lang3.StringUtils;
55  
56  /**
57   * Abstract base class for elements that operate on a specified piece of content.
58   */
59  public abstract class AbstractContentTemplatingElement extends AbstractTemplatingElement {
60  
61      // TODO should also support a JSP ContentMap
62      private Node content;
63      private String workspace;
64      private String nodeIdentifier;
65      private String path;
66      private final Map<String, Object> savedCtxAttributes = new HashMap<String, Object>();
67  
68      private final I18nizer i18nizer;
69  
70      public AbstractContentTemplatingElement(ServerConfiguration server, RenderingContext renderingContext, I18nizer i18nizer) {
71          super(server, renderingContext);
72          this.i18nizer = i18nizer;
73      }
74  
75      /**
76       * @deprecated since 5.4.4. Use {@link #AbstractContentTemplatingElement(info.magnolia.cms.beans.config.ServerConfiguration, info.magnolia.rendering.context.RenderingContext, info.magnolia.i18nsystem.I18nizer)} instead.
77       */
78      @Deprecated
79      public AbstractContentTemplatingElement(ServerConfiguration server, RenderingContext renderingContext) {
80          this(server, renderingContext, Components.getComponent(I18nizer.class));
81      }
82  
83      protected <D> D i18nize(D renderableDefinition) {
84          return i18nizer.decorate(renderableDefinition);
85      }
86  
87      /**
88       * @deprecated since 5.4.4. The support for i18nBasename will be removed in a future version.
89       */
90      @Deprecated
91      protected String legacyTranslate(String keyOrAlreadyTranslatedValue, String i18nBasename) {
92          if (isMessageKey(keyOrAlreadyTranslatedValue)) {
93              return Components.getComponent(TranslationService.class).translate(Components.getComponent(LocaleProvider.class), i18nBasename, new String[]{keyOrAlreadyTranslatedValue});
94          } else {
95              return keyOrAlreadyTranslatedValue;
96          }
97      }
98  
99      protected boolean isMessageKey(String key) {
100         return !StringUtils.endsWith(key, ".") && StringUtils.contains(key, ".") && !StringUtils.contains(key, " ");
101     }
102 
103     protected String getNodePath(Node node) throws RenderException {
104         try {
105             return node.getSession().getWorkspace().getName() + ":" + node.getPath();
106         } catch (RepositoryException e) {
107             throw new RenderException("Can't construct node path for node " + node);
108         }
109     }
110 
111     /**
112      * Returns the content passed to the element (content or workspace/path attribute) or null if nothing was passed.
113      */
114     protected Node getPassedContent() throws RenderException {
115 
116         // TODO should we default workspace to 'website' ?
117         // TODO should we be strict and fail on invalid combinations ?
118 
119         // TODO we can safely keep the node around after we've resolved it
120 
121         if (content != null) {
122             return content;
123         }
124         if (StringUtils.isNotEmpty(workspace)) {
125             if (StringUtils.isNotEmpty(nodeIdentifier)) {
126                 try {
127                     return MgnlContext.getJCRSession(workspace).getNodeByIdentifier(nodeIdentifier);
128                 } catch (RepositoryException e) {
129                     throw new RenderException("Can't read content from workspace [" + workspace + "] with identifier [" + nodeIdentifier + "].");
130                 }
131             }
132             if (StringUtils.isNotEmpty(path)) {
133                 try {
134                     return MgnlContext.getJCRSession(workspace).getNode(path);
135                 } catch (RepositoryException e) {
136                     throw new RenderException("Can't read content from workspace [" + workspace + "] with path [" + path + "].");
137                 }
138             }
139             throw new IllegalArgumentException("Need to specify either uuid or path in combination with workspace");
140         }
141 
142         return null;
143     }
144 
145     public Node getContent() {
146         return content;
147     }
148 
149     public void setContent(Node node) {
150         this.content = node;
151     }
152 
153     public String getWorkspace() {
154         return workspace;
155     }
156 
157     public void setWorkspace(String workspace) {
158         this.workspace = workspace;
159     }
160 
161     public String getNodeIdentifier() {
162         return nodeIdentifier;
163     }
164 
165     public void setNodeIdentifier(String nodeIdentifier) {
166         this.nodeIdentifier = nodeIdentifier;
167     }
168 
169     public String getPath() {
170         return path;
171     }
172 
173     public void setPath(String path) {
174         this.path = path;
175     }
176 
177     /**
178      * Sets attributes in web context under the specified scope. If an attribute already exists its value will be overwritten
179      * with the new one and the old value saved for subsequent restore.
180      *
181      * @param scope one of {@link info.magnolia.context.Context#APPLICATION_SCOPE} {@link info.magnolia.context.Context#SESSION_SCOPE} {@link info.magnolia.context.Context#LOCAL_SCOPE}.
182      */
183     protected void setAttributesInWebContext(final Map<String, Object> attributes, int scope) {
184         if (attributes == null) {
185             return;
186         }
187         switch (scope) {
188         case WebContext.APPLICATION_SCOPE:
189         case WebContext.SESSION_SCOPE:
190         case WebContext.LOCAL_SCOPE:
191             break;
192         default:
193             throw new IllegalArgumentException("Scope is not valid. Use one of the scopes defined in info.magnolia.context.WebContext");
194         }
195         final WebContext webContext = MgnlContext.getWebContext();
196         for (Entry<String, Object> entry : attributes.entrySet()) {
197             final String key = entry.getKey();
198             if (webContext.containsKey(key)) {
199                 savedCtxAttributes.put(key, webContext.get(key));
200             }
201             webContext.setAttribute(key, entry.getValue(), scope);
202         }
203     }
204 
205     /**
206      * Restores the original values of attributes in web context under the specified scope.
207      *
208      * @param scope one of {@link info.magnolia.context.Context#APPLICATION_SCOPE} {@link info.magnolia.context.Context#SESSION_SCOPE} {@link info.magnolia.context.Context#LOCAL_SCOPE}.
209      */
210     protected void restoreAttributesInWebContext(final Map<String, Object> attributes, int scope) {
211         if (attributes == null) {
212             return;
213         }
214         switch (scope) {
215         case WebContext.APPLICATION_SCOPE:
216         case WebContext.SESSION_SCOPE:
217         case WebContext.LOCAL_SCOPE:
218             break;
219         default:
220             throw new IllegalArgumentException("Scope is not valid. Use one of the scopes defined in info.magnolia.context.WebContext");
221         }
222         final WebContext webContext = MgnlContext.getWebContext();
223 
224         for (Entry<String, Object> entry : attributes.entrySet()) {
225             final String key = entry.getKey();
226             if (webContext.containsKey(key) && savedCtxAttributes.get(key) != null) {
227                 webContext.setAttribute(key, savedCtxAttributes.get(key), scope);
228                 continue;
229             }
230             webContext.removeAttribute(key, scope);
231         }
232     }
233 
234     /**
235      * Override to set conditions for rendering of cms:comments.
236      */
237     protected boolean renderComments() {
238         return isAdmin();
239     }
240 
241     protected String getActivationStatus(Node node) {
242         int status = NodeTypes.Activatable.ACTIVATION_STATUS_NOT_ACTIVATED;
243 
244         if (node != null) {
245             try {
246                 status = NodeTypes.Activatable.getActivationStatus(node);
247             } catch (RepositoryException e) {
248                 // page has no activation status
249             }
250         }
251         return String.valueOf(status);
252     }
253 }