View Javadoc

1   /**
2    * This file Copyright (c) 2012-2013 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.Collection;
45  import java.util.LinkedList;
46  import java.util.Map;
47  
48  import javax.jcr.RepositoryException;
49  
50  import org.slf4j.Logger;
51  import org.slf4j.LoggerFactory;
52  
53  import com.google.common.base.Predicate;
54  import com.google.common.collect.Iterables;
55  import com.google.common.collect.Maps;
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       *
78       * @param beanClass class which collection will be hidden
79       * @param collectionName name of collection to hide
80       */
81      public CollectionPropertyHidingTransformer(Class<?> beanClass, String collectionName) {
82          this.beanClass = beanClass;
83          this.collectionName = collectionName;
84      }
85  
86      @Override
87      protected TypeDescriptor onResolveType(TypeMapping typeMapping, TransformationState state, TypeDescriptor resolvedType, ComponentProvider componentProvider) {
88          // lazy init, we need TypeMapping
89          if (type == null) {
90              type = typeMapping.getTypeDescriptor(beanClass);
91              propertyDescriptor = type.getPropertyTypeDescriptor(collectionName, typeMapping);
92              writeMethod = propertyDescriptor.getWriteMethod();
93              propertyType = propertyDescriptor.getCollectionEntryType();
94          }
95  
96          if (resolvedType == null) {
97              // if we are transforming a child node which does not define
98              // the class to be used, return the type of the collection entries
99  
100             // if the parent type is of the handled type
101             // this is the case when we are transforming children nodes)
102             if(state.getLevel() > 1 && state.getCurrentType().equals(type)) {
103                 // make it the default
104                 // use property descriptor
105                 resolvedType = getPropertyType();
106             }
107         }
108         return resolvedType;
109     }
110 
111     @Override
112     public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor, Map<String, Object> values) throws RepositoryException {
113         if (descriptor.getName().equals(collectionName)) {
114             Object bean = state.getCurrentBean();
115 
116             Map<String, Object> value = Maps.filterValues(values, new Predicate<Object>() {
117                 @Override
118                 public boolean apply(Object input) {
119                     return getPropertyType().getType().isInstance(input);
120                 }
121             });
122 
123             try {
124                 if (propertyDescriptor.isMap()) {
125                     writeMethod.invoke(bean, value);
126                 } else if (propertyDescriptor.isArray()) {
127                     Class<?> entryClass = getPropertyType().getType();
128                     Collection<Object> list = new LinkedList<Object>(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] = Iterables.get(list, 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     public TypeDescriptor getPropertyType() {
149         return propertyType;
150     }
151 }