1 package org.lsst.ccs.command;
2
3 import org.lsst.ccs.command.annotations.Command;
4
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Method;
7 import java.util.Collection;
8 import java.util.HashMap;
9 import java.util.Map;
10
11
12
13
14
15
16
17
18
19
20
21
22 public class CommandDictionaryBuilder implements LocalCommandDictionary {
23
24 private MethodBasedCommandDictionary dict;
25 private final Map<DictionaryCommand, Method> methods = new HashMap<>();
26
27
28
29
30
31
32 CommandDictionaryBuilder(Class klass) {
33 init(klass);
34 }
35
36
37
38
39
40
41 public Dictionary getCommandDictionary() {
42 return dict;
43 }
44
45
46
47
48
49
50
51
52
53 public Method getMethod(BasicCommand command) {
54
55
56 DictionaryCommand dc = dict.findCommand(command);
57 if (dc == null) {
58 return null;
59 }
60 return methods.get(dc);
61 }
62
63
64
65
66
67
68
69 public Method getMethod(DictionaryCommand dc) {
70 if (dc == null) {
71 return null;
72 }
73 return methods.get(dc);
74 }
75
76
77 private static Method[] arrayModel = new Method[0] ;
78
79
80
81 public Collection<Method> getMethods() {
82 return methods.values() ;
83 }
84
85 private void init(Class targetClass) {
86 dict = new MethodBasedCommandDictionary();
87 for (Method targetMethod : targetClass.getMethods()) {
88 Method annotatedMethod = getAnnotationWithInheritance(targetMethod, Command.class);
89 if (annotatedMethod != null) {
90 Command annotation = annotatedMethod.getAnnotation(Command.class);
91 if (annotation != null) {
92 MethodBasedDictionaryCommand dc = new MethodBasedDictionaryCommand(annotatedMethod, annotation);
93 dict.add(dc);
94 methods.put(dc, targetMethod);
95 }
96 }
97 }
98 }
99
100
101
102
103
104
105
106
107
108
109
110 private static <T extends Annotation> Method getAnnotationWithInheritance(Method method, Class<T> annotationClass) {
111 for (;;) {
112 T annotation = method.getAnnotation(annotationClass);
113 if (annotation != null) {
114 return method;
115 }
116 Class superClass = method.getDeclaringClass().getSuperclass();
117 if (superClass == null) {
118 break;
119 }
120 try {
121 method = superClass.getMethod(method.getName(), method.getParameterTypes());
122 } catch (NoSuchMethodException ex) {
123 break;
124 }
125 }
126 return null;
127 }
128 }