1 19 20 21 package org.apache.cayenne.jpa.conf; 22 23 import java.lang.reflect.Method ; 24 import java.lang.reflect.Modifier ; 25 26 import javax.persistence.PostLoad; 27 import javax.persistence.PostPersist; 28 import javax.persistence.PostRemove; 29 import javax.persistence.PostUpdate; 30 import javax.persistence.PrePersist; 31 import javax.persistence.PreRemove; 32 import javax.persistence.PreUpdate; 33 34 import org.apache.cayenne.jpa.map.JpaEntityListener; 35 import org.apache.cayenne.jpa.map.JpaLifecycleCallback; 36 37 53 public class EntityListenerAnnotationLoader { 54 55 59 public JpaEntityListener getEntityListener(Class listenerClass) { 60 JpaEntityListener listener = new JpaEntityListener(); 61 62 boolean hasAnnotations = false; 63 Method [] methods = listenerClass.getDeclaredMethods(); 64 for (int i = 0; i < methods.length; i++) { 65 66 if (isValidListenerMethod(methods[i])) { 67 if (processAnnotations(methods[i], listener)) { 68 hasAnnotations = true; 69 } 70 } 71 } 72 73 if (hasAnnotations) { 74 listener.setClassName(listenerClass.getName()); 75 return listener; 76 } 77 78 return null; 79 } 80 81 85 protected boolean isValidListenerMethod(Method m) { 86 int modifiers = m.getModifiers(); 87 if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { 88 return false; 89 } 90 91 if (!Void.TYPE.equals(m.getReturnType())) { 92 return false; 93 } 94 95 Class [] params = m.getParameterTypes(); 96 if (params.length != 1 || !Object .class.equals(params[0])) { 97 return false; 98 } 99 100 return true; 101 } 102 103 protected boolean processAnnotations(Method method, JpaEntityListener listener) { 104 boolean hasListenerAnnotations = false; 105 106 if (method.isAnnotationPresent(PrePersist.class)) { 107 listener.setPrePersist(new JpaLifecycleCallback(method.getName())); 108 hasListenerAnnotations = true; 109 } 110 111 if (method.isAnnotationPresent(PostPersist.class)) { 112 listener.setPostPersist(new JpaLifecycleCallback(method.getName())); 113 hasListenerAnnotations = true; 114 } 115 116 if (method.isAnnotationPresent(PreRemove.class)) { 117 listener.setPreRemove(new JpaLifecycleCallback(method.getName())); 118 hasListenerAnnotations = true; 119 } 120 121 if (method.isAnnotationPresent(PostRemove.class)) { 122 listener.setPostRemove(new JpaLifecycleCallback(method.getName())); 123 hasListenerAnnotations = true; 124 } 125 126 if (method.isAnnotationPresent(PreUpdate.class)) { 127 listener.setPreUpdate(new JpaLifecycleCallback(method.getName())); 128 hasListenerAnnotations = true; 129 } 130 131 if (method.isAnnotationPresent(PostUpdate.class)) { 132 listener.setPostUpdate(new JpaLifecycleCallback(method.getName())); 133 hasListenerAnnotations = true; 134 } 135 136 if (method.isAnnotationPresent(PostLoad.class)) { 137 listener.setPostLoad(new JpaLifecycleCallback(method.getName())); 138 hasListenerAnnotations = true; 139 } 140 141 return hasListenerAnnotations; 142 } 143 } 144 | Popular Tags |