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 info.magnolia.jcr.node2bean.PropertyTypeDescriptor;
37  import info.magnolia.jcr.node2bean.TransformationState;
38  import info.magnolia.jcr.node2bean.TypeDescriptor;
39  import info.magnolia.jcr.node2bean.TypeMapping;
40  import info.magnolia.objectfactory.ComponentProvider;
41  
42  import java.lang.reflect.Array;
43  import java.lang.reflect.Method;
44  import java.util.ArrayList;
45  import java.util.Collection;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.Map.Entry;
50  import java.util.stream.Collectors;
51  
52  import javax.jcr.RepositoryException;
53  
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  /**
58   * A transformer which "hides" a collection node. Extend or pass the type and node name in the constructor.
59   */
60  public class CollectionPropertyHidingTransformer extends Node2BeanTransformerImpl {
61  
62      private static final Logger log = LoggerFactory.getLogger(CollectionPropertyHidingTransformer.class);
63  
64      private Class<?> beanClass;
65  
66      private String collectionName;
67  
68      private TypeDescriptor type;
69  
70      private PropertyTypeDescriptor propertyDescriptor;
71  
72      private Method writeMethod;
73  
74      private TypeDescriptor propertyType;
75  
76      /**
77       * @param beanClass class which collection will be hidden
78       * @param collectionName name of collection to hide
79       */
80      public CollectionPropertyHidingTransformer(Class<?> beanClass, String collectionName) {
81          this.beanClass = beanClass;
82          this.collectionName = collectionName;
83      }
84  
85      @Override
86      protected TypeDescriptorypeDescriptor">TypeDescriptor onResolveType(TypeMapping typeMapping, TransformationState state, TypeDescriptor resolvedType, ComponentProvider componentProvider) {
87          // lazy init, we need TypeMapping
88          if (type == null) {
89              type = typeMapping.getTypeDescriptor(beanClass);
90              propertyDescriptor = type.getPropertyTypeDescriptor(collectionName, typeMapping);
91              writeMethod = propertyDescriptor.getWriteMethod();
92              propertyType = propertyDescriptor.getCollectionEntryType();
93          }
94  
95          if (resolvedType == null) {
96              // if we are transforming a child node which does not define
97              // the class to be used, return the type of the collection entries
98  
99              // if the parent type is of the handled type
100             // this is the case when we are transforming children nodes)
101             if (state.getLevel() > 1 && state.getCurrentType().equals(type)) {
102                 // make it the default
103                 // use property descriptor
104                 resolvedType = getPropertyType();
105             }
106         }
107         return resolvedType;
108     }
109 
110     @Override
111     public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor, Map<String, Object> values) throws RepositoryException {
112         if (descriptor.getName().equals(collectionName)) {
113             Object bean = state.getCurrentBean();
114 
115             Map<String, Object> value = values.entrySet().stream()
116                     .filter(this::canHandleValue)
117                     .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
118                             (u, v) -> {
119                                 throw new IllegalStateException(String.format("Duplicate key %s", u));
120                             },
121                             LinkedHashMap::new));
122 
123             try {
124                 if (propertyDescriptor.isMap()) {
125                     writeMethod.invoke(bean, value);
126                 } else if (propertyDescriptor.isArray()) {
127                     Class<?> entryClass = getPropertyType().getType();
128                     List<Object> list = new ArrayList<>(value.values());
129 
130                     Object[] arr = (Object[]) Array.newInstance(entryClass, list.size());
131 
132                     for (int i = 0; i < arr.length; i++) {
133                         arr[i] = list.get(i);
134                     }
135                     writeMethod.invoke(bean, new Object[]{arr});
136                 } else if (propertyDescriptor.isCollection()) {
137                     Collection<?> collection = createCollectionFromMap(value, propertyDescriptor.getType().getType());
138                     writeMethod.invoke(bean, collection);
139                 }
140             } catch (Exception e) {
141                 log.error("Can't call set method {}", propertyDescriptor.getWriteMethod(), e);
142             }
143         } else {
144             super.setProperty(mapping, state, descriptor, values);
145         }
146     }
147 
148     @Override
149     public boolean canHandleValue(TypeMapping typeMapping, TransformationState state, PropertyTypeDescriptor descriptor, Entry<String, Object> value) {
150         return canHandleValue(value) || super.canHandleValue(typeMapping, state, descriptor, value);
151     }
152 
153     private boolean canHandleValue(Entry<String, Object> entry) {
154         return getPropertyType().getType().isInstance(entry.getValue());
155     }
156 
157     @Override
158     public boolean supportsValueClaims() {
159         // sub-classes should opt-in explicitly
160         return getClass().equals(CollectionPropertyHidingTransformer.class);
161     }
162 
163     public TypeDescriptor getPropertyType() {
164         return propertyType;
165     }
166 }