View Javadoc
1   /**
2    * This file Copyright (c) 2010-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.jcr.util;
35  
36  import info.magnolia.link.LinkException;
37  import info.magnolia.link.LinkUtil;
38  
39  import java.lang.reflect.Method;
40  import java.util.Collection;
41  import java.util.HashMap;
42  import java.util.LinkedHashSet;
43  import java.util.Map;
44  import java.util.Set;
45  
46  import javax.jcr.Node;
47  import javax.jcr.PathNotFoundException;
48  import javax.jcr.Property;
49  import javax.jcr.PropertyIterator;
50  import javax.jcr.PropertyType;
51  import javax.jcr.RepositoryException;
52  import javax.jcr.Value;
53  
54  import org.apache.commons.lang3.StringUtils;
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  /**
59   * Map based representation of JCR content. This class is for instance used in template scripts to allow notations like <code>content.propName</code>. It first tries to read a property with name (key) and if not present checks for the
60   * presence of child node. Few special property names map to the JCR methods: \@name, \@id, \@path, \@level, \@nodeType
61   */
62  public class ContentMap implements Map<String, Object> {
63  
64      private final static Logger log = LoggerFactory.getLogger(ContentMap.class);
65  
66      private final Node content;
67  
68      /**
69       * Represents getters of the node itself.
70       */
71      private final Map<String, Method> specialProperties = new HashMap<String, Method>();
72  
73      public ContentMap(Node content) {
74          if (content == null) {
75              throw new NullPointerException("ContentMap doesn't accept null content");
76          }
77  
78          this.content = content;
79  
80          // Supported special types are: @nodeType @name, @path @depth (and their deprecated forms - see
81          // convertDeprecatedProps() for details)
82          Class<? extends Node> clazz = content.getClass();
83          try {
84              specialProperties.put("name", clazz.getMethod("getName", (Class<?>[]) null));
85              specialProperties.put("id", clazz.getMethod("getIdentifier", (Class<?>[]) null));
86              specialProperties.put("path", clazz.getMethod("getPath", (Class<?>[]) null));
87              specialProperties.put("depth", clazz.getMethod("getDepth", (Class<?>[]) null));
88              specialProperties.put("nodeType", clazz.getMethod("getPrimaryNodeType", (Class<?>[]) null));
89          } catch (SecurityException e) {
90              log.debug("Failed to gain access to Node get***() method. Check VM security settings. {}", e.getLocalizedMessage(), e);
91          } catch (NoSuchMethodException e) {
92              log.debug("Failed to retrieve get***() method of Node class. Check the classpath for conflicting version of JCR classes. {}", e.getLocalizedMessage(), e);
93          }
94      }
95  
96      @Override
97      public boolean containsKey(Object key) {
98  
99          String strKey = convertKey(key);
100 
101         if (!isValidKey(strKey)) {
102             return false;
103         }
104 
105         if (isSpecialProperty(strKey)) {
106             return true;
107         }
108 
109         try {
110             return content.hasProperty(strKey);
111         } catch (RepositoryException e) {
112             // ignore, most likely invalid name
113         }
114         return false;
115     }
116 
117     private String convertKey(Object key) {
118         if (key == null) {
119             return null;
120         }
121         try {
122             return (String) key;
123         } catch (ClassCastException e) {
124             log.debug("Invalid key. Expected String, but got {}.", key.getClass().getName());
125         }
126         return null;
127     }
128 
129     private boolean isValidKey(String strKey) {
130         return !StringUtils.isBlank(strKey);
131     }
132 
133     public boolean isSpecialProperty(String strKey) {
134         if (!strKey.startsWith("@")) {
135             return false;
136         }
137         strKey = convertDeprecatedProps(strKey);
138         return specialProperties.containsKey(StringUtils.removeStart(strKey, "@"));
139     }
140 
141     /**
142      * @return a property name - in case the one handed in is known to be deprecated it'll be converted, else the
143      *         original one is returned.
144      */
145     private String convertDeprecatedProps(String strKey) {
146         // in the past we allowed both lower and upper case notation ...
147         if ("@UUID".equals(strKey) || "@uuid".equals(strKey)) {
148             return "@id";
149         } else if ("@handle".equals(strKey)) {
150             return "@path";
151         } else if ("@level".equals(strKey)) {
152             return "@depth";
153         }
154         return strKey;
155     }
156 
157     @Override
158     public Object get(Object key) {
159         String keyStr;
160         try {
161             keyStr = (String) key;
162         } catch (ClassCastException e) {
163             throw new ClassCastException("ContentMap accepts only String as a parameters, provided object was of type "
164                     + (key == null ? "null" : key.getClass().getName()));
165         }
166 
167         Object prop = getNodeProperty(keyStr);
168         if (prop == null) {
169             keyStr = convertDeprecatedProps(keyStr);
170             return getSpecialProperty(keyStr);
171         }
172         return prop;
173     }
174 
175     private Object getSpecialProperty(String strKey) {
176         if (isSpecialProperty(strKey)) {
177             final Method method = specialProperties.get(StringUtils.removeStart(strKey, "@"));
178             try {
179                 return method.invoke(content, null);
180             } catch (Exception e) {
181                 throw new RuntimeException(e);
182             }
183         }
184         return null;
185 
186     }
187 
188     private Object getNodeProperty(String keyStr) {
189         try {
190             if (content.hasProperty(keyStr)) {
191                 Property prop = content.getProperty(keyStr);
192                 int type = prop.getType();
193                 if (type == PropertyType.DATE) {
194                     return prop.getDate();
195                 } else if (type == PropertyType.BINARY) {
196                     // this should actually never happen. there is no reason why anyone should stream binary data into
197                     // template ... or is there?
198                 } else if (type == PropertyType.BOOLEAN) {
199                     return prop.getBoolean();
200                 } else if (type == PropertyType.LONG) {
201                     return prop.getLong();
202                 } else if (type == PropertyType.DOUBLE) {
203                     return prop.getDouble();
204                 } else if (type == PropertyType.REFERENCE) {
205                     return prop.getNode();
206                 } else if (prop.isMultiple()) {
207 
208                     Value[] values = prop.getValues();
209 
210                     String[] valueStrings = new String[values.length];
211 
212                     for (int j = 0; j < values.length; j++) {
213                         try {
214                             valueStrings[j] = values[j].getString();
215                         } catch (RepositoryException e) {
216                             log.debug(e.getMessage());
217                         }
218                     }
219 
220                     return valueStrings;
221                 } else if (LinkUtil.UUID_PATTERN.matcher(prop.getString()).find()) {
222                     try {
223                         return info.magnolia.link.LinkUtil.convertLinksFromUUIDPattern(prop.getString());
224                     } catch (LinkException e) {
225                         log.warn("Failed to parse links with from {}", prop.getName(), e);
226                     }
227                 }
228                 // don't we want to honor other types (e.g. numbers? )
229                 return prop.getString();
230             }
231             // property doesn't exist, but maybe child of that name does
232             if (content.hasNode(keyStr)) {
233                 return new ContentMap(content.getNode(keyStr));
234             }
235 
236         } catch (PathNotFoundException e) {
237             // ignore, property doesn't exist
238         } catch (RepositoryException e) {
239             log.warn("Failed to retrieve {} on {} with {}", keyStr, content, e.getMessage());
240         }
241 
242         return null;
243     }
244 
245     @Override
246     public int size() {
247         try {
248             return (int) (content.getProperties().getSize() + specialProperties.size());
249         } catch (RepositoryException e) {
250             // ignore ... no rights to read properties.
251         }
252         return specialProperties.size();
253     }
254 
255     @Override
256     public Set<String> keySet() {
257         Set<String> keys = new LinkedHashSet<>();
258         try {
259             PropertyIterator props = content.getProperties();
260             while (props.hasNext()) {
261                 keys.add(props.nextProperty().getName());
262             }
263         } catch (RepositoryException e) {
264             // ignore - has no access
265         }
266         for (String name : specialProperties.keySet()) {
267             keys.add(name);
268         }
269         return keys;
270     }
271 
272     @Override
273     public Set<java.util.Map.Entry<String, Object>> entrySet() {
274         throw new UnsupportedOperationException("Entry collections are not supported");
275     }
276 
277     @Override
278     public Collection<Object> values() {
279         throw new UnsupportedOperationException("Value collections are not supported");
280     }
281 
282     @Override
283     public boolean containsValue(Object arg0) {
284         throw new UnsupportedOperationException("Value checks are not supported");
285     }
286 
287     @Override
288     public boolean isEmpty() {
289         // can never be empty because of the node props themselves (name, uuid, ...)
290         return false;
291     }
292 
293     @Override
294     public void clear() {
295         // ignore, read only
296     }
297 
298     @Override
299     public Object put(String arg0, Object arg1) {
300         // ignore, read only
301         return null;
302     }
303 
304     @Override
305     public void putAll(Map<? extends String, ? extends Object> arg0) {
306         // ignore, read only
307     }
308 
309     @Override
310     public Object remove(Object arg0) {
311         // ignore, read only
312         return null;
313     }
314 
315     public Node getJCRNode() {
316         return content;
317     }
318 }