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.StringWriter;
24 import java.io.Writer;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedHashSet;
30 import java.util.List;
33 import java.util.WeakHashMap;
34 import javax.annotation.processing.AbstractProcessor;
35 import javax.annotation.processing.Completion;
36 import javax.annotation.processing.Completions;
37 import javax.annotation.processing.Messager;
38 import javax.annotation.processing.Processor;
39 import javax.annotation.processing.RoundEnvironment;
40 import javax.annotation.processing.SupportedAnnotationTypes;
41 import javax.lang.model.element.AnnotationMirror;
42 import javax.lang.model.element.Element;
43 import javax.lang.model.element.ElementKind;
44 import javax.lang.model.element.ExecutableElement;
45 import javax.lang.model.element.Modifier;
46 import javax.lang.model.element.PackageElement;
47 import javax.lang.model.element.TypeElement;
48 import javax.lang.model.element.VariableElement;
49 import javax.lang.model.type.ArrayType;
50 import javax.lang.model.type.DeclaredType;
51 import javax.lang.model.type.MirroredTypeException;
52 import javax.lang.model.type.TypeKind;
53 import javax.lang.model.type.TypeMirror;
54 import javax.lang.model.util.Elements;
55 import javax.lang.model.util.Types;
56 import javax.tools.Diagnostic;
57 import javax.tools.FileObject;
58 import javax.tools.StandardLocation;
59 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
60 import org.apidesign.bck2brwsr.htmlpage.api.Model;
61 import org.apidesign.bck2brwsr.htmlpage.api.On;
62 import org.apidesign.bck2brwsr.htmlpage.api.OnFunction;
63 import org.apidesign.bck2brwsr.htmlpage.api.OnReceive;
64 import org.apidesign.bck2brwsr.htmlpage.api.Page;
65 import org.apidesign.bck2brwsr.htmlpage.api.Property;
66 import org.openide.util.lookup.ServiceProvider;
68 /** Annotation processor to process an XHTML page and generate appropriate
71 * @author Jaroslav Tulach <jtulach@netbeans.org>
73 @ServiceProvider(service=Processor.class)
74 @SupportedAnnotationTypes({
75 "org.apidesign.bck2brwsr.htmlpage.api.Model",
76 "org.apidesign.bck2brwsr.htmlpage.api.Page",
77 "org.apidesign.bck2brwsr.htmlpage.api.OnFunction",
78 "org.apidesign.bck2brwsr.htmlpage.api.OnReceive",
79 "org.apidesign.bck2brwsr.htmlpage.api.On"
81 public final class PageProcessor extends AbstractProcessor {
82 private final Map<Element,String> models = new WeakHashMap<>();
84 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
86 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
87 if (!processModel(e)) {
91 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
92 if (!processPage(e)) {
96 if (roundEnv.processingOver()) {
102 private InputStream openStream(String pkg, String name) throws IOException {
104 FileObject fo = processingEnv.getFiler().getResource(
105 StandardLocation.SOURCE_PATH, pkg, name);
106 return fo.openInputStream();
107 } catch (IOException ex) {
108 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
112 private Messager err() {
113 return processingEnv.getMessager();
116 private boolean processModel(Element e) {
118 Model m = e.getAnnotation(Model.class);
122 String pkg = findPkgName(e);
124 String className = m.className();
125 models.put(e, className);
127 StringWriter body = new StringWriter();
128 List<String> propsGetSet = new ArrayList<>();
129 List<String> functions = new ArrayList<>();
130 Map<String, Collection<String>> propsDeps = new HashMap<>();
131 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
134 if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
137 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
140 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
141 w = new OutputStreamWriter(java.openOutputStream());
143 w.append("package " + pkg + ";\n");
144 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
145 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
146 w.append("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
147 w.append("final class ").append(className).append(" implements Cloneable {\n");
148 w.append(" private boolean locked;\n");
149 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
150 w.append(body.toString());
151 w.append(" private static Class<" + inPckName(e) + "> modelFor() { return null; }\n");
152 w.append(" public ").append(className).append("() {\n");
153 w.append(" intKnckt();\n");
155 w.append(" private void intKnckt() {\n");
156 w.append(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
157 writeStringArray(propsGetSet, w);
159 writeStringArray(functions, w);
162 w.append(" ").append(className).append("(Object json) {\n");
164 for (int i = 0; i < propsGetSet.size(); i += 4) {
165 Property p = findProperty(m.properties(), propsGetSet.get(i));
171 w.append(" Object[] ret = new Object[" + values + "];\n");
172 w.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n");
173 for (int i = 0; i < propsGetSet.size(); i += 4) {
174 Property p = findProperty(m.properties(), propsGetSet.get(i));
178 w.append(" \"").append(propsGetSet.get(i)).append("\",\n");
180 w.append(" }, ret);\n");
181 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) {
182 final String pn = propsGetSet.get(i);
183 Property p = findProperty(m.properties(), pn);
187 boolean[] isModel = { false };
188 boolean[] isEnum = { false };
189 String type = checkType(m.properties()[prop++], isModel, isEnum);
191 // w.append(type).append(".valueOf((String)");
193 w.append(" this.prop_").append(pn);
194 w.append(" = null;\n");
195 } else if (p.array()) {
196 w.append("if (ret[" + cnt + "] instanceof Object[]) {\n");
197 w.append(" for (Object e : ((Object[])ret[" + cnt + "])) {\n");
199 w.append(" this.prop_").append(pn).append(".add(new ");
200 w.append(type).append("(e));\n");
202 if (isPrimitive(type)) {
203 w.append(" this.prop_").append(pn).append(".add(((Number)e).");
204 w.append(type).append("Value());\n");
206 w.append(" this.prop_").append(pn).append(".add((");
207 w.append(type).append(")e);\n");
213 if (isPrimitive(type)) {
214 w.append(" this.prop_").append(pn);
215 w.append(" = ((Number)").append("ret[" + cnt + "]).");
216 w.append(type).append("Value();\n");
218 w.append(" this.prop_").append(pn);
219 w.append(" = (").append(type).append(')');
220 w.append("ret[" + cnt + "];\n");
225 w.append(" intKnckt();\n");
227 writeToString(m.properties(), w);
228 writeClone(className, m.properties(), w);
233 } catch (IOException ex) {
234 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
240 private boolean processPage(Element e) {
242 Page p = e.getAnnotation(Page.class);
246 String pkg = findPkgName(e);
249 try (InputStream is = openStream(pkg, p.xhtml())) {
250 pp = ProcessPage.readPage(is);
252 } catch (IOException iOException) {
253 err().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e);
258 String className = p.className();
259 if (className.isEmpty()) {
260 int indx = p.xhtml().indexOf('.');
261 className = p.xhtml().substring(0, indx);
264 StringWriter body = new StringWriter();
265 List<String> propsGetSet = new ArrayList<>();
266 List<String> functions = new ArrayList<>();
267 Map<String, Collection<String>> propsDeps = new HashMap<>();
268 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
271 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
274 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
277 if (!generateReceive(e, body, className, e.getEnclosedElements(), functions)) {
281 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
282 w = new OutputStreamWriter(java.openOutputStream());
284 w.append("package " + pkg + ";\n");
285 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
286 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
287 w.append("final class ").append(className).append(" {\n");
288 w.append(" private boolean locked;\n");
289 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
292 if (pp != null) for (String id : pp.ids()) {
293 String tag = pp.tagNameForId(id);
294 String type = type(tag);
295 w.append(" ").append("public final ").
296 append(type).append(' ').append(cnstnt(id)).append(" = new ").
297 append(type).append("(\"").append(id).append("\");\n");
300 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
301 w.append(body.toString());
302 if (!propsGetSet.isEmpty()) {
303 w.write("public " + className + " applyBindings() {\n");
304 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
305 w.write(className + ".class, this, ");
306 writeStringArray(propsGetSet, w);
308 writeStringArray(functions, w);
309 w.write(");\n return this;\n}\n");
311 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
312 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
319 } catch (IOException ex) {
320 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
326 private static String type(String tag) {
327 if (tag.equals("title")) {
330 if (tag.equals("button")) {
333 if (tag.equals("input")) {
336 if (tag.equals("canvas")) {
339 if (tag.equals("img")) {
345 private static String cnstnt(String id) {
346 return id.replace('.', '_').replace('-', '_');
349 private boolean initializeOnClick(
350 String className, TypeElement type, Writer w, ProcessPage pp
351 ) throws IOException {
353 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
354 { //for (Element clazz : pe.getEnclosedElements()) {
355 // if (clazz.getKind() != ElementKind.CLASS) {
358 w.append(" public ").append(className).append("() {\n");
359 StringBuilder dispatch = new StringBuilder();
361 for (Element method : type.getEnclosedElements()) {
362 On oc = method.getAnnotation(On.class);
364 for (String id : oc.id()) {
366 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
370 if (pp.tagNameForId(id) == null) {
371 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
375 ExecutableElement ee = (ExecutableElement)method;
376 CharSequence params = wrapParams(ee, id, className, "ev", null);
377 if (!ee.getModifiers().contains(Modifier.STATIC)) {
378 err().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
382 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
383 err().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
387 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
388 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
391 append(" case ").append(dispatchCnt).append(": ").
392 append(type.getSimpleName().toString()).
393 append('.').append(ee.getSimpleName()).append("(").
395 append("); break;\n");
402 if (dispatchCnt > 0) {
403 w.append("class OnDispatch implements OnHandler {\n");
404 w.append(" private final int dispatch;\n");
405 w.append(" OnDispatch(int d) { dispatch = d; }\n");
406 w.append(" public void onEvent(Object ev) {\n");
407 w.append(" switch (dispatch) {\n");
420 public Iterable<? extends Completion> getCompletions(
421 Element element, AnnotationMirror annotation,
422 ExecutableElement member, String userText
424 if (!userText.startsWith("\"")) {
425 return Collections.emptyList();
428 Element cls = findClass(element);
429 Page p = cls.getAnnotation(Page.class);
430 String pkg = findPkgName(cls);
433 InputStream is = openStream(pkg, p.xhtml());
434 pp = ProcessPage.readPage(is);
436 } catch (IOException iOException) {
437 return Collections.emptyList();
440 List<Completion> cc = new ArrayList<>();
441 userText = userText.substring(1);
442 for (String id : pp.ids()) {
443 if (id.startsWith(userText)) {
444 cc.add(Completions.of("\"" + id + "\"", id));
450 private static Element findClass(Element e) {
454 Page p = e.getAnnotation(Page.class);
458 return e.getEnclosingElement();
461 private boolean generateProperties(
463 Writer w, Property[] properties,
464 Collection<String> props, Map<String,Collection<String>> deps
465 ) throws IOException {
467 for (Property p : properties) {
469 tn = typeName(where, p);
470 String[] gs = toGetSet(p.name(), tn, p.array());
473 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
475 final Collection<String> dependants = deps.get(p.name());
476 if (dependants != null) {
477 for (String depProp : dependants) {
485 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
486 w.write(" if (locked) throw new IllegalStateException();\n");
487 w.write(" prop_" + p.name() + ".assign(ko);\n");
488 w.write(" return prop_" + p.name() + ";\n");
491 w.write("private " + tn + " prop_" + p.name() + ";\n");
492 w.write("public " + tn + " " + gs[0] + "() {\n");
493 w.write(" if (locked) throw new IllegalStateException();\n");
494 w.write(" return prop_" + p.name() + ";\n");
496 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
497 w.write(" if (locked) throw new IllegalStateException();\n");
498 w.write(" prop_" + p.name() + " = v;\n");
499 w.write(" if (ko != null) {\n");
500 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
501 final Collection<String> dependants = deps.get(p.name());
502 if (dependants != null) {
503 for (String depProp : dependants) {
504 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
519 private boolean generateComputedProperties(
520 Writer w, Property[] fixedProps,
521 Collection<? extends Element> arr, Collection<String> props,
522 Map<String,Collection<String>> deps
523 ) throws IOException {
525 for (Element e : arr) {
526 if (e.getKind() != ElementKind.METHOD) {
529 if (e.getAnnotation(ComputedProperty.class) == null) {
532 ExecutableElement ee = (ExecutableElement)e;
533 final TypeMirror rt = ee.getReturnType();
534 final Types tu = processingEnv.getTypeUtils();
535 TypeMirror ert = tu.erasure(rt);
536 String tn = fqn(ert, ee);
537 boolean array = false;
538 if (tn.equals("java.util.List")) {
542 final String sn = ee.getSimpleName().toString();
543 String[] gs = toGetSet(sn, tn, array);
545 w.write("public " + tn + " " + gs[0] + "() {\n");
546 w.write(" if (locked) throw new IllegalStateException();\n");
548 for (VariableElement pe : ee.getParameters()) {
549 final String dn = pe.getSimpleName().toString();
551 if (!verifyPropName(pe, dn, fixedProps)) {
555 final String dt = fqn(pe.asType(), ee);
556 String[] call = toGetSet(dn, dt, false);
557 w.write(" " + dt + " arg" + (++arg) + " = ");
558 w.write(call[0] + "();\n");
560 Collection<String> depends = deps.get(dn);
561 if (depends == null) {
562 depends = new LinkedHashSet<>();
563 deps.put(dn, depends);
568 w.write(" locked = true;\n");
569 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
571 for (int i = 1; i <= arg; i++) {
577 w.write(" } finally {\n");
578 w.write(" locked = false;\n");
582 props.add(e.getSimpleName().toString());
591 private static String[] toGetSet(String name, String type, boolean array) {
592 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
593 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
594 if ("int".equals(type)) {
597 if ("double".equals(type)) {
601 if ("boolean".equals(type)) {
605 final String nu = n.replace('.', '_');
607 return new String[] {
610 "get" + nu + "__Ljava_util_List_2",
617 pref + nu + "__" + bck2brwsrType,
618 "set" + nu + "__V" + bck2brwsrType
622 private String typeName(Element where, Property p) {
624 boolean[] isModel = { false };
625 boolean[] isEnum = { false };
626 ret = checkType(p, isModel, isEnum);
628 String bt = findBoxedType(ret);
633 if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) {
634 String bt = findBoxedType(ret);
637 Diagnostic.Kind.ERROR,
638 "Only primitive types supported in the mapping. Not " + ret,
646 private static String findBoxedType(String ret) {
647 if (ret.equals("boolean")) {
648 return Boolean.class.getName();
650 if (ret.equals("byte")) {
651 return Byte.class.getName();
653 if (ret.equals("short")) {
654 return Short.class.getName();
656 if (ret.equals("char")) {
657 return Character.class.getName();
659 if (ret.equals("int")) {
660 return Integer.class.getName();
662 if (ret.equals("long")) {
663 return Long.class.getName();
665 if (ret.equals("float")) {
666 return Float.class.getName();
668 if (ret.equals("double")) {
669 return Double.class.getName();
674 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
675 StringBuilder sb = new StringBuilder();
677 for (Property property : existingProps) {
678 if (property.name().equals(propName)) {
683 sb.append(property.name());
687 err().printMessage(Diagnostic.Kind.ERROR,
688 propName + " is not one of known properties: " + sb
694 private static String findPkgName(Element e) {
696 if (e.getKind() == ElementKind.PACKAGE) {
697 return ((PackageElement)e).getQualifiedName().toString();
699 e = e.getEnclosingElement();
703 private boolean generateFunctions(
704 Element clazz, StringWriter body, String className,
705 List<? extends Element> enclosedElements, List<String> functions
707 for (Element m : enclosedElements) {
708 if (m.getKind() != ElementKind.METHOD) {
711 ExecutableElement e = (ExecutableElement)m;
712 OnFunction onF = e.getAnnotation(OnFunction.class);
716 if (!e.getModifiers().contains(Modifier.STATIC)) {
718 Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
722 if (e.getModifiers().contains(Modifier.PRIVATE)) {
724 Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
728 if (e.getReturnType().getKind() != TypeKind.VOID) {
730 Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
734 String n = e.getSimpleName().toString();
735 body.append("private void ").append(n).append("(Object data, Object ev) {\n");
736 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
737 body.append(wrapParams(e, null, className, "ev", "data"));
742 functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
747 private boolean generateReceive(
748 Element clazz, StringWriter body, String className,
749 List<? extends Element> enclosedElements, List<String> functions
751 for (Element m : enclosedElements) {
752 if (m.getKind() != ElementKind.METHOD) {
755 ExecutableElement e = (ExecutableElement)m;
756 OnReceive onR = e.getAnnotation(OnReceive.class);
760 if (!e.getModifiers().contains(Modifier.STATIC)) {
762 Diagnostic.Kind.ERROR, "@OnReceive method needs to be static", e
766 if (e.getModifiers().contains(Modifier.PRIVATE)) {
768 Diagnostic.Kind.ERROR, "@OnReceive method cannot be private", e
772 if (e.getReturnType().getKind() != TypeKind.VOID) {
774 Diagnostic.Kind.ERROR, "@OnReceive method should return void", e
778 String modelClass = null;
779 boolean expectsList = false;
780 List<String> args = new ArrayList<>();
782 for (VariableElement ve : e.getParameters()) {
783 TypeMirror modelType = null;
784 if (ve.asType().toString().equals(className)) {
785 args.add(className + ".this");
786 } else if (isModel(ve.asType())) {
787 modelType = ve.asType();
788 } else if (ve.asType().getKind() == TypeKind.ARRAY) {
789 modelType = ((ArrayType)ve.asType()).getComponentType();
792 if (modelType != null) {
793 if (modelClass != null) {
794 err().printMessage(Diagnostic.Kind.ERROR, "There can be only one model class among arguments", e);
796 modelClass = modelType.toString();
806 if (modelClass == null) {
807 err().printMessage(Diagnostic.Kind.ERROR, "The method needs to have one @Model class as parameter", e);
809 String n = e.getSimpleName().toString();
810 body.append("public void ").append(n).append("(");
811 StringBuilder assembleURL = new StringBuilder();
814 for (String p : findParamNames(e, onR.url(), assembleURL)) {
816 body.append("String ").append(p);
820 body.append(") {\n");
821 body.append(" final Object[] result = { null };\n");
823 " class ProcessResult implements Runnable {\n" +
825 " public void run() {\n" +
826 " Object value = result[0];\n");
828 " " + modelClass + "[] arr;\n");
830 " if (value instanceof Object[]) {\n" +
831 " Object[] data = ((Object[])value);\n" +
832 " arr = new " + modelClass + "[data.length];\n" +
833 " for (int i = 0; i < data.length; i++) {\n" +
834 " arr[i] = new " + modelClass + "(data[i]);\n" +
837 " arr = new " + modelClass + "[1];\n" +
838 " arr[0] = new " + modelClass + "(value);\n" +
842 body.append(clazz.getSimpleName()).append(".").append(n).append("(");
844 for (String arg : args) {
855 body.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.loadJSON(\n ");
856 body.append(assembleURL);
857 body.append(", result, new ProcessResult()\n );\n");
858 // body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
859 // body.append(wrapParams(e, null, className, "ev", "data"));
860 // body.append(");\n");
866 private CharSequence wrapParams(
867 ExecutableElement ee, String id, String className, String evName, String dataName
869 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
870 StringBuilder params = new StringBuilder();
871 boolean first = true;
872 for (VariableElement ve : ee.getParameters()) {
877 String toCall = null;
878 if (ve.asType() == stringType) {
879 if (ve.getSimpleName().contentEquals("id")) {
880 params.append('"').append(id).append('"');
883 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
885 if (ve.asType().getKind() == TypeKind.DOUBLE) {
886 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
888 if (ve.asType().getKind() == TypeKind.INT) {
889 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
891 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
892 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
895 if (toCall != null) {
896 params.append(toCall);
897 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
898 params.append(dataName);
899 params.append(", null");
901 params.append(evName);
902 params.append(", \"");
903 params.append(ve.getSimpleName().toString());
909 String rn = fqn(ve.asType(), ee);
910 int last = rn.lastIndexOf('.');
912 rn = rn.substring(last + 1);
914 if (rn.equals(className)) {
915 params.append(className).append(".this");
918 err().printMessage(Diagnostic.Kind.ERROR,
919 "@On method can only accept String named 'id' or " + className + " arguments",
926 private boolean isModel(TypeMirror tm) {
927 final Element e = processingEnv.getTypeUtils().asElement(tm);
931 for (Element ch : e.getEnclosedElements()) {
932 if (ch.getKind() == ElementKind.METHOD) {
933 ExecutableElement ee = (ExecutableElement)ch;
934 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
939 return models.values().contains(e.getSimpleName().toString());
942 private void writeStringArray(List<String> strings, Writer w) throws IOException {
943 w.write("new String[] {\n");
945 for (String n : strings) {
950 w.write(" \"" + n + "\"");
957 private void writeToString(Property[] props, Writer w) throws IOException {
958 w.write(" public String toString() {\n");
959 w.write(" StringBuilder sb = new StringBuilder();\n");
960 w.write(" sb.append('{');\n");
962 for (Property p : props) {
964 w.append(" sb.append(\"" + p.name() + ": \");\n");
965 w.append(" sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
966 w.append(p.name()).append("));\n");
967 sep = " sb.append(',');\n";
969 w.write(" sb.append('}');\n");
970 w.write(" return sb.toString();\n");
973 private void writeClone(String className, Property[] props, Writer w) throws IOException {
974 w.write(" public " + className + " clone() {\n");
975 w.write(" " + className + " ret = new " + className + "();\n");
976 for (Property p : props) {
978 boolean isModel[] = { false };
979 boolean isEnum[] = { false };
980 checkType(p, isModel, isEnum);
982 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
986 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
989 w.write(" return ret;\n");
993 private String inPckName(Element e) {
994 StringBuilder sb = new StringBuilder();
995 while (e.getKind() != ElementKind.PACKAGE) {
996 if (sb.length() == 0) {
997 sb.append(e.getSimpleName());
1000 sb.insert(0, e.getSimpleName());
1002 e = e.getEnclosingElement();
1004 return sb.toString();
1007 private String fqn(TypeMirror pt, Element relative) {
1008 if (pt.getKind() == TypeKind.ERROR) {
1009 final Elements eu = processingEnv.getElementUtils();
1010 PackageElement pckg = eu.getPackageOf(relative);
1011 return pckg.getQualifiedName() + "." + pt.toString();
1013 return pt.toString();
1016 private String checkType(Property p, boolean[] isModel, boolean[] isEnum) {
1019 ret = p.type().getName();
1020 } catch (MirroredTypeException ex) {
1021 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
1022 final Element e = processingEnv.getTypeUtils().asElement(tm);
1023 final Model m = e == null ? null : e.getAnnotation(Model.class);
1025 ret = findPkgName(e) + '.' + m.className();
1027 models.put(e, m.className());
1029 ret = tm.toString();
1031 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1032 enm = processingEnv.getTypeUtils().erasure(enm);
1033 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1038 private Iterable<String> findParamNames(Element e, String url, StringBuilder assembleURL) {
1039 List<String> params = new ArrayList<>();
1041 for (int pos = 0; ;) {
1042 int next = url.indexOf('{', pos);
1044 assembleURL.append('"')
1045 .append(url.substring(pos))
1049 int close = url.indexOf('}', next);
1051 err().printMessage(Diagnostic.Kind.ERROR, "Unbalanced '{' and '}' in " + url, e);
1054 final String paramName = url.substring(next + 1, close);
1055 params.add(paramName);
1056 assembleURL.append('"')
1057 .append(url.substring(pos, next))
1058 .append("\" + ").append(paramName).append(" + ");
1063 private static Property findProperty(Property[] properties, String propName) {
1064 for (Property p : properties) {
1065 if (propName.equals(p.name())) {
1072 private boolean isPrimitive(String type) {
1074 "int".equals(type) ||
1075 "double".equals(type) ||
1076 "long".equals(type) ||
1077 "short".equals(type) ||
1078 "byte".equals(type) ||
1079 "float".equals(type);