Moving towards testability: Model class does not have any public fields, rather instance onces
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.bck2brwsr.htmlpage;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStreamWriter;
23 import java.io.Writer;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.LinkedHashSet;
29 import java.util.List;
30 import java.util.Locale;
33 import javax.annotation.processing.AbstractProcessor;
34 import javax.annotation.processing.Completion;
35 import javax.annotation.processing.Completions;
36 import javax.annotation.processing.Processor;
37 import javax.annotation.processing.RoundEnvironment;
38 import javax.annotation.processing.SupportedAnnotationTypes;
39 import javax.lang.model.element.AnnotationMirror;
40 import javax.lang.model.element.Element;
41 import javax.lang.model.element.ElementKind;
42 import javax.lang.model.element.ExecutableElement;
43 import javax.lang.model.element.Modifier;
44 import javax.lang.model.element.PackageElement;
45 import javax.lang.model.element.TypeElement;
46 import javax.lang.model.element.VariableElement;
47 import javax.lang.model.type.MirroredTypeException;
48 import javax.lang.model.type.TypeMirror;
49 import javax.tools.Diagnostic;
50 import javax.tools.FileObject;
51 import javax.tools.StandardLocation;
52 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
53 import org.apidesign.bck2brwsr.htmlpage.api.On;
54 import org.apidesign.bck2brwsr.htmlpage.api.Page;
55 import org.apidesign.bck2brwsr.htmlpage.api.Property;
56 import org.openide.util.lookup.ServiceProvider;
58 /** Annotation processor to process an XHTML page and generate appropriate
61 * @author Jaroslav Tulach <jtulach@netbeans.org>
63 @ServiceProvider(service=Processor.class)
64 @SupportedAnnotationTypes({
65 "org.apidesign.bck2brwsr.htmlpage.api.Page",
66 "org.apidesign.bck2brwsr.htmlpage.api.On"
68 public final class PageProcessor extends AbstractProcessor {
70 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
71 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
72 Page p = e.getAnnotation(Page.class);
73 PackageElement pe = (PackageElement)e.getEnclosingElement();
74 String pkg = pe.getQualifiedName().toString();
78 InputStream is = openStream(pkg, p.xhtml());
79 pp = ProcessPage.readPage(is);
81 } catch (IOException iOException) {
82 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
86 String className = p.className();
87 if (className.isEmpty()) {
88 int indx = p.xhtml().indexOf('.');
89 className = p.xhtml().substring(0, indx);
92 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
93 w = new OutputStreamWriter(java.openOutputStream());
95 w.append("package " + pkg + ";\n");
96 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
97 w.append("final class ").append(className).append(" {\n");
98 w.append(" private static boolean locked;\n");
99 w.append(" public ").append(className).append("() {\n");
100 if (!initializeOnClick((TypeElement) e, w, pp)) {
104 for (String id : pp.ids()) {
105 String tag = pp.tagNameForId(id);
106 String type = type(tag);
107 w.append(" ").append("public final ").
108 append(type).append(' ').append(cnstnt(id)).append(" = new ").
109 append(type).append("(\"").append(id).append("\");\n");
111 List<String> propsGetSet = new ArrayList<String>();
112 Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
113 generateComputedProperties(w, e.getEnclosedElements(), propsGetSet, propsDeps);
114 generateProperties(w, p.properties(), propsGetSet, propsDeps);
115 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
116 if (!propsGetSet.isEmpty()) {
117 w.write("public " + className + " applyBindings() {\n");
118 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
119 w.write(className + ".class, new " + className + "(), ");
120 w.write("new String[] {\n");
122 for (String n : propsGetSet) {
127 w.write(" \"" + n + "\"");
131 w.write("\n });\n return this;\n}\n");
137 } catch (IOException ex) {
138 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
145 private InputStream openStream(String pkg, String name) throws IOException {
147 FileObject fo = processingEnv.getFiler().getResource(
148 StandardLocation.SOURCE_PATH, pkg, name);
149 return fo.openInputStream();
150 } catch (IOException ex) {
151 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
155 private static String type(String tag) {
156 if (tag.equals("title")) {
159 if (tag.equals("button")) {
162 if (tag.equals("input")) {
168 private static String cnstnt(String id) {
169 return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
172 private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
173 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
174 { //for (Element clazz : pe.getEnclosedElements()) {
175 // if (clazz.getKind() != ElementKind.CLASS) {
178 for (Element method : type.getEnclosedElements()) {
179 On oc = method.getAnnotation(On.class);
181 for (String id : oc.id()) {
182 if (pp.tagNameForId(id) == null) {
183 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
186 ExecutableElement ee = (ExecutableElement)method;
188 if (ee.getParameters().isEmpty()) {
191 if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
192 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
197 if (!ee.getModifiers().contains(Modifier.STATIC)) {
198 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
201 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
202 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
205 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
206 append(").perform(new Runnable() { public void run() {\n");
207 w.append(" ").append(type.getSimpleName().toString()).
208 append('.').append(ee.getSimpleName()).append("(");
210 w.append("\"").append(id).append("\"");
222 public Iterable<? extends Completion> getCompletions(
223 Element element, AnnotationMirror annotation,
224 ExecutableElement member, String userText
226 if (!userText.startsWith("\"")) {
227 return Collections.emptyList();
230 Element cls = findClass(element);
231 Page p = cls.getAnnotation(Page.class);
232 PackageElement pe = (PackageElement) cls.getEnclosingElement();
233 String pkg = pe.getQualifiedName().toString();
236 InputStream is = openStream(pkg, p.xhtml());
237 pp = ProcessPage.readPage(is);
239 } catch (IOException iOException) {
240 return Collections.emptyList();
243 List<Completion> cc = new ArrayList<Completion>();
244 userText = userText.substring(1);
245 for (String id : pp.ids()) {
246 if (id.startsWith(userText)) {
247 cc.add(Completions.of("\"" + id + "\"", id));
253 private static Element findClass(Element e) {
257 Page p = e.getAnnotation(Page.class);
261 return e.getEnclosingElement();
264 private static void generateProperties(
265 Writer w, Property[] properties, Collection<String> props,
266 Map<String,Collection<String>> deps
267 ) throws IOException {
268 for (Property p : properties) {
269 final String tn = typeName(p);
270 String[] gs = toGetSet(p.name(), tn);
272 w.write("private " + tn + " prop_" + p.name() + ";\n");
273 w.write("public " + tn + " " + gs[0] + "() {\n");
274 w.write(" if (locked) throw new IllegalStateException();\n");
275 w.write(" return prop_" + p.name() + ";\n");
277 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
278 w.write(" if (locked) throw new IllegalStateException();\n");
279 w.write(" prop_" + p.name() + " = v;\n");
280 w.write(" if (ko != null) {\n");
281 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
282 final Collection<String> dependants = deps.get(p.name());
283 if (dependants != null) {
284 for (String depProp : dependants) {
285 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
297 private boolean generateComputedProperties(
298 Writer w, Collection<? extends Element> arr, Collection<String> props,
299 Map<String,Collection<String>> deps
300 ) throws IOException {
301 for (Element e : arr) {
302 if (e.getKind() != ElementKind.METHOD) {
305 if (e.getAnnotation(ComputedProperty.class) == null) {
308 ExecutableElement ee = (ExecutableElement)e;
309 final String tn = ee.getReturnType().toString();
310 final String sn = ee.getSimpleName().toString();
311 String[] gs = toGetSet(sn, tn);
313 w.write("public " + tn + " " + gs[0] + "() {\n");
314 w.write(" if (locked) throw new IllegalStateException();\n");
316 for (VariableElement pe : ee.getParameters()) {
317 final String dn = pe.getSimpleName().toString();
318 final String dt = pe.asType().toString();
319 String[] call = toGetSet(dn, dt);
320 w.write(" " + dt + " arg" + (++arg) + " = ");
321 w.write(call[0] + "();\n");
323 Collection<String> depends = deps.get(dn);
324 if (depends == null) {
325 depends = new LinkedHashSet<String>();
326 deps.put(dn, depends);
331 w.write(" locked = true;\n");
332 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
334 for (int i = 1; i <= arg; i++) {
340 w.write(" } finally {\n");
341 w.write(" locked = false;\n");
345 props.add(e.getSimpleName().toString());
353 private static String[] toGetSet(String name, String type) {
354 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
355 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
356 if ("int".equals(type)) {
359 if ("double".equals(type)) {
363 if ("boolean".equals(type)) {
367 final String nu = n.replace('.', '_');
371 pref + nu + "__" + bck2brwsrType,
372 "set" + nu + "__V" + bck2brwsrType
376 private static String typeName(Property p) {
378 return p.type().getName();
379 } catch (MirroredTypeException ex) {
380 return ex.getTypeMirror().toString();