(no commit message)
[utils] / support / general / src / main / java / org / wamblee / persistence / JpaMergeSupport.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.persistence;
17
18 import java.io.Serializable;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.Map.Entry;
27
28 import javax.persistence.EntityManager;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.wamblee.persistence.PersistentFactory.EntityAccessor;
33 import org.wamblee.reflection.ReflectionUtils;
34
35 /**
36  * Support for merging of JPA entities. This utility allows the result of a
37  * merge (modifications of primary key and/or version) to be merged back into
38  * the argument that was merged. As a result, the merged entity can be reused
39  * and the application is not forced to use the new version that was returned
40  * from the merge.
41  * 
42  * The utility traverses the object graph based on the public getter methods.
43  * Therefore, care should be taken with this utility as usage could lead to
44  * recursively loading all objects reachable from the given object. Then again,
45  * this utility is for working with detached objects and it would, in general,
46  * be bad practice to work with detached objects that still contain unresolved
47  * lazy loaded relations and with detached objects that implicitly refer to
48  * almost the entire datamodel.
49  * 
50  * This utility best supports a service oriented design where interaction is
51  * through service interfaces where each service has its own storage isolated
52  * from other services. That would be opposed to a shared data design with many
53  * services acting on the same data.
54  * 
55  * @author Erik Brakkee
56  */
57 public class JpaMergeSupport {
58     private static final Log LOG = LogFactory.getLog(JpaMergeSupport.class);
59
60     /**
61      * Constructs the object.
62      * 
63      */
64     public JpaMergeSupport() {
65         // Empty
66     }
67
68     /**
69      * As {@link #merge(Persistent)} but with a given template. This method can
70      * be accessed in a static way.
71      * 
72      * @param aMerge
73      *            The result of the call to {@link EntityManager#merge(Object)}.
74      * @param aPersistent
75      *            Object that was passed to {@link EntityManager#merge(Object)}.
76      */
77     public static void merge(Object aMerged, Object aPersistent) {
78         processPersistent(aMerged, aPersistent, new ArrayList<ObjectElem>());
79     }
80
81     /**
82      * Copies primary keys and version from the result of the merged to the
83      * object that was passed to the merge operation. It does this by traversing
84      * the public properties of the object. It copies the primary key and
85      * version for objects that implement {@link Persistent} and applies the
86      * same rules to objects in maps and sets as well (i.e. recursively).
87      * 
88      * @param aPersistent
89      *            Object whose primary key and version are to be set.
90      * @param aMerged
91      *            Object that was the result of the merge.
92      * @param aProcessed
93      *            List of already processed Persistent objects of the persistent
94      *            part.
95      * 
96      */
97     public static void processPersistent(Object aMerged, Object aPersistent,
98         List<ObjectElem> aProcessed) {
99         if ((aPersistent == null) && (aMerged == null)) {
100             return;
101         }
102
103         if ((aPersistent == null) || (aMerged == null)) {
104             throw new RuntimeException("persistent or merged object is null '" +
105                 aPersistent + "'" + "  '" + aMerged + "'");
106         }
107
108         ObjectElem elem = new ObjectElem(aPersistent);
109
110         if (aProcessed.contains(elem)) {
111             return; // already processed.
112         }
113
114         aProcessed.add(elem);
115
116         LOG.debug("Setting pk/version on " + aPersistent + " from " + aMerged);
117
118         Persistent persistentWrapper = PersistentFactory.create(aPersistent);
119         Persistent mergedWrapper = PersistentFactory.create(aMerged);
120
121         if (persistentWrapper == null) {
122             // Not an entity so it is ignored.
123             return;
124         }
125
126         Serializable pk = persistentWrapper.getPrimaryKey();
127         boolean pkIsNull = false;
128         if (pk instanceof Number) {
129             if (((Number) pk).longValue() != 0l) {
130                 pkIsNull = false;
131             } else {
132                 pkIsNull = true;
133             }
134         } else {
135             pkIsNull = (pk == null);
136         }
137         if (!pkIsNull &&
138             !mergedWrapper.getPrimaryKey().equals(
139                 persistentWrapper.getPrimaryKey())) {
140             throw new IllegalArgumentException(
141                 "Mismatch between primary key values: " + aPersistent + " " +
142                     aMerged);
143         } else {
144             persistentWrapper.setPersistedVersion(mergedWrapper
145                 .getPersistedVersion());
146             persistentWrapper.setPrimaryKey(mergedWrapper.getPrimaryKey());
147         }
148
149         List<Method> methods = ReflectionUtils.getAllMethods(aPersistent
150             .getClass(), Object.class);
151
152         for (Method getter : methods) {
153             if ((getter.getName().startsWith("get") || getter.getName()
154                 .startsWith("is")) &&
155                 !Modifier.isStatic(getter.getModifiers()) &&
156                 Modifier.isPublic(getter.getModifiers()) &&
157                 getter.getParameterTypes().length == 0 &&
158                 getter.getReturnType() != Void.class) {
159                 Class returnType = getter.getReturnType();
160
161                 try {
162                     if (Set.class.isAssignableFrom(returnType)) {
163                         Set merged = (Set) getter.invoke(aMerged);
164                         Set persistent = (Set) getter.invoke(aPersistent);
165                         processSet(merged, persistent, aProcessed);
166                     } else if (List.class.isAssignableFrom(returnType)) {
167                         List merged = (List) getter.invoke(aMerged);
168                         List persistent = (List) getter.invoke(aPersistent);
169                         processList(merged, persistent, aProcessed);
170                     } else if (Map.class.isAssignableFrom(returnType)) {
171                         Map merged = (Map) getter.invoke(aMerged);
172                         Map persistent = (Map) getter.invoke(aPersistent);
173                         processMap(merged, persistent, aProcessed);
174                     } else if (returnType.isArray()) {
175                         Object[] merged = (Object[]) getter.invoke(aMerged);
176                         Object[] persistent = (Object[]) getter
177                             .invoke(aPersistent);
178                         if (merged.length != persistent.length) {
179                             throw new IllegalArgumentException(
180                                 "Array sizes differ " + merged.length + " " +
181                                     persistent.length);
182                         }
183                         for (int i = 0; i < persistent.length; i++) {
184                             processPersistent(merged[i], persistent[i],
185                                 aProcessed);
186                         }
187                     } else {
188                         Object merged = getter.invoke(aMerged);
189                         Object persistent = getter.invoke(aPersistent);
190                         processPersistent(merged, persistent, aProcessed);
191                     }
192                 } catch (InvocationTargetException e) {
193                     throw new RuntimeException(e.getMessage(), e);
194                 } catch (IllegalAccessException e) {
195                     throw new RuntimeException(e.getMessage(), e);
196                 }
197             }
198         }
199     }
200
201     /**
202      * Process the persistent objects in the collections.
203      * 
204      * @param aPersistent
205      *            Collection in the original object.
206      * @param aMerged
207      *            Collection as a result of the merge.
208      * @param aProcessed
209      *            List of processed persistent objects.
210      * 
211      */
212     public static void processList(List aMerged, List aPersistent,
213         List<ObjectElem> aProcessed) {
214         Object[] merged = aMerged.toArray();
215         Object[] persistent = aPersistent.toArray();
216
217         if (merged.length != persistent.length) {
218             throw new IllegalArgumentException("Array sizes differ " +
219                 merged.length + " " + persistent.length);
220         }
221
222         for (int i = 0; i < merged.length; i++) {
223             assert merged[i].equals(persistent[i]);
224             processPersistent(merged[i], persistent[i], aProcessed);
225         }
226     }
227
228     /**
229      * Process the persistent objects in sets.
230      * 
231      * @param aPersistent
232      *            Collection in the original object.
233      * @param aMerged
234      *            Collection as a result of the merge.
235      * @param aProcessed
236      *            List of processed persistent objects.
237      * 
238      */
239     public static void processSet(Set aMerged, Set aPersistent,
240         List<ObjectElem> aProcessed) {
241         if (aMerged.size() != aPersistent.size()) {
242             throw new IllegalArgumentException("Array sizes differ " +
243                 aMerged.size() + " " + aPersistent.size());
244         }
245
246         for (Object merged : aMerged) {
247             // Find the object that equals the merged[i]
248             for (Object persistent : aPersistent) {
249                 if (persistent.equals(merged)) {
250                     processPersistent(merged, persistent, aProcessed);
251                     break;
252                 }
253             }
254         }
255     }
256
257     /**
258      * Process the Map objects in the collections.
259      * 
260      * @param aPersistent
261      *            Collection in the original object.
262      * @param aMerged
263      *            Collection as a result of the merge.
264      * @param aProcessed
265      *            List of processed persistent objects.
266      * 
267      */
268     public static <Key, Value> void processMap(Map<Key, Value> aMerged,
269         Map<Key, Value> aPersistent, List<ObjectElem> aProcessed) {
270         if (aMerged.size() != aPersistent.size()) {
271             throw new IllegalArgumentException("Sizes differ " +
272                 aMerged.size() + " " + aPersistent.size());
273         }
274
275         Set<Entry<Key, Value>> entries = aMerged.entrySet();
276
277         for (Entry<Key, Value> entry : entries) {
278             Key key = entry.getKey();
279             if (!aPersistent.containsKey(key)) {
280                 throw new IllegalArgumentException("Key '" + key +
281                     "' not found");
282             }
283
284             Value mergedValue = entry.getValue();
285             Object persistentValue = aPersistent.get(key);
286
287             processPersistent(mergedValue, persistentValue, aProcessed);
288         }
289     }
290
291     /**
292      * This class provided an equality operation based on the object reference
293      * of the wrapped object. This is required because we cannto assume that the
294      * equals operation has any meaning for different types of persistent
295      * objects. This allows us to use the standard collection classes for
296      * detecting cyclic dependences and avoiding recursion.
297      */
298     private static final class ObjectElem {
299         private Object object;
300
301         public ObjectElem(Object aObject) {
302             object = aObject;
303         }
304
305         public boolean equals(Object aObj) {
306             if (aObj == null) {
307                 return false;
308             }
309             if (!(aObj instanceof ObjectElem)) {
310                 return false;
311             }
312             return ((ObjectElem) aObj).object == object;
313         }
314
315         public int hashCode() {
316             return object.hashCode();
317         }
318     }
319 }