(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 import java.util.logging.Logger;
28
29 import javax.persistence.EntityManager;
30
31 import org.wamblee.general.ObjectElem;
32 import org.wamblee.reflection.ReflectionUtils;
33
34 /**
35  * Support for merging of JPA entities. This utility allows the result of a
36  * merge (modifications of primary key and/or version) to be merged back into
37  * the argument that was merged. As a result, the merged entity can be reused
38  * and the application is not forced to use the new version that was returned
39  * from the merge.
40  * 
41  * The utility traverses the object graph based on the public getter methods.
42  * Therefore, care should be taken with this utility as usage could lead to
43  * recursively loading all objects reachable from the given object. Then again,
44  * this utility is for working with detached objects and it would, in general,
45  * be bad practice to work with detached objects that still contain unresolved
46  * lazy loaded relations and with detached objects that implicitly refer to
47  * almost the entire datamodel.
48  * 
49  * This utility best supports a service oriented design where interaction is
50  * through service interfaces where each service has its own storage isolated
51  * from other services. That would be opposed to a shared data design with many
52  * services acting on the same data.
53  * 
54  * @author Erik Brakkee
55  */
56 public class JpaMergeSupport {
57     private static final Logger LOG = Logger.getLogger(JpaMergeSupport.class
58         .getName());
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.fine("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         }
144         persistentWrapper.setPersistedVersion(mergedWrapper
145             .getPersistedVersion());
146         persistentWrapper.setPrimaryKey(mergedWrapper.getPrimaryKey());
147
148         List<Method> methods = ReflectionUtils.getAllMethods(aPersistent
149             .getClass(), Object.class);
150
151         for (Method getter : methods) {
152             if ((getter.getName().startsWith("get") || getter.getName()
153                 .startsWith("is")) &&
154                 !Modifier.isStatic(getter.getModifiers()) &&
155                 Modifier.isPublic(getter.getModifiers()) &&
156                 getter.getParameterTypes().length == 0 &&
157                 getter.getReturnType() != Void.class) {
158                 Class returnType = getter.getReturnType();
159
160                 try {
161                     if (Set.class.isAssignableFrom(returnType)) {
162                         Set merged = (Set) getter.invoke(aMerged);
163                         Set persistent = (Set) getter.invoke(aPersistent);
164                         processSet(merged, persistent, aProcessed);
165                     } else if (List.class.isAssignableFrom(returnType)) {
166                         List merged = (List) getter.invoke(aMerged);
167                         List persistent = (List) getter.invoke(aPersistent);
168                         processList(merged, persistent, aProcessed);
169                     } else if (Map.class.isAssignableFrom(returnType)) {
170                         Map merged = (Map) getter.invoke(aMerged);
171                         Map persistent = (Map) getter.invoke(aPersistent);
172                         processMap(merged, persistent, aProcessed);
173                     } else if (returnType.isArray()) {
174                         Object[] merged = (Object[]) getter.invoke(aMerged);
175                         Object[] persistent = (Object[]) getter
176                             .invoke(aPersistent);
177                         if (merged.length != persistent.length) {
178                             throw new IllegalArgumentException(
179                                 "Array sizes differ " + merged.length + " " +
180                                     persistent.length);
181                         }
182                         for (int i = 0; i < persistent.length; i++) {
183                             processPersistent(merged[i], persistent[i],
184                                 aProcessed);
185                         }
186                     } else {
187                         Object merged = getter.invoke(aMerged);
188                         Object persistent = getter.invoke(aPersistent);
189                         processPersistent(merged, persistent, aProcessed);
190                     }
191                 } catch (InvocationTargetException e) {
192                     throw new RuntimeException(e.getMessage(), e);
193                 } catch (IllegalAccessException e) {
194                     throw new RuntimeException(e.getMessage(), e);
195                 }
196             }
197         }
198     }
199
200     /**
201      * Process the persistent objects in the collections.
202      * 
203      * @param aPersistent
204      *            Collection in the original object.
205      * @param aMerged
206      *            Collection as a result of the merge.
207      * @param aProcessed
208      *            List of processed persistent objects.
209      * 
210      */
211     public static void processList(List aMerged, List aPersistent,
212         List<ObjectElem> aProcessed) {
213         Object[] merged = aMerged.toArray();
214         Object[] persistent = aPersistent.toArray();
215
216         if (merged.length != persistent.length) {
217             throw new IllegalArgumentException("Array sizes differ " +
218                 merged.length + " " + persistent.length);
219         }
220
221         for (int i = 0; i < merged.length; i++) {
222             assert merged[i].equals(persistent[i]);
223             processPersistent(merged[i], persistent[i], aProcessed);
224         }
225     }
226
227     /**
228      * Process the persistent objects in sets.
229      * 
230      * @param aPersistent
231      *            Collection in the original object.
232      * @param aMerged
233      *            Collection as a result of the merge.
234      * @param aProcessed
235      *            List of processed persistent objects.
236      * 
237      */
238     public static void processSet(Set aMerged, Set aPersistent,
239         List<ObjectElem> aProcessed) {
240         if (aMerged.size() != aPersistent.size()) {
241             throw new IllegalArgumentException("Array sizes differ " +
242                 aMerged.size() + " " + aPersistent.size());
243         }
244
245         for (Object merged : aMerged) {
246             // Find the object that equals the merged[i]
247             for (Object persistent : aPersistent) {
248                 if (persistent.equals(merged)) {
249                     processPersistent(merged, persistent, aProcessed);
250                     break;
251                 }
252             }
253         }
254     }
255
256     /**
257      * Process the Map objects in the collections.
258      * 
259      * @param aPersistent
260      *            Collection in the original object.
261      * @param aMerged
262      *            Collection as a result of the merge.
263      * @param aProcessed
264      *            List of processed persistent objects.
265      * 
266      */
267     public static <Key, Value> void processMap(Map<Key, Value> aMerged,
268         Map<Key, Value> aPersistent, List<ObjectElem> aProcessed) {
269         if (aMerged.size() != aPersistent.size()) {
270             throw new IllegalArgumentException("Sizes differ " +
271                 aMerged.size() + " " + aPersistent.size());
272         }
273
274         Set<Entry<Key, Value>> entries = aMerged.entrySet();
275
276         for (Entry<Key, Value> entry : entries) {
277             Key key = entry.getKey();
278             if (!aPersistent.containsKey(key)) {
279                 throw new IllegalArgumentException("Key '" + key +
280                     "' not found");
281             }
282
283             Value mergedValue = entry.getValue();
284             Object persistentValue = aPersistent.get(key);
285
286             processPersistent(mergedValue, persistentValue, aProcessed);
287         }
288     }
289 }