View Javadoc
1   /**
2    * This file Copyright (c) 2003-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.content2bean.impl;
35  
36  import info.magnolia.cms.core.SystemProperty;
37  import info.magnolia.content2bean.Content2BeanTransformer;
38  import info.magnolia.content2bean.PropertyTypeDescriptor;
39  import info.magnolia.content2bean.TypeDescriptor;
40  import info.magnolia.content2bean.TypeMapping;
41  import info.magnolia.objectfactory.ClassFactory;
42  import info.magnolia.objectfactory.Classes;
43  
44  import java.beans.PropertyDescriptor;
45  import java.lang.reflect.Method;
46  import java.util.Collection;
47  import java.util.HashMap;
48  import java.util.Map;
49  
50  import javax.inject.Singleton;
51  
52  import org.apache.commons.beanutils.PropertyUtils;
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  
58  /**
59   * Basic type mapping implementation.
60   *
61   * @deprecated since 5.2.4 - use {@link info.magnolia.jcr.node2bean.impl.TypeMappingImpl} instead.
62   */
63  @Singleton
64  public class TypeMappingImpl implements TypeMapping {
65  
66      private static Logger log = LoggerFactory.getLogger(TypeMappingImpl.class);
67  
68      /**
69       * Property types already resolved.
70       */
71      private final Map<String, PropertyTypeDescriptor> propertyTypes = new HashMap<String, PropertyTypeDescriptor>();
72  
73      /**
74       * Descriptors for types.
75       */
76      private final Map<Class<?>, TypeDescriptor> types = new HashMap<Class<?>, TypeDescriptor>();
77  
78      /**
79       * Get a adder method. Transforms name to singular.
80       */
81      public Method getAddMethod(Class<?> type, String name, int numberOfParameters) {
82          name = StringUtils.capitalize(name);
83          Method method = getExactMethod(type, "add" + name, numberOfParameters);
84          if (method == null) {
85              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "s"), numberOfParameters);
86          }
87  
88          if (method == null) {
89              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "es"), numberOfParameters);
90          }
91  
92          if (method == null) {
93              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ren"), numberOfParameters);
94          }
95  
96          if (method == null) {
97              method = getExactMethod(type, "add" + StringUtils.removeEnd(name, "ies") + "y", numberOfParameters);
98          }
99          return method;
100     }
101 
102     /**
103      * Cache the already resolved types.
104      */
105     @Override
106     public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) {
107         PropertyTypeDescriptor dscr;
108         String key = beanClass.getName() + "." + propName;
109 
110         dscr = propertyTypes.get(key);
111         if (dscr != null) {
112             return dscr;
113         }
114 
115         //TypeMapping defaultMapping = TypeMapping.Factory.getDefaultMapping();
116         // TODO - is this used - or is the comparison correct ?
117 //        if (this != defaultMapping) {
118 //            dscr = defaultMapping.getPropertyTypeDescriptor(beanClass, propName);
119 //            if (dscr.getType()  != null) {
120 //                return dscr;
121 //            }
122 //        }
123 
124         dscr = new PropertyTypeDescriptor();
125         dscr.setName(propName);
126 
127         PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
128         for (int i = 0; i < descriptors.length; i++) {
129             PropertyDescriptor descriptor = descriptors[i];
130             if (descriptor.getName().equals(propName)) {
131                 Class<?> propertytype = descriptor.getPropertyType(); // may be null for indexed properties
132                 if (propertytype != null) {
133                     dscr.setType(getTypeDescriptor(propertytype));
134                 }
135                 break;
136             }
137         }
138 
139         if (dscr.getType() != null) {
140             if (dscr.isMap() || dscr.isCollection()) {
141                 int numberOfParameters = dscr.isMap() ? 2 : 1;
142                 Method method = getAddMethod(beanClass, propName, numberOfParameters);
143                 if (method != null) {
144                     dscr.setAddMethod(method);
145                     if (dscr.isMap()) {
146                         dscr.setCollectionKeyType(getTypeDescriptor(method.getParameterTypes()[0]));
147                         dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[1]));
148                     } else {
149                         dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[0]));
150                     }
151                 }
152             }
153         }
154 
155         // remember me
156         propertyTypes.put(key, dscr);
157 
158         return dscr;
159     }
160 
161     @Override
162     public void addPropertyTypeDescriptor(Class<?> beanClass, String propName, PropertyTypeDescriptor dscr) {
163         propertyTypes.put(beanClass.getName() + "." + propName, dscr);
164     }
165 
166     @Override
167     public void addTypeDescriptor(Class<?> beanClass, TypeDescriptor dscr) {
168         types.put(beanClass, dscr);
169     }
170 
171     @Override
172     public TypeDescriptor getTypeDescriptor(Class<?> beanClass) {
173         TypeDescriptor dscr = types.get(beanClass);
174         // eh, we know about this type, don't bother resolving any further.
175         if (dscr != null) {
176             return dscr;
177         }
178         dscr = new TypeDescriptor();
179         dscr.setType(beanClass);
180         dscr.setMap(Map.class.isAssignableFrom(beanClass));
181         dscr.setCollection(beanClass.isArray() || Collection.class.isAssignableFrom(beanClass));
182         types.put(beanClass, dscr);
183 
184         if (!beanClass.isArray() && !beanClass.isPrimitive()) { // don't bother looking for a transformer if the property is an array or a primitive type
185             Content2BeanTransformer transformer = null; // TODO ? transformerProvider.getTransformerFor(beanClass);
186             try {
187                 transformer = findTransformerByNamingConvention(beanClass);
188                 if (transformer == null) {
189                     transformer = findTransformerViaProperty(beanClass);
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             dscr.setTransformer(transformer);
196         }
197         return dscr;
198     }
199 
200     /**
201      * @deprecated since 4.5, transformers should be explicitly registered via the module descriptor.
202      */
203     protected Content2BeanTransformer findTransformerByNamingConvention(Class<?> beanClass) {
204         final String transformerClassName = beanClass.getName() + "Transformer";
205         try {
206             return instantiateTransformer(beanClass, transformerClassName);
207         } catch (ClassNotFoundException e) {
208             log.debug("No transformer found by naming convention for {} (attempted to load {})", beanClass, transformerClassName);
209             return null;
210         }
211     }
212 
213     /**
214      * This was originally implemented by {@link info.magnolia.content2bean.impl.PropertiesBasedTypeMapping}.
215      *
216      * @deprecated since 4.5, transformers should be explicitly registered via the module descriptor.
217      */
218     protected Content2BeanTransformer findTransformerViaProperty(Class<?> beanClass) throws ClassNotFoundException {
219         final String property = SystemProperty.getProperty(beanClass.getName() + ".transformer");
220         if (property != null) {
221             return instantiateTransformer(beanClass, property);
222         }
223         return null;
224     }
225 
226     protected Content2BeanTransformer instantiateTransformer(Class<?> beanClass, String transformerClassName) throws ClassNotFoundException {
227         final ClassFactory classFactory = Classes.getClassFactory();
228         final Class<Content2BeanTransformer> transformerClass = classFactory.forName(transformerClassName);
229 
230         if (Content2BeanTransformer.class.isAssignableFrom(transformerClass)) {
231             try {
232                 log.debug("Found a custom transformer [{{}}] for [{{}}]", transformerClass, beanClass);
233                 // TODO use components ?
234                 return classFactory.newInstance(transformerClass);
235             } catch (Exception e) {
236                 log.error("Can't instantiate custom transformer [{{}}] for [{{}}]", transformerClass, beanClass, e);
237             }
238         }
239         return null;
240     }
241 
242     /**
243      * Find a method.
244      */
245     protected Method getExactMethod(Class<?> type, String name, int numberOfParameters) {
246         Method[] methods = type.getMethods();
247         for (int i = 0; i < methods.length; i++) {
248             Method method = methods[i];
249             if (method.getName().equals(name)) {
250                 // TODO - CAUTION: in case there's several methods with the same name and the same numberOfParameters
251                 // this method might pick the "wrong" one. We should think about adding a check and throw an exceptions
252                 // if there's more than one match!
253                 if (method.getParameterTypes().length == numberOfParameters) {
254                     return method;
255                 }
256             }
257         }
258         return null;
259     }
260 
261 }