1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
package test;
import javax.annotation.Generated;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public final class SimpleProcessor extends AbstractProcessor {
private final Map<TypeElement, List<Item>> collectedElements = new HashMap<>();
private static String callbacksClassName(TypeElement ce) {
return ce.getSimpleName() + "Callbacks";
}
private static String capitalize(String str) {
char[] chars = str.toCharArray();
return String.valueOf(chars[0]).toUpperCase() + String.valueOf(Arrays.copyOfRange(chars, 1, chars.length));
}
private static String callbacksSubClassName(Item item) {
return "On" + capitalize(item.element.getSimpleName().toString());
}
private static String callbackName(TypeElement ce, Item item) {
return callbacksClassName(ce) + '.' + callbacksSubClassName(item);
}
private static String eventName(TypeElement ce, Item item) {
return ce.getSimpleName() + fieldName(item);
}
private static String fieldName(Item item) {
return "On" + capitalize(item.element.getSimpleName().toString()) + "Event";
}
private static String toString(VariableElement var, boolean printNames) {
final StringBuilder builder = new StringBuilder();
if (printNames) {
for (final AnnotationMirror annotation : var.getAnnotationMirrors())
builder.append(annotation).append(' ');
}
builder.append(var.asType());
if (printNames)
builder.append(' ').append(var);
return builder.toString();
}
private static void generateEmit(BufferedWriter bw, TypeElement ce, Item item) throws IOException {
bw.append(" private static void emit(").append(eventName(ce, item)).append(" event, ").append(ce.getSimpleName()).append(" emmiter");
for (final VariableElement variableElement : item.element.getParameters())
bw.append(", ").append(toString(variableElement, true));
bw.append(") {\n");
bw.append(" final Collection<").append(callbackName(ce, item)).append("> callbacksSafe = event.callbacks;\n");
bw.append(" if (callbacksSafe == null)\n");
bw.append(" return;\n");
bw.append(" for (final ").append(callbackName(ce, item)).append(" callback : new ArrayList<>(callbacksSafe))\n");
bw.append(" callback.changed(emmiter");
for (final VariableElement variableElement : item.element.getParameters())
bw.append(", ").append(variableElement.getSimpleName());
bw.append(");\n");
bw.append(" }\n");
bw.newLine();
}
private static void generateEvent(BufferedWriter bw, TypeElement ce, Item item) throws IOException {
bw.append(" public static final class ").append(eventName(ce, item)).append(" {\n");
bw.append(" private Collection<").append(callbackName(ce, item)).append("> callbacks = null;\n");
bw.append("\n");
bw.append(" ").append(eventName(ce, item)).append("() {\n");
bw.append(" }\n");
bw.append("\n");
bw.append(" public void add(").append(callbackName(ce, item)).append(" callback) {\n");
bw.append(" Collection<").append(callbackName(ce, item)).append("> callbacksSafe = callbacks;\n");
bw.append(" if (callbacksSafe == null) {\n");
bw.append(" callbacksSafe = new ArrayList<>(1);\n");
bw.append(" callbacks = callbacksSafe;\n");
bw.append(" }\n");
bw.append(" callbacksSafe.add(callback);\n");
bw.append(" }\n");
bw.append("\n");
bw.append(" public void clean() {\n");
bw.append(" callbacks = null;\n");
bw.append(" }\n");
bw.append(" }");
bw.newLine();
bw.newLine();
}
private static void generateField(BufferedWriter bw, TypeElement ce, Item item) throws IOException {
bw.append(" @SuppressWarnings(\"PublicField\")\n");
bw.append(" public final ").append(eventName(ce, item)).append(' ').append(ce.getQualifiedName()).append('.').append(fieldName(item))
.append(" = new ").append(eventName(ce, item)).append("();\n");
bw.newLine();
}
private static void generatePointcut(BufferedWriter bw, TypeElement ce, Item item) throws IOException {
bw.append(" ").append(item.description.value().name().toLowerCase()).append("(): execution(").append(item.element.getReturnType().toString()).append(' ').append(ce.getQualifiedName()).append('.')
.append(item.element.getSimpleName()).append('(');
for (final Iterator<? extends TypeParameterElement> i = item.element.getTypeParameters().iterator(); i.hasNext(); ) {
bw.append(i.next().getSimpleName());
if (i.hasNext())
bw.append(", ");
}
bw.append(")) {\n");
bw.append(" final ").append(ce.getQualifiedName()).append(" emmiter = (").append(ce.getQualifiedName()).append(") thisJoinPoint.getThis();\n");
bw.append(" emit(emmiter.").append(fieldName(item)).append(", emmiter");
final List<? extends VariableElement> parameters = item.element.getParameters();
for (int i = 0, s = parameters.size(); i < s; i++) {
final VariableElement element = parameters.get(i);
final TypeMirror type = element.asType();
bw.append(", ").append('(').append(type.toString()).append(") thisJoinPoint.getArgs()[").append(Integer.toString(i)).append(']');
}
bw.append(");\n");
bw.append(" }");
bw.newLine();
bw.newLine();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(Event.class.getName());
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
generateAll();
return true;
}
for (final Element elem : roundEnv.getElementsAnnotatedWith(Event.class)) {
final Event description = elem.getAnnotation(Event.class);
if (description == null)
continue;
if (elem.getKind() == ElementKind.FIELD) {
// TODO(yushkovskiy): implement this
continue;
}
if (elem.getKind() != ElementKind.METHOD)
continue;
final ExecutableElement exeElement = (ExecutableElement) elem;
final Element enclosingElement = exeElement.getEnclosingElement();
final TypeElement classElement = (TypeElement) enclosingElement;
List<Item> items = collectedElements.get(classElement);
if (items == null) {
items = new ArrayList<>();
collectedElements.put(classElement, items);
}
items.add(new Item(exeElement, description));
}
return true; // no further processing of this annotation type
}
private void generateCallbacks(TypeElement ce, List<Item> items) throws IOException {
final PackageElement packageElement = (PackageElement) ce.getEnclosingElement();
final JavaFileObject jfo = processingEnv.getFiler().createSourceFile(packageElement.getQualifiedName().toString() + '.' + callbacksClassName(ce));
try (final BufferedWriter bw = new BufferedWriter(jfo.openWriter())) {
bw.append("package ").append(packageElement.getQualifiedName()).append(";");
bw.newLine();
bw.newLine();
bw.append("/**\n").append(" * Events' callbacks for ").append(ce.getQualifiedName()).append(".\n").append(" *\n").append(" * @author ").append(SimpleProcessor.class.getCanonicalName()).append("\n").append(" */");
bw.newLine();
bw.append("public final class ").append(callbacksClassName(ce)).append(" {");
bw.newLine();
for (final Item item : items) {
bw.append(" public interface ").append(callbacksSubClassName(item)).append(" {\n");
bw.append(" void changed(").append(ce.getSimpleName()).append(" emmiter");
for (final VariableElement var : item.element.getParameters())
bw.append(", ").append(toString(var, true));
bw.append(");\n");
bw.append(" }");
bw.newLine();
bw.newLine();
}
bw.append("}");
bw.newLine();
bw.newLine();
}
}
private void generateAll() {
for (final Map.Entry<TypeElement, List<Item>> entry : collectedElements.entrySet()) {
final TypeElement classElement = entry.getKey();
final PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
try {
final FileObject jfo = processingEnv.getFiler().createResource(
StandardLocation.SOURCE_OUTPUT,
packageElement.getQualifiedName(),
classElement.getSimpleName() + "EventsAspect.aj");
try (final BufferedWriter bw = new BufferedWriter(jfo.openWriter())) {
bw.append("package ").append(packageElement.getQualifiedName()).append(";");
bw.newLine();
bw.append("import java.util.ArrayList;\n");
bw.append("import java.util.Collection;");
bw.newLine();
bw.newLine();
bw.append("/**\n").append(" * Events for ").append(classElement.getQualifiedName()).append(".\n").append(" *\n").append(" * @author ").append(SimpleProcessor.class.getCanonicalName()).append("\n").append(" */");
bw.newLine();
bw.append("@").append(Generated.class.getCanonicalName()).append("(\"").append(SimpleProcessor.class.getCanonicalName()).append("\")");
bw.newLine();
bw.append("final aspect ").append(classElement.getSimpleName()).append("EventsAspect").append(" {");
bw.newLine();
bw.newLine();
generateCallbacks(classElement, entry.getValue());
for (final Item item : entry.getValue()) {
generateEvent(bw, classElement, item);
generateEmit(bw, classElement, item);
generateField(bw, classElement, item);
generatePointcut(bw, classElement, item);
}
bw.append("}");
bw.newLine();
bw.newLine();
}
} catch (final Throwable e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
}
}
}
private static final class Item {
private final ExecutableElement element;
private final Event description;
private Item(ExecutableElement element, Event description) {
this.element = element;
this.description = description;
}
}
}
|