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