1 19 20 21 package org.apache.cayenne.jpa.conf; 22 23 import java.lang.annotation.Annotation ; 24 import java.lang.reflect.AnnotatedElement ; 25 import java.util.HashMap ; 26 import java.util.Map ; 27 28 36 abstract class AnnotationProcessorFactory { 37 38 static final String ANNOTATIONS_PACKAGE = "javax.persistence."; 39 static final String PROCESSOR_NAME_SUFFIX = "Processor"; 40 static final AnnotationProcessor NOOP_PROCESSOR = new AnnotationProcessor() { 41 42 public void onFinishElement( 43 AnnotatedElement element, 44 AnnotationProcessorStack context) { 45 } 46 47 public void onStartElement( 48 AnnotatedElement element, 49 AnnotationProcessorStack context) { 50 } 51 }; 52 53 56 static Class processorClass(Class factoryClass, String annotationFQN) { 57 if (annotationFQN.startsWith(ANNOTATIONS_PACKAGE)) { 58 59 62 64 String processorName = factoryClass.getName() 65 + "$" 66 + annotationFQN.substring(ANNOTATIONS_PACKAGE.length()) 67 + PROCESSOR_NAME_SUFFIX; 68 69 try { 70 return Class.forName(processorName, true, Thread 71 .currentThread() 72 .getContextClassLoader()); 73 74 } 75 catch (Exception e) { 76 return null; 79 } 80 } 81 else { 82 return null; 83 } 84 85 } 86 87 90 static Class annotationClass(Class processorClass) { 91 String name = processorClass.getName(); 92 if (!name.endsWith(PROCESSOR_NAME_SUFFIX)) { 93 return null; 94 } 95 96 int split = name.lastIndexOf('$'); 97 if (split <= 0) { 98 return null; 99 } 100 101 String className = name.substring(split + 1); 102 String annotationFQN = ANNOTATIONS_PACKAGE 103 + className.substring(0, className.length() 104 - PROCESSOR_NAME_SUFFIX.length()); 105 106 try { 107 return Class.forName(annotationFQN, true, Thread 108 .currentThread() 109 .getContextClassLoader()); 110 111 } 112 catch (Exception e) { 113 return null; 116 } 117 } 118 119 final Map <String , AnnotationProcessor> processors; 120 121 AnnotationProcessorFactory() { 122 this.processors = new HashMap <String , AnnotationProcessor>(); 123 } 124 125 129 AnnotationProcessor getProcessor(Annotation annotation) { 130 131 String annotationName = annotation.annotationType().getName(); 132 AnnotationProcessor processor = processors.get(annotationName); 133 134 if (processor == null) { 135 processor = createProcessor(annotationName); 136 processors.put(annotationName, processor); 137 } 138 139 return processor == NOOP_PROCESSOR ? null : processor; 140 } 141 142 145 AnnotationProcessor createProcessor(String annotationFQN) { 146 147 Class processorClass = processorClass(getClass(), annotationFQN); 148 149 if (processorClass != null) { 150 151 try { 152 return (AnnotationProcessor) processorClass.newInstance(); 153 } 154 catch (Exception e) { 155 return NOOP_PROCESSOR; 156 } 157 } 158 159 return NOOP_PROCESSOR; 161 } 162 } 163 | Popular Tags |