944bd34aa3a028df0543626e86205f70bfb6fcbb
[utils] / support / general / src / main / java / org / wamblee / persistence / PersistentFactory.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.annotation.Annotation;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.concurrent.ConcurrentHashMap;
25
26 import javax.persistence.Id;
27 import javax.persistence.Version;
28
29 import org.wamblee.reflection.ReflectionUtils;
30
31 /**
32  * Factory which creates a {@link Persistent} object for a given JPA entity for
33  * interfacing with the primary key and version of the entity.
34  * 
35  * This utility only treats primary keys and fields that are annotated with @Id
36  * and @Version. In case ORM files are used for the definition of primary key
37  * and or version, then those fields are ignored.
38  * 
39  * @author Erik Brakkee
40  * 
41  */
42 public class PersistentFactory {
43
44     /**
45      * Cache of a mapping of class names to entity accessors.
46      */
47     private static Map<String, EntityAccessor> CACHE = new ConcurrentHashMap<String, EntityAccessor>();
48
49     public static interface Accessor<T> {
50         void set(Object aEntity, T aValue);
51
52         T get(Object aEntity);
53     }
54
55     static class FieldAccessor<T> implements Accessor<T> {
56         private Field field;
57
58         public FieldAccessor(Field aField) {
59             field = aField;
60             field.setAccessible(true);
61         }
62
63         @Override
64         public T get(Object aEntity) {
65             try {
66                 T value = (T) field.get(aEntity);
67                 return value;
68             } catch (Exception e) {
69                 throw new RuntimeException(e);
70             }
71         }
72
73         @Override
74         public void set(Object aEntity, T aValue) {
75             try {
76                 field.set(aEntity, aValue);
77             } catch (IllegalAccessException e) {
78                 throw new RuntimeException(e.getMessage(), e);
79             }
80         }
81
82         public Field getField() {
83             return field;
84         }
85     }
86
87     static class PropertyAccessor<T> implements Accessor<T> {
88         private Method getter;
89         private Method setter;
90
91         public PropertyAccessor(Method aGetter, Method aSetter) {
92             getter = aGetter;
93             setter = aSetter;
94             getter.setAccessible(true);
95             setter.setAccessible(true);
96         }
97
98         @Override
99         public T get(Object aEntity) {
100             try {
101                 return (T) getter.invoke(aEntity);
102             } catch (Exception e) {
103                 throw new RuntimeException(e);
104             }
105         }
106
107         @Override
108         public void set(Object aEntity, T aValue) {
109             try {
110                 setter.invoke(aEntity, aValue);
111             } catch (Exception e) {
112                 throw new RuntimeException(e);
113             }
114         }
115
116         public Method getGetter() {
117             return getter;
118         }
119
120         public Method getSetter() {
121             return setter;
122         }
123     }
124
125     static class EntityAccessor {
126         private Accessor pk;
127         private Accessor version;
128
129         public EntityAccessor(Accessor<?> aPk, Accessor<?> aVersion) {
130             pk = aPk;
131             version = aVersion;
132         }
133
134         public Accessor getPk() {
135             return pk;
136         }
137
138         public Accessor getVersion() {
139             return version;
140         }
141     }
142
143     public static class EntityObjectAccessor implements Persistent {
144         private EntityAccessor accessor;
145         private Object entity;
146
147         public EntityObjectAccessor(Object aEntity, EntityAccessor aAccessor) {
148             accessor = aAccessor;
149             entity = aEntity;
150         }
151
152         public EntityAccessor getAccessor() {
153             return accessor;
154         };
155
156         @Override
157         public Serializable getPrimaryKey() {
158             if (accessor == null || accessor.getPk() == null) {
159                 return null;
160             }
161             return (Serializable) accessor.getPk().get(entity);
162         }
163
164         @Override
165         public void setPrimaryKey(Serializable aKey) {
166             if (accessor == null || accessor.getPk() == null) {
167                 return;
168             }
169             accessor.getPk().set(entity, aKey);
170         }
171
172         @Override
173         public Number getPersistedVersion() {
174             if (accessor == null || accessor.getVersion() == null) {
175                 return null;
176             }
177             return (Number) accessor.getVersion().get(entity);
178         }
179
180         @Override
181         public void setPersistedVersion(Number aVersion) {
182             if (accessor == null || accessor.getVersion() == null) {
183                 return;
184             }
185             accessor.getVersion().set(entity, aVersion);
186         }
187     }
188
189     /**
190      * Create the entity accessor for a given class or returns a cached instance
191      * if one already exists.
192      * 
193      * @param aClass
194      *            Class.
195      * @return Entity accessor for the given class or null of the given object
196      *         is not an entity.
197      */
198     public static EntityAccessor createEntityAccessor(Class aClass) {
199         EntityAccessor accessor = CACHE.get(aClass.getName());
200         if (accessor == null) {
201             accessor = analyse(aClass);
202             if (accessor != null) {
203                 CACHE.put(aClass.getName(), accessor);
204             }
205         }
206         return accessor;
207     }
208
209     private static EntityAccessor analyse(Class aClass) {
210         Accessor<Serializable> pk = analyse(aClass, Id.class);
211         Accessor<Integer> version = analyse(aClass, Version.class);
212         if (pk != null || version != null) {
213             return new EntityAccessor(pk, version);
214         }
215         return null;
216     }
217
218     /**
219      * Returns the accessor for a given annotation.
220      * 
221      * @param aClass
222      *            Class to analyse.
223      * @param aAnnotation
224      *            Annotation that must be present.
225      * @return Accessor to use or null if the annotation is not present.
226      */
227     // TODO move generic analysis part to the reflection package.
228     public static Accessor analyse(Class aClass,
229         Class<? extends Annotation> aAnnotation) {
230         List<Field> fields = ReflectionUtils.getAllFields(aClass);
231         for (Field field : fields) {
232             if (field.isAnnotationPresent(aAnnotation)) {
233                 return new FieldAccessor(field);
234             }
235         }
236         List<Method> methods = ReflectionUtils.getAllMethods(aClass,
237             Object.class);
238         for (Method method : methods) {
239             if (method.isAnnotationPresent(aAnnotation)) {
240                 String setterName = null;
241                 if (method.getName().startsWith("get")) {
242                     setterName = method.getName().replaceFirst("get", "set");
243                 } else if (method.getName().startsWith("is")) {
244                     setterName = method.getName().replaceFirst("is", "set");
245                 }
246                 try {
247                     Class returnType = method.getReturnType();
248                     Method setter = method.getDeclaringClass()
249                         .getDeclaredMethod(setterName, returnType);
250                     return new PropertyAccessor(method, setter);
251                 } catch (NoSuchMethodException e) {
252                     throw new RuntimeException("Error obtaining setter for " +
253                         method.getName() + " in class " + aClass.getName(), e);
254                 }
255             }
256         }
257         return null;
258     }
259
260     /**
261      * Creates the {@link Persistent} wrapper for interfacing with primary key
262      * and version of the entity.
263      * 
264      * @param aEntity
265      *            Entity to use.
266      * @return Persistent object or null if this is not an entity.
267      */
268     public static Persistent create(Object aEntity) {
269         EntityAccessor accessor = createEntityAccessor(aEntity.getClass());
270         if (accessor == null) {
271             return null;
272         }
273         return new EntityObjectAccessor(aEntity, accessor);
274     }
275 }