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.LinkTransformerManager;
38  import info.magnolia.link.LinkUtil;
39  
40  import java.lang.reflect.Method;
41  import java.util.Collection;
42  import java.util.HashMap;
43  import java.util.HashSet;
44  import java.util.Map;
45  import java.util.Set;
46  
47  import javax.jcr.Node;
48  import javax.jcr.PathNotFoundException;
49  import javax.jcr.Property;
50  import javax.jcr.PropertyIterator;
51  import javax.jcr.PropertyType;
52  import javax.jcr.RepositoryException;
53  import javax.jcr.Value;
54  
55  import org.apache.commons.lang3.StringUtils;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  /**
60   * 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
61   * presence of child node. Few special property names map to the JCR methods: \@name, \@id, \@path, \@level, \@nodeType
62   */
63  public class ContentMap implements Map<String, Object> {
64  
65      private final static Logger log = LoggerFactory.getLogger(ContentMap.class);
66  
67      private final Node content;
68  
69      /**
70       * Represents getters of the node itself.
71       */
72      private final Map<String, Method> specialProperties = new HashMap<String, Method>();
73  
74      public ContentMap(Node content) {
75          if (content == null) {
76              throw new NullPointerException("ContentMap doesn't accept null content");
77          }
78  
79          this.content = content;
80  
81          // Supported special types are: @nodeType @name, @path @depth (and their deprecated forms - see
82          // convertDeprecatedProps() for details)
83          Class<? extends Node> clazz = content.getClass();
84          try {
85              specialProperties.put("name", clazz.getMethod("getName", (Class<?>[]) null));
86              specialProperties.put("id", clazz.getMethod("getIdentifier", (Class<?>[]) null));
87              specialProperties.put("path", clazz.getMethod("getPath", (Class<?>[]) null));
88              specialProperties.put("depth", clazz.getMethod("getDepth", (Class<?>[]) null));
89              specialProperties.put("nodeType", clazz.getMethod("getPrimaryNodeType", (Class<?>[]) null));
90          } catch (SecurityException e) {
91              log.debug("Failed to gain access to Node get***() method. Check VM security settings. {}", e.getLocalizedMessage(), e);
92          } catch (NoSuchMethodException e) {
93              log.debug("Failed to retrieve get***() method of Node class. Check the classpath for conflicting version of JCR classes. {}", e.getLocalizedMessage(), e);
94          }
95      }
96  
97      @Override
98      public boolean containsKey(Object key) {
99  
100         String strKey = convertKey(key);
101 
102         if (!isValidKey(strKey)) {
103             return false;
104         }
105 
106         if (isSpecialProperty(strKey)) {
107             return true;
108         }
109 
110         try {
111             return content.hasProperty(strKey);
112         } catch (RepositoryException e) {
113             // ignore, most likely invalid name
114         }
115         return false;
116     }
117 
118     private String convertKey(Object key) {
119         if (key == null) {
120             return null;
121         }
122         try {
123             return (String) key;
124         } catch (ClassCastException e) {
125             log.debug("Invalid key. Expected String, but got {}.", key.getClass().getName());
126         }
127         return null;
128     }
129 
130     private boolean isValidKey(String strKey) {
131         return !StringUtils.isBlank(strKey);
132     }
133 
134     private boolean isSpecialProperty(String strKey) {
135         if (!strKey.startsWith("@")) {
136             return false;
137         }
138         strKey = convertDeprecatedProps(strKey);
139         return specialProperties.containsKey(StringUtils.removeStart(strKey, "@"));
140     }
141 
142     /**
143      * @return a property name - in case the one handed in is known to be deprecated it'll be converted, else the
144      *         original one is returned.
145      */
146     private String convertDeprecatedProps(String strKey) {
147         // in the past we allowed both lower and upper case notation ...
148         if ("@UUID".equals(strKey) || "@uuid".equals(strKey)) {
149             return "@id";
150         } else if ("@handle".equals(strKey)) {
151             return "@path";
152         } else if ("@level".equals(strKey)) {
153             return "@depth";
154         }
155         return strKey;
156     }
157 
158     @Override
159     public Object get(Object key) {
160         String keyStr;
161         try {
162             keyStr = (String) key;
163         } catch (ClassCastException e) {
164             throw new ClassCastException("ContentMap accepts only String as a parameters, provided object was of type "
165                     + (key == null ? "null" : key.getClass().getName()));
166         }
167 
168         Object prop = getNodeProperty(keyStr);
169         if (prop == null) {
170             keyStr = convertDeprecatedProps(keyStr);
171             return getSpecialProperty(keyStr);
172         }
173         return prop;
174     }
175 
176     private Object getSpecialProperty(String strKey) {
177         if (isSpecialProperty(strKey)) {
178             final Method method = specialProperties.get(StringUtils.removeStart(strKey, "@"));
179             try {
180                 return method.invoke(content, null);
181             } catch (Exception e) {
182                 throw new RuntimeException(e);
183             }
184         }
185         return null;
186 
187     }
188 
189     private Object getNodeProperty(String keyStr) {
190         try {
191             if (content.hasProperty(keyStr)) {
192                 Property prop = content.getProperty(keyStr);
193                 int type = prop.getType();
194                 if (type == PropertyType.DATE) {
195                     return prop.getDate();
196                 } else if (type == PropertyType.BINARY) {
197                     // this should actually never happen. there is no reason why anyone should stream binary data into
198                     // template ... or is there?
199                 } else if (type == PropertyType.BOOLEAN) {
200                     return prop.getBoolean();
201                 } else if (type == PropertyType.LONG) {
202                     return prop.getLong();
203                 } else if (type == PropertyType.DOUBLE) {
204                     return prop.getDouble();
205                 } else if (prop.isMultiple()) {
206 
207                     Value[] values = prop.getValues();
208 
209                     String[] valueStrings = new String[values.length];
210 
211                     for (int j = 0; j < values.length; j++) {
212                         try {
213                             valueStrings[j] = values[j].getString();
214                         } catch (RepositoryException e) {
215                             log.debug(e.getMessage());
216                         }
217                     }
218 
219                     return valueStrings;
220                 } else if (LinkUtil.UUID_PATTERN.matcher(prop.getString()).find()) {
221                     try {
222                         return info.magnolia.link.LinkUtil.convertLinksFromUUIDPattern(prop.getString(),
223                                 LinkTransformerManager.getInstance().getBrowserLink(content.getPath()));
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 HashSet<String>();
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 }