View Javadoc

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