View Javadoc

1   /**
2    * This file Copyright (c) 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.jcr.node2bean.Node2BeanTransformer;
37  import info.magnolia.jcr.node2bean.PropertyTypeDescriptor;
38  import info.magnolia.jcr.node2bean.TypeDescriptor;
39  import info.magnolia.jcr.node2bean.TypeMapping;
40  import info.magnolia.objectfactory.Components;
41  
42  import java.beans.PropertyDescriptor;
43  import java.lang.reflect.Method;
44  import java.lang.reflect.ParameterizedType;
45  import java.lang.reflect.Type;
46  import java.util.Collection;
47  import java.util.HashMap;
48  import java.util.Map;
49  
50  import org.apache.commons.beanutils.PropertyUtils;
51  import org.apache.commons.lang.ArrayUtils;
52  import org.apache.commons.lang.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * Basic type mapping implementation.
58   */
59  public class TypeMappingImpl implements TypeMapping {
60  
61      private static Logger log = LoggerFactory.getLogger(TypeMappingImpl.class);
62  
63      private final Map<String, PropertyTypeDescriptor> propertyTypes = new HashMap<String, PropertyTypeDescriptor>();
64      private final Map<Class<?>, TypeDescriptor> types = new HashMap<Class<?>, TypeDescriptor>();
65  
66      @Override
67      public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) {
68          PropertyTypeDescriptor dscr = null;
69          String key = beanClass.getName() + "." + propName;
70  
71          dscr = propertyTypes.get(key);
72  
73          if (dscr != null) {
74              return dscr;
75          }
76  
77          dscr = new PropertyTypeDescriptor();
78          dscr.setName(propName);
79  
80          PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
81          for (PropertyDescriptor descriptor : descriptors) {
82              if (descriptor.getName().equals(propName)) {
83                  // may be null for indexed properties
84                  Class<?> propertyType = descriptor.getPropertyType();
85                  if (propertyType != null) {
86                      dscr.setType(getTypeDescriptor(propertyType));
87                  }
88                  // set write method
89                  dscr.setWriteMethod(descriptor.getWriteMethod());
90                  // set add method
91                  int numberOfParameters = dscr.isMap() ? 2 : 1;
92                  dscr.setAddMethod(getAddMethod(beanClass, propName, numberOfParameters));
93  
94                  break;
95              }
96          }
97  
98          if (dscr.getType() != null) {
99              // we have discovered type for property
100             if (dscr.isMap() || dscr.isCollection()) {
101                 Type[] typeArgs = new Type[] {}; // this will contain collection types (for map key/value type, for collection value type)
102                 if (dscr.getWriteMethod() != null) {
103                     // now we have to find out if generics are set
104                     Type[] parameterTypes = dscr.getWriteMethod().getGenericParameterTypes();
105                     if (parameterTypes.length > 0) {
106                         // we have parameter with generics
107                         for (Type genericParameterType : parameterTypes) {
108                             // check if we have parameterized type e.g. Collection<String>
109                             if (genericParameterType instanceof ParameterizedType) {
110                                 ParameterizedType type = (ParameterizedType) genericParameterType;
111                                 for (Type t : type.getActualTypeArguments()) {
112                                     if (t instanceof ParameterizedType) {
113                                         // this the case when parameterized type looks like this: Collection<List<String>>
114                                         // we care only for raw type List
115                                         typeArgs = (Type[]) ArrayUtils.add(typeArgs, ((ParameterizedType) t).getRawType());
116                                     } else {
117                                         typeArgs = (Type[]) ArrayUtils.add(typeArgs, t);
118                                     }
119                                 }
120                             }
121                         }
122                     }
123                 }
124                 if (dscr.getAddMethod() != null && typeArgs.length == 0) {
125                     // here we know we don't have setter or setter doesn't have parameterized type
126                     // but we have add method so we take parameters from it
127                     typeArgs = dscr.getAddMethod().getParameterTypes();
128                     // rather set it to null because when we are here we will use add method
129                     dscr.setWriteMethod(null);
130                 }
131                 if (typeArgs.length > 0) {
132                     // we resolved types
133                     if (dscr.isMap()) {
134                         dscr.setCollectionKeyType(getTypeDescriptor((Class<?>) typeArgs[0]));
135                         dscr.setCollectionEntryType(getTypeDescriptor((Class<?>) typeArgs[1]));
136                     } else {
137                         // collection
138                         dscr.setCollectionEntryType(getTypeDescriptor((Class<?>) typeArgs[0]));
139                     }
140                 }
141             } else if (dscr.isArray()) {
142                 // for arrays we don't need to discover its parameter from set/add method
143                 // we just take it via Class#getComponentType() method
144                 dscr.setCollectionEntryType(getTypeDescriptor(dscr.getType().getType().getComponentType()));
145             }
146         }
147         propertyTypes.put(key, dscr);
148 
149         return dscr;
150     }
151 
152     @Override
153     public TypeDescriptor getTypeDescriptor(Class<?> beanClass) {
154         TypeDescriptor dscr = types.get(beanClass);
155         // eh, we know about this type, don't bother resolving any further.
156         if(dscr != null){
157             return dscr;
158         }
159         dscr = new TypeDescriptor();
160         dscr.setType(beanClass);
161         dscr.setMap(Map.class.isAssignableFrom(beanClass));
162         dscr.setCollection(Collection.class.isAssignableFrom(beanClass));
163         dscr.setArray(beanClass.isArray());
164         types.put(beanClass, dscr);
165 
166         if (!beanClass.isArray() && !beanClass.isPrimitive()) { // don't bother looking for a transformer if the property is an array or a primitive type
167             Node2BeanTransformer transformer = null;
168             try {
169                 @SuppressWarnings("unchecked")
170                 Class<Node2BeanTransformer> clazz = (Class<Node2BeanTransformer>) Class.forName(beanClass.getName() + "Transformer");
171                 transformer = Components.getComponent(clazz);
172             } catch (Exception e) {
173                 log.debug("No custom transformer class {}Transformer class found", beanClass.getName());
174             }
175             dscr.setTransformer(transformer);
176         }
177         return dscr;
178     }
179 
180     /**
181      * Get a adder method. Transforms name to singular.
182      * @deprecated since 5.0 - use setters
183      */
184     public Method getAddMethod(Class<?> type, String name, int numberOfParameters) {
185         name = StringUtils.capitalize(name);
186         Method method = getExactMethod(type, "add" + name, numberOfParameters);
187         if (method == null) {
188             method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "s"), numberOfParameters);
189         }
190 
191         if (method == null) {
192             method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "es"), numberOfParameters);
193         }
194 
195         if (method == null) {
196             method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ren"), numberOfParameters);
197         }
198 
199         if (method == null) {
200             method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ies") + "y", numberOfParameters);
201         }
202         return method;
203     }
204 
205     /**
206      * Find a method.
207      *
208      * @param numberOfParameters
209      * @deprecated since 5.0 - use setters
210      */
211     protected Method getExactMethod(Class<?> type, String name, int numberOfParameters) {
212         Method[] methods = type.getMethods();
213         for (int i = 0; i < methods.length; i++) {
214             Method method = methods[i];
215             if (method.getName().equals(name)) {
216                 // TODO - CAUTION: in case there's several methods with the same
217                 // name and the same numberOfParameters
218                 // this method might pick the "wrong" one. We should think about
219                 // adding a check and throw an exceptions
220                 // if there's more than one match!
221                 if (method.getParameterTypes().length == numberOfParameters) {
222                     return method;
223                 }
224             }
225         }
226         return null;
227     }
228 
229 }