View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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.content2bean.impl;
35  
36  import info.magnolia.content2bean.Content2BeanTransformer;
37  import info.magnolia.content2bean.PropertyTypeDescriptor;
38  import info.magnolia.content2bean.TypeDescriptor;
39  import info.magnolia.content2bean.TypeMapping;
40  
41  import java.beans.PropertyDescriptor;
42  import java.lang.reflect.Method;
43  import java.util.Collection;
44  import java.util.HashMap;
45  import java.util.Map;
46  
47  import info.magnolia.objectfactory.ClassFactory;
48  import info.magnolia.objectfactory.Classes;
49  import org.apache.commons.beanutils.PropertyUtils;
50  import org.apache.commons.lang.StringUtils;
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  
55  /**
56   * Basic type mapping implementation.
57   * @author philipp
58   * @version $Id: TypeMappingImpl.java 36506 2010-08-18 12:05:34Z had $
59   *
60   */
61  public class TypeMappingImpl implements TypeMapping {
62  
63      private static Logger log = LoggerFactory.getLogger(TypeMappingImpl.class);
64  
65      /**
66       * Property types already resolved.
67       */
68      protected static Map<String, PropertyTypeDescriptor> propertyTypes = new HashMap<String, PropertyTypeDescriptor>();
69  
70      /**
71       * Descriptors for types.
72       **/
73      protected static Map<Class<?>, TypeDescriptor> types = new HashMap<Class<?>, TypeDescriptor>();
74  
75      /**
76       * Get a adder method. Transforms name to singular.
77       */
78      public Method getAddMethod(Class<?> type, String name, int numberOfParameters) {
79          name = StringUtils.capitalize(name);
80          Method method = getExactMethod(type, "add" + name, numberOfParameters);
81          if (method == null) {
82              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "s"), numberOfParameters);
83          }
84  
85          if (method == null) {
86              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "es"), numberOfParameters);
87          }
88  
89          if (method == null) {
90              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ren"), numberOfParameters);
91          }
92  
93          if (method == null) {
94              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ies") + "y", numberOfParameters);
95          }
96          return method;
97      }
98  
99      /**
100      * Cache the already resolved types.
101      *
102      */
103     public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) {
104         PropertyTypeDescriptor dscr;
105         String key = beanClass.getName() + "." + propName;
106 
107         dscr = propertyTypes.get(key);
108         if(dscr != null){
109             return dscr;
110         }
111         TypeMapping defaultMapping = TypeMapping.Factory.getDefaultMapping();
112 
113         if (this != defaultMapping) {
114             dscr = defaultMapping.getPropertyTypeDescriptor(beanClass, propName);
115             if (dscr.getType()  != null) {
116                 return dscr;
117             }
118         }
119 
120         dscr = new PropertyTypeDescriptor();
121         dscr.setName(propName);
122 
123         PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
124         for (int i = 0; i < descriptors.length; i++) {
125             PropertyDescriptor descriptor = descriptors[i];
126             if (descriptor.getName().equals(propName)) {
127                 Class<?> propertytype = descriptor.getPropertyType(); // may be null for indexed properties
128                 if (propertytype != null) {
129                     dscr.setType(getTypeDescriptor(propertytype));
130                 }
131                 break;
132             }
133         }
134 
135         if(dscr.getType() != null){
136             if(dscr.isMap() || dscr.isCollection()){
137                 int numberOfParameters = dscr.isMap() ? 2 : 1;
138                 Method method = getAddMethod(beanClass, propName, numberOfParameters);
139                 if(method != null){
140                     dscr.setAddMethod(method);
141                     if(dscr.isMap()){
142                         dscr.setCollectionKeyType(getTypeDescriptor(method.getParameterTypes()[0]));
143                         dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[1]));
144                     }
145                     else{
146                         dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[0]));
147                     }
148                 }
149             }
150         }
151 
152         // remember me
153         propertyTypes.put(key, dscr);
154 
155         return dscr;
156     }
157 
158     public void addPropertyTypeDescriptor(Class<?> beanClass, String propName, PropertyTypeDescriptor dscr) {
159         propertyTypes.put(beanClass.getName() + "." + propName, dscr);
160     }
161 
162     public void addTypeDescriptor(Class<?> beanClass, TypeDescriptor dscr) {
163         types.put(beanClass, dscr);
164     }
165 
166     public TypeDescriptor getTypeDescriptor(Class<?> beanClass) {
167         TypeDescriptor dscr = types.get(beanClass);
168         if(dscr != null){
169             return dscr;
170         }
171         dscr = new TypeDescriptor();
172         dscr.setType(beanClass);
173         dscr.setMap(Map.class.isAssignableFrom(beanClass));
174         dscr.setCollection(beanClass.isArray() || Collection.class.isAssignableFrom(beanClass));
175         types.put(beanClass, dscr);
176 
177         if (!beanClass.isArray() && !beanClass.isPrimitive()) { // don't bother looking for a transformer if the property is an array or a primitive type
178             try {
179                 final ClassFactory classFactory = Classes.getClassFactory();
180                 final Class<Content2BeanTransformer> transformerClass = classFactory.forName(beanClass.getName() + "Transformer");
181 
182                 if(Content2BeanTransformer.class.isAssignableFrom(transformerClass)){
183                     try {
184                         final Content2BeanTransformer transformer = classFactory.newInstance(transformerClass);
185                         dscr.setTransformer(transformer);
186                         log.debug("Found a custom transformer [{" + transformerClass + "}] for [{" + beanClass + "}]");
187                     } catch (Exception e) {
188                         log.error("Can't instantiate custom transformer [{" + transformerClass + "}] for [{" + beanClass + "}]", e);
189                     }
190                 }
191             } catch (Exception e) {
192                 // this is fine because having a transformer class is optional
193                 log.debug("No custom transformer class {}Transformer class found", beanClass.getName());
194             }
195         }
196 
197         return dscr;
198     }
199 
200     /**
201      * Find a method.
202      * @param numberOfParameters
203      */
204     protected Method getExactMethod(Class<?> type, String name, int numberOfParameters) {
205         Method[] methods = type.getMethods();
206         for (int i = 0; i < methods.length; i++) {
207             Method method = methods[i];
208             if (method.getName().equals(name)) {
209                 if(method.getParameterTypes().length == numberOfParameters){
210                     return method;
211                 }
212             }
213         }
214         return null;
215     }
216 
217 }