View Javadoc
1   /**
2    * This file Copyright (c) 2008-2016 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.beanmerger;
35  
36  import java.lang.reflect.Modifier;
37  import java.net.URL;
38  import java.util.ArrayList;
39  import java.util.Collection;
40  import java.util.List;
41  import java.util.Map;
42  
43  import org.apache.commons.collections4.CollectionUtils;
44  import org.apache.commons.collections4.functors.NotNullPredicate;
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  
49  /**
50   * Base implementation of interface BeanMerge.
51   */
52  public abstract class BeanMergerBase implements BeanMerger {
53  
54      protected Logger log = LoggerFactory.getLogger(this.getClass());
55  
56      @Override
57      public Object merge(List sources) {
58          CollectionUtils.filter(sources, NotNullPredicate.INSTANCE);
59          if (sources.isEmpty()) {
60              return null;
61          }
62  
63          if (sources.size() == 1 || isSimpleType(sources.get(0).getClass()) || !isMergeable(sources.get(0).getClass())) {
64              return sources.get(0);
65          }
66  
67          if (sources.get(0) instanceof Collection) {
68              return mergeCollections(sources);
69          }
70  
71          if (sources.get(0) instanceof Map) {
72              return mergeMaps(sources);
73          }
74  
75          return mergeBean(sources);
76      }
77  
78      protected abstract Object mergeBean(List sources);
79  
80      protected Map mergeMaps(List<Map> sources) {
81          try {
82              Map mergedMap = this.instantiateOneOf(sources);
83              for (Map map : sources) {
84                  for (Object key : map.keySet()) {
85                      List values = new ArrayList();
86                      for (Map map2 : sources) {
87                          if (map2.containsKey(key)) {
88                              values.add(map2.get(key));
89                          }
90                      }
91                      mergedMap.put(key, merge(values));
92                  }
93              }
94              return mergedMap;
95          } catch (Exception e) {
96              log.error(e.getMessage(), e);
97              return sources.get(0);
98          }
99      }
100 
101     protected Collection mergeCollections(List<Collection> sources) {
102         try {
103             Collection mergedCol = this.instantiateOneOf(sources);
104             for (Collection col : sources) {
105                 mergedCol.addAll(col);
106             }
107             return mergedCol;
108         } catch (Exception e) {
109             log.error(e.getMessage(), e);
110             return sources.get(0);
111         }
112     }
113 
114     /**
115      * Checks whether type represents
116      * <ul>
117      * <li>a primitive
118      * <li>a boxed primitive, e.g {@link Double} or {@link Integer}
119      * <li>a {@link String}, {@link Class} or {@link URL}.
120      * </ul>
121      */
122     protected boolean isSimpleType(Class type) {
123         return type.isPrimitive() ||
124                 type == Object.class ||
125                 type == Boolean.class ||
126                 type == Byte.class ||
127                 type == Character.class ||
128                 type == Short.class ||
129                 type == Integer.class ||
130                 type == Long.class ||
131                 type == Float.class ||
132                 type == Double.class ||
133                 type == Void.class ||
134                 // well, at least property wise
135                 type == String.class ||
136                 type == Class.class ||
137                 type == URL.class;
138     }
139 
140     /**
141      * @return <code>true</code> if type is
142      * <ul>
143      * <li>not a final class
144      * <li>not an interface, with the exclusion of {@link Map} and {@link Collection}.
145      * </ul>
146      */
147     protected boolean isMergeable(Class type) {
148         if (Modifier.isFinal(type.getModifiers())) {
149             return false;
150         }
151         if (Modifier.isInterface(type.getModifiers())) {
152             return Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type);
153         }
154         return true;
155     }
156 
157     private <T>T instantiateOneOf(List<T> sources) throws IllegalAccessException, InstantiationException {
158         for (T object : sources) {
159             try {
160                 return (T) object.getClass().newInstance();
161             } catch (ReflectiveOperationException e) {
162                 if (object == sources.get(sources.size() - 1)) {
163                     throw e;
164                 }
165             }
166         }
167         return null;
168     }
169 
170 }