View Javadoc

1   /**
2    * This file Copyright (c) 2012-2012 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.node2bean.impl;
35  
36  import info.magnolia.cms.core.MgnlNodeType;
37  import info.magnolia.cms.util.ContentUtil;
38  import info.magnolia.cms.util.SystemContentWrapper;
39  import info.magnolia.jcr.iterator.FilteringNodeIterator;
40  import info.magnolia.jcr.node2bean.Node2BeanException;
41  import info.magnolia.jcr.node2bean.Node2BeanTransformer;
42  import info.magnolia.jcr.node2bean.PropertyTypeDescriptor;
43  import info.magnolia.jcr.node2bean.TransformationState;
44  import info.magnolia.jcr.node2bean.TypeDescriptor;
45  import info.magnolia.jcr.node2bean.TypeMapping;
46  import info.magnolia.jcr.predicate.AbstractPredicate;
47  import info.magnolia.objectfactory.Classes;
48  import info.magnolia.objectfactory.ComponentProvider;
49  
50  import java.lang.reflect.Array;
51  import java.lang.reflect.Constructor;
52  import java.lang.reflect.InvocationTargetException;
53  import java.lang.reflect.Method;
54  import java.text.MessageFormat;
55  import java.util.Collection;
56  import java.util.HashSet;
57  import java.util.Iterator;
58  import java.util.LinkedHashMap;
59  import java.util.LinkedList;
60  import java.util.List;
61  import java.util.Locale;
62  import java.util.Map;
63  import java.util.Queue;
64  import java.util.Set;
65  import java.util.regex.Pattern;
66  
67  import javax.inject.Inject;
68  import javax.jcr.Node;
69  import javax.jcr.NodeIterator;
70  import javax.jcr.RepositoryException;
71  
72  import org.apache.commons.beanutils.BeanUtilsBean;
73  import org.apache.commons.beanutils.Converter;
74  import org.apache.commons.beanutils.MethodUtils;
75  import org.apache.commons.beanutils.PropertyUtils;
76  import org.apache.commons.beanutils.PropertyUtilsBean;
77  import org.apache.commons.lang.LocaleUtils;
78  import org.apache.commons.lang.StringUtils;
79  import org.slf4j.Logger;
80  import org.slf4j.LoggerFactory;
81  
82  import com.google.common.collect.Iterables;
83  
84  /**
85   * Concrete implementation using reflection, generics and setter methods.
86   */
87  public class Node2BeanTransformerImpl implements Node2BeanTransformer {
88  
89      private static final Logger log = LoggerFactory.getLogger(Node2BeanTransformerImpl.class);
90  
91      private final BeanUtilsBean beanUtilsBean;
92  
93      private final Class<?> defaultListImpl;
94  
95      private final Class<?> defaultSetImpl;
96  
97      private final Class<?> defaultQueueImpl;
98  
99      @Inject
100     public Node2BeanTransformerImpl() {
101         this(LinkedList.class, HashSet.class, LinkedList.class);
102     }
103 
104     public Node2BeanTransformerImpl(Class<?> defaultListImpl, Class<?> defaultSetImpl, Class<?> defaultQueueImpl) {
105         this.defaultListImpl = defaultListImpl;
106         this.defaultSetImpl = defaultSetImpl;
107         this.defaultQueueImpl = defaultQueueImpl;
108 
109         // We use non-static BeanUtils conversion, so we can
110         // * use our custom ConvertUtilsBean
111         // * control converters (convertUtilsBean.register()) - we can register them here, locally, as opposed to a
112         // global ConvertUtils.register()
113         final EnumAwareConvertUtilsBean convertUtilsBean = new EnumAwareConvertUtilsBean();
114 
115         // de-register the converter for Class, we do our own conversion in convertPropertyValue()
116         convertUtilsBean.deregister(Class.class);
117 
118         convertUtilsBean.register(new Converter() {
119             @Override
120             public Object convert(Class type, Object value) {
121                     return new MessageFormat((String) value);
122             }
123         }, MessageFormat.class);
124 
125         convertUtilsBean.register(new Converter() {
126             @Override
127             public Object convert(Class type, Object value) {
128                 return Pattern.compile((String) value);
129             }
130         }, Pattern.class);
131 
132         this.beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
133     }
134 
135     @Override
136     public TransformationState newState() {
137         return new TransformationStateImpl();
138     }
139 
140     @Override
141     public TypeDescriptor resolveType(TypeMapping typeMapping, TransformationState state, ComponentProvider componentProvider) throws ClassNotFoundException, RepositoryException {
142         TypeDescriptor typeDscr = null;
143         Node node = state.getCurrentNode();
144 
145         try {
146             if (node.hasProperty("class")) {
147                 String className = node.getProperty("class").getString();
148                 if (StringUtils.isBlank(className)) {
149                     log.warn("Cannot resolve type for node [" + node + "] because class property has empty value.");
150                 } else {
151                     Class<?> clazz = Classes.getClassFactory().forName(className);
152                     typeDscr = typeMapping.getTypeDescriptor(clazz);
153                 }
154             }
155         } catch (RepositoryException e) {
156             log.warn("Can't read class property from node [{}]", node.getPath(), e);
157         }
158 
159         if (typeDscr == null && state.getLevel() > 1) {
160             TypeDescriptor parentTypeDscr = state.getCurrentType();
161             PropertyTypeDescriptor propDscr;
162 
163             if (parentTypeDscr.isMap() || parentTypeDscr.isCollection()) {
164                 if (state.getLevel() > 2) {
165                     // this is not necessarily the parent node of the current
166                     String mapProperyName = state.peekNode(1).getName();
167                     propDscr = state.peekType(1).getPropertyTypeDescriptor(mapProperyName, typeMapping);
168                     if (propDscr != null) {
169                         typeDscr = propDscr.getCollectionEntryType();
170                     }
171                 }
172             } else {
173                 propDscr = state.getCurrentType().getPropertyTypeDescriptor(node.getName(), typeMapping);
174                 if (propDscr != null) {
175                     typeDscr = propDscr.getType();
176                 }
177             }
178         }
179 
180         typeDscr = onResolveType(typeMapping, state, typeDscr, componentProvider);
181 
182         if (typeDscr != null) {
183             // might be that the factory util defines a default implementation for interfaces
184             final Class<?> type = typeDscr.getType();
185             typeDscr = typeMapping.getTypeDescriptor(componentProvider.getImplementation(type));
186 
187             // now that we know the property type we should delegate to the custom transformer if any defined
188             Node2BeanTransformer customTransformer = typeDscr.getTransformer();
189             if (customTransformer != null && customTransformer != this) {
190                 TypeDescriptor typeFoundByCustomTransformer = customTransformer.resolveType(typeMapping, state, componentProvider);
191                 // if no specific type has been provided by the
192                 // TODO - TypeDescriptor - equals and hashCode impl and use
193                 // not equals instead of !=
194                 if (typeFoundByCustomTransformer != TypeMapping.MAP_TYPE) {
195                     // might be that the factory util defines a default implementation for interfaces
196                     Class<?> implementation = componentProvider.getImplementation(typeFoundByCustomTransformer.getType());
197                     typeDscr = typeMapping.getTypeDescriptor(implementation);
198                 }
199             }
200         }
201 
202         if (typeDscr == null || typeDscr.needsDefaultMapping()) {
203             if (typeDscr == null) {
204                 log.debug("Was not able to resolve type for node [{}] will use a map", node);
205             }
206             typeDscr = TypeMapping.MAP_TYPE;
207         }
208         log.debug("Resolved type [{}] for node [{}]", typeDscr.getType(), node.getPath());
209 
210         return typeDscr;
211     }
212 
213     @Override
214     public NodeIterator getChildren(Node node) throws RepositoryException {
215         // TODO create predicate into separate class, <? extends Item> ItemHidingPredicate (regexp)
216         return new FilteringNodeIterator(node.getNodes(), new AbstractPredicate<Node>() {
217             @Override
218             public boolean evaluateTyped(Node t) {
219                 try {
220                     return !(t.getName().startsWith(MgnlNodeType.JCR_PREFIX) ||
221                             t.getName().startsWith(MgnlNodeType.MGNL_PREFIX) ||
222                             t.isNodeType(MgnlNodeType.NT_METADATA));
223                 } catch (RepositoryException e) {
224                     return false;
225                 }
226             }
227         });
228     }
229 
230     @Override
231     public Object newBeanInstance(TransformationState state, Map<String, Object> values, ComponentProvider componentProvider) throws Node2BeanException {
232         // we try first to use conversion (Map --> primitive type)
233         // this is the case when we flattening the hierarchy?
234         final Object bean = convertPropertyValue(state.getCurrentType().getType(), values);
235         // were the properties transformed?
236         if (bean == values) {
237             try {
238                 // is this property remove necessary?
239                 values.remove("class");
240                 final Class<?> type = state.getCurrentType().getType();
241                 if (LinkedHashMap.class.equals(type)) {
242                     // TODO - as far as I can tell, "bean" and "properties" are already the same instance of a
243                     // LinkedHashMap, so what are we doing in here ?
244                     return new LinkedHashMap();
245                 } else if (Map.class.isAssignableFrom(type)) {
246                     // TODO ?
247                     log.warn("someone wants another type of map ? " + type);
248                 } else if (Collection.class.isAssignableFrom(type)) {
249                     // someone wants specific collection
250                     return type.newInstance();
251                 }
252                 return componentProvider.newInstance(type);
253             } catch (Throwable e) {
254                 throw new Node2BeanException(e);
255             }
256         }
257         return bean;
258     }
259 
260     @Override
261     public void initBean(TransformationState state, Map values) throws Node2BeanException {
262         Object bean = state.getCurrentBean();
263 
264         Method init;
265         try {
266             init = bean.getClass().getMethod("init", new Class[] {});
267             try {
268                 init.invoke(bean); // no parameters
269             } catch (Exception e) {
270                 throw new Node2BeanException("can't call init method", e);
271             }
272         } catch (SecurityException e) {
273             return;
274         } catch (NoSuchMethodException e) {
275             return;
276         }
277         log.debug("{} is initialized", bean);
278 
279     }
280 
281     @Override
282     public Object convertPropertyValue(Class<?> propertyType, Object value) throws Node2BeanException {
283         if (Class.class.equals(propertyType)) {
284             try {
285                 return Classes.getClassFactory().forName(value.toString());
286             } catch (ClassNotFoundException e) {
287                 log.error("Can't convert property. Class for type [{}] not found.", propertyType);
288                 throw new Node2BeanException(e);
289             }
290         }
291 
292         if (Locale.class.equals(propertyType)) {
293             if (value instanceof String) {
294                 String localeStr = (String) value;
295                 if (StringUtils.isNotEmpty(localeStr)) {
296                     return LocaleUtils.toLocale(localeStr);
297                 }
298             }
299         }
300 
301         if ((Collection.class.equals(propertyType)) && (value instanceof Map)) {
302             // TODO never used ?
303             return ((Map) value).values();
304         }
305 
306         // this is mainly the case when we are flattening node hierarchies
307         if ((String.class.equals(propertyType)) && (value instanceof Map) && (((Map) value).size() == 1)) {
308             return ((Map) value).values().iterator().next();
309         }
310 
311         return value;
312     }
313 
314     /**
315      * Called once the type should have been resolved. The resolvedType might be
316      * null if no type has been resolved. Every subclass should override this method.
317      */
318     protected TypeDescriptor onResolveType(TypeMapping typeMapping, TransformationState state, TypeDescriptor resolvedType, ComponentProvider componentProvider) {
319         return resolvedType;
320     }
321 
322     @Override
323     public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor, Map<String, Object> values) throws RepositoryException {
324         String propertyName = descriptor.getName();
325         if (propertyName.equals("class")) {
326             return;
327         }
328         Object value = values.get(propertyName);
329         Object bean = state.getCurrentBean();
330 
331         if (propertyName.equals("content") && value == null) {
332             // TODO this should be changed to node but this would require to
333             // rewrite some classes to use node instead of content
334             value = new SystemContentWrapper(ContentUtil.asContent((state.getCurrentNode())));
335         } else if (propertyName.equals("name") && value == null) {
336             value = state.getCurrentNode().getName();
337         } else if (propertyName.equals("className") && value == null) {
338             value = values.get("class");
339         }
340 
341         // do no try to set a bean-property that has no corresponding node-property
342         if (value == null) {
343             return;
344         }
345 
346         log.debug("try to set {}.{} with value {}", new Object[] {bean, propertyName, value});
347         // if the parent bean is a map, we can't guess the types.
348         if (!(bean instanceof Map)) {
349             try {
350                 PropertyTypeDescriptor dscr = mapping.getPropertyTypeDescriptor(bean.getClass(), propertyName);
351                 if (dscr.getType() != null) {
352                     // try to use a setter method for a Collection property of
353                     // the bean
354                     if (dscr.isCollection() || dscr.isMap() || dscr.isArray()) {
355                         log.debug("{} is of type collection, map or array", propertyName);
356                         if (dscr.getWriteMethod() != null) {
357                             Method method = dscr.getWriteMethod();
358                             clearCollection(bean, propertyName);
359                             if (dscr.isMap()) {
360                                 method.invoke(bean, value);
361                             } else if (dscr.isArray()){
362                                 Class<?> entryClass = dscr.getCollectionEntryType().getType();
363                                 Collection<Object> list = new LinkedList<Object>(((Map<Object, Object>) value).values());
364 
365                                 Object[] arr = (Object[]) Array.newInstance(entryClass, list.size());
366                                 for (int i = 0; i < arr.length; i++) {
367                                     arr[i] = Iterables.get(list, i);
368                                 }
369                                 method.invoke(bean, new Object[] {arr});
370                             } else if (dscr.isCollection()) {
371                                 if (value instanceof Map) {
372                                     value = createCollectionFromMap((Map<Object, Object>) value, dscr.getType().getType());
373                                 }
374                                 method.invoke(bean, value);
375                             }
376                             return;
377                         } else if (dscr.getAddMethod() != null) {
378                             Method method = dscr.getAddMethod();
379                             clearCollection(bean, propertyName);
380                             Class<?> entryClass = dscr.getCollectionEntryType().getType();
381 
382                             log.warn("Will use deprecated add method [" + method.getName() + "] to populate [" + propertyName + "] in bean class [" + bean.getClass().getName() + "].");
383                             for (Iterator<Object> iter = ((Map<Object, Object>) value).keySet().iterator(); iter.hasNext();) {
384                                 Object key = iter.next();
385                                 Object entryValue = ((Map<Object, Object>) value).get(key);
386                                 entryValue = convertPropertyValue(entryClass, entryValue);
387                                 if (dscr.isCollection() || dscr.isArray()) {
388                                     log.debug("will add value {}", entryValue);
389                                     method.invoke(bean, new Object[] { entryValue });
390                                 }
391                                 // is a map
392                                 else {
393                                     log.debug("will add key {} with value {}", key, entryValue);
394                                     method.invoke(bean, new Object[] { key, entryValue });
395                                 }
396                             }
397                             return;
398                         }
399                         if (dscr.isCollection()) {
400                             log.debug("transform the values to a collection", propertyName);
401                             value = ((Map<Object, Object>) value).values();
402                         }
403                     } else {
404                         value = convertPropertyValue(dscr.getType().getType(), value);
405                     }
406                 }
407             } catch (Exception e) {
408                 if (log.isDebugEnabled()) {
409                     log.debug("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
410                         new Object[] { propertyName, value, bean.getClass().getName(),
411                             state.getCurrentNode().getPath(), e.toString() });
412                 } else {
413                     log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
414                         new Object[] {propertyName, value, bean.getClass().getName(),
415                                 state.getCurrentNode().getPath(), e.toString()});
416                 }
417             }
418         }
419 
420         try {
421             // This uses the converters registered in beanUtilsBean.convertUtilsBean (see constructor of this class)
422             // If a converter is registered, beanutils will convert value.toString(), not the value object as-is.
423             // If no converter is registered, then the value Object is set as-is.
424             // If convertPropertyValue() already converted this value, you'll probably want to unregister the beanutils
425             // converter.
426             // some conversions like string to class. Performance of PropertyUtils.setProperty() would be better
427             beanUtilsBean.setProperty(bean, propertyName, value);
428         } catch (Exception e) {
429             if (log.isDebugEnabled()) {
430                 log.debug("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
431                     new Object[] { propertyName, value, bean.getClass().getName(),
432                         state.getCurrentNode().getPath(), e.toString() });
433             } else {
434                 log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
435                     new Object[] {propertyName, value, bean.getClass().getName(),
436                             state.getCurrentNode().getPath(), e.toString()});
437             }
438         }
439     }
440 
441     /**
442      * @param bean
443      * @param propertyName
444      */
445     private void clearCollection(Object bean, String propertyName) {
446         log.debug("clearing the current content of the collection/map");
447         try {
448             Object col = PropertyUtils.getProperty(bean, propertyName);
449             if (col != null) {
450                 MethodUtils.invokeExactMethod(col, "clear", new Object[] {});
451             }
452         } catch (Exception e) {
453             log.debug("no clear method found on collection {}", propertyName);
454         }
455     }
456 
457     /**
458      * Creates collection from map. Collection type depends on passed class parameter. If passed class parameter is
459      * interface, then default implementation will be used for creating collection.<br/>
460      * By default
461      * <ul>
462      * <li>{@link LinkedList} is used for creating List and Queue collections.</li>
463      * <li>{@link HashSet} is used for creating Set collection.</li>
464      * </ul>
465      * If passed class parameter is an implementation of any collection type, then this method will create
466      * this implementation and returns it.
467      * @param map a map which values will be converted to a collection
468      * @param clazz collection type
469      * @return Collection of elements or null.
470      */
471     protected Collection<?> createCollectionFromMap(Map<?, ?> map, Class<?> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
472         Collection<?> collection = null;
473         Constructor<?> constructor = null;
474         if (clazz.isInterface()) {
475             // class is an interface, we need to decide which implementation of interface we will use
476             if (List.class.isAssignableFrom(clazz)) {
477                 constructor = defaultListImpl.getConstructor(Collection.class);
478             } else if (clazz.isAssignableFrom(Queue.class)) {
479                 constructor = defaultQueueImpl.getConstructor(Collection.class);
480             } else if (Set.class.isAssignableFrom(clazz)) {
481                 constructor = defaultSetImpl.getConstructor(Collection.class);
482             }
483         } else {
484             if (Collection.class.isAssignableFrom(clazz)) {
485                 constructor = clazz.getConstructor(Collection.class);
486             }
487         }
488         if (constructor != null) {
489             collection = (Collection<?>) constructor.newInstance(map.values());
490         }
491         return collection;
492     }
493 
494 }