View Javadoc
1   /**
2    * This file Copyright (c) 2012-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.node2bean.impl;
35  
36  import static info.magnolia.transformer.TransformationProblem.error;
37  
38  import info.magnolia.jcr.iterator.FilteringNodeIterator;
39  import info.magnolia.jcr.iterator.FilteringPropertyIterator;
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.jcr.predicate.JCRMgnlPropertyHidingPredicate;
48  import info.magnolia.jcr.util.NodeTypes;
49  import info.magnolia.jcr.util.PropertyUtil;
50  import info.magnolia.objectfactory.Classes;
51  import info.magnolia.objectfactory.ComponentProvider;
52  import info.magnolia.objectfactory.Components;
53  import info.magnolia.transformer.BeanTypeResolver;
54  
55  import java.lang.reflect.Array;
56  import java.lang.reflect.Constructor;
57  import java.lang.reflect.InvocationTargetException;
58  import java.lang.reflect.Method;
59  import java.util.ArrayList;
60  import java.util.Arrays;
61  import java.util.Collection;
62  import java.util.HashSet;
63  import java.util.LinkedHashMap;
64  import java.util.LinkedList;
65  import java.util.List;
66  import java.util.Locale;
67  import java.util.Map;
68  import java.util.Map.Entry;
69  import java.util.Queue;
70  import java.util.Set;
71  import java.util.stream.Collectors;
72  
73  import javax.inject.Inject;
74  import javax.jcr.Node;
75  import javax.jcr.NodeIterator;
76  import javax.jcr.Property;
77  import javax.jcr.PropertyIterator;
78  import javax.jcr.RepositoryException;
79  
80  import org.apache.commons.beanutils.BeanUtilsBean;
81  import org.apache.commons.beanutils.Converter;
82  import org.apache.commons.beanutils.MethodUtils;
83  import org.apache.commons.beanutils.PropertyUtils;
84  import org.apache.commons.lang3.LocaleUtils;
85  import org.apache.commons.lang3.StringUtils;
86  import org.slf4j.Logger;
87  import org.slf4j.LoggerFactory;
88  
89  import com.google.common.collect.Iterables;
90  import com.google.common.collect.Maps;
91  
92  /**
93   * Concrete implementation using reflection, generics and setter methods.
94   */
95  public class Node2BeanTransformerImpl implements Node2BeanTransformer {
96  
97      private static final Logger log = LoggerFactory.getLogger(Node2BeanTransformerImpl.class);
98  
99      private final BeanUtilsBean beanUtilsBean;
100 
101     private final Class<?> defaultListImpl;
102 
103     private final Class<?> defaultSetImpl;
104 
105     private final Class<?> defaultQueueImpl;
106 
107     private final BeanTypeResolver beanTypeResolver;
108 
109     @Inject
110     public Node2BeanTransformerImpl(PreConfiguredBeanUtils beanUtilsBean, BeanTypeResolver beanTypeResolver) {
111         this(beanUtilsBean, LinkedList.class, HashSet.class, LinkedList.class, beanTypeResolver);
112     }
113 
114     /**
115      * @deprecated since 5.4 - use IoC, don't instantiate directly. You should not have to instantiate this if you
116      * use magnolia-configuration mechanisms introduced in 5.4.
117      */
118     @Deprecated
119     public Node2BeanTransformerImpl() {
120         this(Components.getComponent(PreConfiguredBeanUtils.class), new BeanTypeResolver());
121     }
122 
123     /**
124      * @deprecated since 5.5.1 - use {@link #Node2BeanTransformerImpl(PreConfiguredBeanUtils, BeanTypeResolver)} instead.
125      */
126     @Deprecated
127     public Node2BeanTransformerImpl(PreConfiguredBeanUtils beanUtilsBean) {
128         this(beanUtilsBean, LinkedList.class, HashSet.class, LinkedList.class, new BeanTypeResolver());
129     }
130 
131     /**
132      * @deprecated since 5.4 - use IoC, don't instantiate directly. You should not have to instantiate this if you
133      * use magnolia-configuration mechanisms introduced in 5.4.
134      */
135     @Deprecated
136     public Node2BeanTransformerImpl(Class<?> defaultListImpl, Class<?> defaultSetImpl, Class<?> defaultQueueImpl) {
137         this(Components.getComponent(PreConfiguredBeanUtils.class), defaultListImpl, defaultSetImpl, defaultQueueImpl, Components.getComponent(BeanTypeResolver.class));
138     }
139 
140     protected Node2BeanTransformerImpl(PreConfiguredBeanUtils beanUtilsBean, Class<?> defaultListImpl, Class<?> defaultSetImpl, Class<?> defaultQueueImpl, BeanTypeResolver beanTypeResolver) {
141         this.beanUtilsBean = beanUtilsBean;
142         this.defaultListImpl = defaultListImpl;
143         this.defaultSetImpl = defaultSetImpl;
144         this.defaultQueueImpl = defaultQueueImpl;
145         this.beanTypeResolver = beanTypeResolver;
146 
147         beanUtilsBean.getConvertUtils().deregister(Class.class);
148     }
149 
150     @Override
151     public TransformationState newState() {
152         return new TransformationStateImpl();
153     }
154 
155     @Override
156     public TypeDescriptor resolveType(TypeMapping typeMapping, TransformationState state, ComponentProvider componentProvider) throws ClassNotFoundException, RepositoryException {
157         Node node = state.getCurrentNode();
158 
159         Map<String, Object> properties = convertPropertiesToMap(node.getProperties());
160 
161         TypeDescriptor typeDscr = null;
162         if (state.getLevel() > 1) {
163             TypeDescriptor parentTypeDscr = state.getCurrentType();
164             PropertyTypeDescriptor propDscr;
165 
166             if (parentTypeDscr.isMap() || parentTypeDscr.isCollection()) {
167                 if (state.getLevel() > 2) {
168                     // this is not necessarily the parent node of the current
169                     String mapProperyName = state.peekNode(1).getName();
170                     propDscr = state.peekType(1).getPropertyTypeDescriptor(mapProperyName, typeMapping);
171                     if (propDscr != null) {
172                         typeDscr = propDscr.getCollectionEntryType();
173                     }
174                 }
175             } else {
176                 propDscr = state.getCurrentType().getPropertyTypeDescriptor(node.getName(), typeMapping);
177                 if (propDscr != null) {
178                     typeDscr = propDscr.getType();
179                 }
180             }
181         }
182 
183         typeDscr = beanTypeResolver.resolve(typeDscr, properties).map(typeMapping::getTypeDescriptor).orElse(typeDscr);
184         typeDscr = onResolveType(typeMapping, state, typeDscr, componentProvider);
185 
186         if (typeDscr != null) {
187             // might be that the factory util defines a default implementation for interfaces
188             final Class<?> type = typeDscr.getType();
189             typeDscr = typeMapping.getTypeDescriptor(componentProvider.getImplementation(type));
190 
191             // now that we know the property type we should delegate to the custom transformer if any defined
192             Node2BeanTransformer customTransformer = typeDscr.getTransformer();
193             if (customTransformer != null && customTransformer != this) {
194                 TypeDescriptor typeFoundByCustomTransformer = customTransformer.resolveType(typeMapping, state, componentProvider);
195                 // if no specific type has been provided by the
196                 // TODO - TypeDescriptor - equals and hashCode impl and use
197                 // not equals instead of !=
198                 if (typeFoundByCustomTransformer != TypeMapping.MAP_TYPE) {
199                     // might be that the factory util defines a default implementation for interfaces
200                     Class<?> implementation = componentProvider.getImplementation(typeFoundByCustomTransformer.getType());
201                     typeDscr = typeMapping.getTypeDescriptor(implementation);
202                 }
203             }
204         }
205 
206         if (typeDscr == null || typeDscr.needsDefaultMapping()) {
207             if (typeDscr == null) {
208                 log.debug("Was not able to resolve type for node [{}] will use a map", node);
209             }
210             typeDscr = TypeMapping.MAP_TYPE;
211         }
212         log.debug("Resolved type [{}] for node [{}]", typeDscr.getType(), node.getPath());
213 
214         return typeDscr;
215     }
216 
217     private Map<String, Object> convertPropertiesToMap(PropertyIterator iterator) throws RepositoryException {
218         Map<String, Object> propertyMap = Maps.newHashMap();
219         while (iterator.hasNext()) {
220             Property property = iterator.nextProperty();
221             final Object propertyValue;
222             if (property.isMultiple()) {
223                propertyValue = Arrays.stream(property.getValues()).map(PropertyUtil::getValueObject).collect(Collectors.toList());
224             } else {
225                propertyValue = PropertyUtil.getValueObject(property.getValue());
226             }
227             propertyMap.put(property.getName(), propertyValue);
228         }
229         return propertyMap;
230     }
231 
232     @Override
233     public NodeIterator getChildren(Node node) throws RepositoryException {
234         // TODO create predicate into separate class, <? extends Item> ItemHidingPredicate (regexp)
235         return new FilteringNodeIterator(node.getNodes(), new AbstractPredicate<Node>() {
236             @Override
237             public boolean evaluateTyped(Node t) {
238                 try {
239                     return !(t.getName().startsWith(NodeTypes.JCR_PREFIX) || t.isNodeType(NodeTypes.MetaData.NAME));
240                 } catch (RepositoryException e) {
241                     return false;
242                 }
243             }
244         });
245     }
246 
247     @Override
248     public PropertyIterator getProperties(Node node) throws RepositoryException {
249         return new FilteringPropertyIterator(node.getProperties(), new JCRMgnlPropertyHidingPredicate());
250     }
251 
252     @Override
253     public Object newBeanInstance(TransformationState state, Map<String, Object> values, ComponentProvider componentProvider) throws Node2BeanException {
254         // we try first to use conversion (Map --> primitive type)
255         // this is the case when we flattening the hierarchy?
256         final Object bean = convertPropertyValue(state.getCurrentType().getType(), values);
257         // were the properties transformed?
258         if (bean == values) {
259             try {
260                 // is this property remove necessary?
261                 values.remove("class");
262                 final Class<?> type = state.getCurrentType().getType();
263                 if (LinkedHashMap.class.equals(type)) {
264                     // TODO - as far as I can tell, "bean" and "properties" are already the same instance of a
265                     // LinkedHashMap, so what are we doing in here ?
266                     return new LinkedHashMap();
267                 } else if (Map.class.isAssignableFrom(type)) {
268                     // TODO ?
269                     log.warn("someone wants another type of map ? {}", type);
270                 } else if (Collection.class.isAssignableFrom(type)) {
271                     // someone wants specific collection
272                     return type.newInstance();
273                 }
274                 return componentProvider.newInstance(type);
275             } catch (Exception e) {
276                 // This error is not tracked here because by current design the N2B conversion is supossed to blow up.
277                 // The N2B exception will bubble upwards to the N2BProcessor where we either handle it (the new API will catch the exception and record the error)
278                 // or, in case of the old API - we don't care about error tracking that much and will just let exception fly.
279                 throw new Node2BeanException(
280                         String.format("Failed to instantiate a bean of type [%s] due to: [%s]", state.getCurrentType().getType().getName(), e.getMessage()), e);
281             }
282         }
283         return bean;
284     }
285 
286     @Override
287     public void initBean(TransformationState state, Map values) throws Node2BeanException {
288         Object bean = state.getCurrentBean();
289 
290         Method init;
291         try {
292             init = bean.getClass().getMethod("init");
293             try {
294                 init.invoke(bean); // no parameters
295             } catch (Exception e) {
296                 throw new Node2BeanException("can't call init method", e);
297             }
298         } catch (SecurityException | NoSuchMethodException e) {
299             return;
300         }
301         log.debug("{} is initialized", bean);
302 
303     }
304 
305     @Override
306     public Object convertPropertyValue(Class<?> propertyType, Object value) throws Node2BeanException {
307         if (Class.class.equals(propertyType)) {
308             try {
309                 return Classes.getClassFactory().forName(value.toString());
310             } catch (ClassNotFoundException e) {
311                 // we let this error to be tracked by handleSetPropertyException, which is a common funnel for property-related failures
312                 throw new Node2BeanException(String.format("Can't convert property. Class for type [%s] not found.", propertyType), e);
313             }
314         }
315 
316         if (Locale.class.equals(propertyType)) {
317             if (value instanceof String) {
318                 String localeStr = (String) value;
319                 if (StringUtils.isNotEmpty(localeStr)) {
320                     return LocaleUtils.toLocale(localeStr);
321                 }
322             }
323         }
324 
325         if (Collection.class.equals(propertyType) && value instanceof Map) {
326             // TODO never used ?
327             return ((Map) value).values();
328         }
329 
330         // this is mainly the case when we are flattening node hierarchies
331         if (String.class.equals(propertyType) && value instanceof Map && ((Map) value).size() == 1) {
332             return ((Map) value).values().iterator().next();
333         }
334 
335         return value;
336     }
337 
338     /**
339      * Called once the type should have been resolved. The resolvedType might be
340      * null if no type has been resolved. Every subclass should override this method.
341      */
342     protected TypeDescriptorypeDescriptor">TypeDescriptor onResolveType(TypeMapping typeMapping, TransformationState state, TypeDescriptor resolvedType, ComponentProvider componentProvider) {
343         return resolvedType;
344     }
345 
346     @Override
347     public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor, Map<String, Object> values) throws RepositoryException {
348         String propertyName = descriptor.getName();
349         if (propertyName.equals("class")) {
350             return;
351         }
352         Object value = values.get(propertyName);
353         Object bean = state.getCurrentBean();
354 
355         if (propertyName.equals("content") && value == null) {
356             PropertyTypeDescriptor dscr = mapping.getPropertyTypeDescriptor(bean.getClass(), propertyName);
357             if (dscr.getType().getType().isAssignableFrom(Node.class)) {
358                 value = state.getCurrentNode();
359             }
360 
361         } else if (propertyName.equals("name") && value == null) {
362             value = state.getCurrentNode().getName();
363         } else if (propertyName.equals("className") && value == null) {
364             value = values.get("class");
365         }
366 
367         // do no try to set a bean-property that has no corresponding node-property
368         if (value == null) {
369             return;
370         }
371 
372         log.debug("try to set {}.{} with value {}", bean, propertyName, value);
373         // if the parent bean is a map, we can't guess the types.
374         if (!(bean instanceof Map)) {
375             try {
376                 PropertyTypeDescriptor dscr = mapping.getPropertyTypeDescriptor(bean.getClass(), propertyName);
377                 if (dscr.getType() != null) {
378                     // try to use a setter method for a Collection property of
379                     // the bean
380                     if (dscr.isCollection() || dscr.isMap() || dscr.isArray()) {
381                         log.debug("{} is of type collection, map or array", propertyName);
382                         if (dscr.getWriteMethod() != null) {
383                             Method method = dscr.getWriteMethod();
384                             clearCollection(bean, propertyName);
385                             filterOrConvertCollectionsAndMaps(dscr, value);
386                             if (dscr.isMap()) {
387                                 method.invoke(bean, value);
388                             } else if (dscr.isArray()) {
389                                 Class<?> entryClass = dscr.getCollectionEntryType().getType();
390                                 Collection<Object> list = new LinkedList<>(((Map<Object, Object>) value).values());
391 
392                                 Object[] arr = (Object[]) Array.newInstance(entryClass, list.size());
393                                 for (int i = 0; i < arr.length; i++) {
394                                     arr[i] = Iterables.get(list, i);
395                                 }
396                                 method.invoke(bean, new Object[]{arr});
397                             } else if (dscr.isCollection()) {
398                                 if (value instanceof Map) {
399                                     value = createCollectionFromMap((Map<Object, Object>) value, dscr.getType().getType());
400                                 }
401                                 method.invoke(bean, value);
402                             }
403                             return;
404                         } else if (dscr.getAddMethod() != null) {
405                             Method method = dscr.getAddMethod();
406                             clearCollection(bean, propertyName);
407                             Class<?> entryClass = dscr.getCollectionEntryType().getType();
408 
409                             log.warn("Will use deprecated add method [{}] to populate [{}] in bean class [{}].", method.getName(), propertyName, bean.getClass().getName());
410                             for (Object key : ((Map<Object, Object>) value).keySet()) {
411                                 Object entryValue = ((Map<Object, Object>) value).get(key);
412                                 entryValue = convertPropertyValue(entryClass, entryValue);
413                                 if (entryClass.isAssignableFrom(entryValue.getClass())) {
414                                     if (dscr.isCollection() || dscr.isArray()) {
415                                         log.debug("will add value {}", entryValue);
416                                         method.invoke(bean, entryValue);
417                                     }
418                                     // is a map
419                                     else {
420                                         log.debug("will add key {} with value {}", key, entryValue);
421                                         method.invoke(bean, key, entryValue);
422                                     }
423                                 }
424                             }
425                             return;
426                         }
427                         if (dscr.isCollection()) {
428                             log.debug("transform the values to a collection", propertyName);
429                             value = ((Map<Object, Object>) value).values();
430                         }
431                     } else {
432                         value = convertPropertyValue(dscr.getType().getType(), value);
433                     }
434                 }
435             } catch (Exception e) {
436                 handleSetPropertyException(state, propertyName, value, bean, e);
437                 return;
438             }
439         }
440 
441         try {
442             // This uses the converters registered in beanUtilsBean.convertUtilsBean (see constructor of this class)
443             // If a converter is registered, beanutils will determineBestMatch value.toString(), not the value object as-is.
444             // If no converter is registered, then the value Object is set as-is.
445             // If convertPropertyValue() already converted this value, you'll probably want to unregister the beanutils
446             // converter.
447             // some conversions like string to class. Performance of PropertyUtils.setProperty() would be better
448             beanUtilsBean.setProperty(bean, propertyName, value);
449         } catch (Exception e) {
450             handleSetPropertyException(state, propertyName, value, bean, e);
451         }
452     }
453 
454     @Override
455     public boolean canHandleValue(TypeMapping typeMapping, TransformationState state, PropertyTypeDescriptor descriptor, Entry<String, Object> value) {
456         return descriptor.getName().equals(value.getKey())
457                 || isCollectionOfStrings(typeMapping, state, value);
458     }
459 
460     private boolean isCollectionOfStrings(TypeMapping typeMapping, TransformationState state, Entry<String, Object> value) {
461         if (state.getCurrentBean() instanceof String && state.getLevel() > 2) {
462             try {
463                 PropertyTypeDescriptor propertyTypeDescriptor = state.peekType(2).getPropertyTypeDescriptor(state.peekNode(1).getName(), typeMapping);
464                 if (propertyTypeDescriptor != null) {
465                     TypeDescriptor entryType = propertyTypeDescriptor.getCollectionEntryType();
466                     if (entryType != null) {
467                         return entryType.getType().isAssignableFrom(value.getValue().getClass());
468                     }
469                 }
470             } catch (RepositoryException e) {
471                 log.error("Could not resolve property type for node [{}]", state.getCurrentNode(), e);
472             }
473         }
474         return false;
475     }
476 
477     @Override
478     public boolean supportsValueClaims() {
479         // sub-classes should opt-in explicitly
480         return getClass().equals(Node2BeanTransformerImpl.class);
481     }
482 
483     protected boolean isBeanEnabled(Object bean) {
484         try {
485             Boolean enabled = (Boolean) PropertyUtils.getSimpleProperty(bean, "enabled");
486             // bean used in Magnolia configuration can have three states, expressed by the Boolean property 'enabled':
487             // true (enabled), false (disabled) and null (undefined or inherited). In the latter case, do not skip bean
488             // so that it can be merged e.g. with a parent definition (e.g. a prototype). See for instance ConfiguredAreaDefinition
489             return enabled == null? true : enabled;
490         } catch (NoSuchMethodException | IllegalArgumentException e) {
491             // this is ok, enabled property is optional
492             return true;
493         } catch (IllegalAccessException e) {
494             log.warn("Can't access method [{}#isEnabled]. Maybe it's private/protected?", bean.getClass());
495             return true;
496         } catch (InvocationTargetException e) {
497             log.error("An exception was thrown by [{}#isEnabled] method.", bean.getClass(), e);
498             return true;
499         }
500     }
501 
502     /**
503      * Filters out not matching values and converts values if required.
504      *
505      * @param dscr descriptor keeping information about the properties
506      * @param value object from which some element might be filtered or converted
507      */
508     private void filterOrConvertCollectionsAndMaps(final PropertyTypeDescriptor dscr, final Object value) {
509         if (dscr.getCollectionEntryType() != null) {
510             Class<?> entryClass = dscr.getCollectionEntryType().getType();
511             if (dscr.getType().isCollection() && value instanceof Collection) {
512                 final Collection<?> collection = ((Collection) value);
513                 final Collection convertedCollection = filterOrConvert(collection, entryClass);
514                 collection.clear();
515                 collection.addAll(convertedCollection);
516             } else if (value instanceof Map) {
517                 final Map map = (Map) value;
518                 final Map convertedMap = filterOrConvert(map, entryClass);
519                 map.clear();
520                 map.putAll(convertedMap);
521             }
522         }
523     }
524 
525     private Collection filterOrConvert(final Collection collection, final Class entryClass) {
526         final Collection converted = new ArrayList();
527         for (Object obj : collection) {
528             if (isBeanEnabled(obj)) {
529                 if (!entryClass.isAssignableFrom(obj.getClass())) {
530                     final Converter converter = beanUtilsBean.getConvertUtils().lookup(entryClass);
531                     if (converter != null) {
532                         converted.add(converter.convert(entryClass, obj));
533                     }
534                 } else {
535                     converted.add(obj);
536                 }
537             }
538         }
539         return converted;
540     }
541 
542     private Map filterOrConvert(final Map map, final Class entryClass) {
543         final Map converted = new LinkedHashMap();
544         for (Object key : map.keySet()) {
545             Object obj = map.get(key);
546             if (isBeanEnabled(obj)) {
547                 if (!entryClass.isAssignableFrom(obj.getClass())) {
548                     final Converter converter = beanUtilsBean.getConvertUtils().lookup(entryClass);
549                     if (converter != null) {
550                         converted.put(key, converter.convert(entryClass, obj));
551                     }
552                 } else {
553                     converted.put(key, obj);
554                 }
555             }
556         }
557         return converted;
558     }
559 
560     private void clearCollection(Object bean, String propertyName) {
561         log.debug("clearing the current content of the collection/map");
562         try {
563             Object col = PropertyUtils.getProperty(bean, propertyName);
564             if (col != null) {
565                 MethodUtils.invokeExactMethod(col, "clear", new Object[]{});
566             }
567         } catch (Exception e) {
568             log.debug("no clear method found on collection {}", propertyName);
569         }
570     }
571 
572     /**
573      * Creates collection from map. Collection type depends on passed class parameter. If passed class parameter is
574      * interface, then default implementation will be used for creating collection.<br/>
575      * By default
576      * <ul>
577      * <li>{@link LinkedList} is used for creating List and Queue collections.</li>
578      * <li>{@link HashSet} is used for creating Set collection.</li>
579      * </ul>
580      * If passed class parameter is an implementation of any collection type, then this method will create
581      * this implementation and returns it.
582      *
583      * @param map a map which values will be converted to a collection
584      * @param clazz collection type
585      * @return Collection of elements or null.
586      */
587     protected Collection<?> createCollectionFromMap(Map<?, ?> map, Class<?> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
588         Collection<?> collection = null;
589         Constructor<?> constructor = null;
590         if (clazz.isInterface()) {
591             // class is an interface, we need to decide which implementation of interface we will use
592             if (List.class.isAssignableFrom(clazz)) {
593                 constructor = defaultListImpl.getConstructor(Collection.class);
594             } else if (clazz.isAssignableFrom(Queue.class)) {
595                 constructor = defaultQueueImpl.getConstructor(Collection.class);
596             } else if (Set.class.isAssignableFrom(clazz)) {
597                 constructor = defaultSetImpl.getConstructor(Collection.class);
598             }
599         } else {
600             if (Collection.class.isAssignableFrom(clazz)) {
601                 constructor = clazz.getConstructor(Collection.class);
602             }
603         }
604         if (constructor != null) {
605             collection = (Collection<?>) constructor.newInstance(map.values());
606         }
607         return collection;
608     }
609 
610     private void handleSetPropertyException(TransformationState state, String propertyName, Object value, Object bean, Exception e) throws RepositoryException /* See MAGNOLIA-5890, Node2BeanException */ {
611         if (e instanceof InvocationTargetException) {
612             e = (Exception) e.getCause();
613         }
614         final String errorMessage = String.format("Can't set property [%s] to value [%s] in bean [%s] for node [%s] due to: [%s]", propertyName, value, bean.getClass().getName(), state.getCurrentNode().getPath(), e.toString());
615 
616         state.trackProblem(error(errorMessage).withException(e));
617     }
618 
619 }