01: package org.vraptor.plugin.jpa;
02:
03: import java.lang.reflect.Constructor;
04: import java.lang.reflect.Field;
05:
06: import javax.persistence.EntityManager;
07: import javax.persistence.PersistenceContext;
08:
09: import org.vraptor.component.ComponentType;
10: import org.vraptor.component.LogicMethod;
11:
12: /**
13: * Reads JPA related metadata on {@link ComponentType}s
14: *
15: * @author Fabio Kung
16: * @since 2.3.2
17: */
18: class EntityManagerIntrospector {
19:
20: public static final String DEFAULT_PERSISTENCE_UNIT = "default";
21:
22: /**
23: *
24: * @param componentType
25: * @return the {@link PersistenceContext} annotated field if exists, null
26: * otherwise
27: */
28: public Field getEntityManagerField(ComponentType componentType) {
29: Class<?> componentClass = componentType.getComponentClass();
30: for (Field field : componentClass.getDeclaredFields()) {
31: if (field.isAnnotationPresent(PersistenceContext.class)) {
32: return field;
33: }
34: }
35: return null;
36: }
37:
38: /**
39: * Checks if the component has any constructor dependency on
40: * {@link EntityManager}
41: *
42: * @param component
43: * @return true if the component has constructor dependency
44: */
45: public boolean dependsOnEntityManager(ComponentType component) {
46: for (Constructor constructor : component.getComponentClass()
47: .getConstructors()) {
48: for (Class<?> dependency : constructor.getParameterTypes()) {
49: if (EntityManager.class.equals(dependency)) {
50: return true;
51: }
52: }
53: }
54: return false;
55: }
56:
57: public boolean hasPersistenceContext(ComponentType component) {
58: for (Field field : component.getComponentClass()
59: .getDeclaredFields()) {
60: if (field.isAnnotationPresent(PersistenceContext.class)) {
61: return true;
62: }
63:
64: }
65: return false;
66: }
67:
68: public String getPersistenceUnitName(ComponentType componentType) {
69: String persistenceUnit = DEFAULT_PERSISTENCE_UNIT;
70: Field entityManagerField = this
71: .getEntityManagerField(componentType);
72:
73: if (entityManagerField != null) {
74: PersistenceContext persistenceContext = entityManagerField
75: .getAnnotation(PersistenceContext.class);
76: if (persistenceContext.unitName().trim().length() != 0) {
77: persistenceUnit = persistenceContext.unitName();
78: }
79:
80: }
81: return persistenceUnit;
82: }
83:
84: public boolean isTransactionRequired(LogicMethod method) {
85: Transaction transactionMetadata = method.getMetadata()
86: .getAnnotation(Transaction.class);
87: return transactionMetadata != null
88: && transactionMetadata.required();
89: }
90:
91: }
|