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 if (propsGetSet.get(i + 2) == null) {
170 w.append(" Object[] ret = new Object[" + values + "];\n");
171 w.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n");
172 for (int i = 0; i < propsGetSet.size(); i += 4) {
173 if (propsGetSet.get(i + 2) == null) {
176 w.append(" \"").append(propsGetSet.get(i)).append("\",\n");
178 w.append(" }, ret);\n");
179 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) {
180 if (propsGetSet.get(i + 2) == null) {
183 boolean[] isModel = { false };
184 boolean[] isEnum = { false };
185 String type = checkType(m.properties()[prop++], isModel, isEnum);
186 w.append(" this.prop_").append(propsGetSet.get(i)).append(" = ");
187 boolean close = false;
189 // w.append(type).append(".valueOf((String)");
194 w.append('(').append(type).append(')');
196 w.append("ret[" + cnt++ + "]");
204 w.append(" intKnckt();\n");
206 writeToString(m.properties(), w);
207 writeClone(className, m.properties(), w);
212 } catch (IOException ex) {
213 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
219 private boolean processPage(Element e) {
221 Page p = e.getAnnotation(Page.class);
225 String pkg = findPkgName(e);
228 try (InputStream is = openStream(pkg, p.xhtml())) {
229 pp = ProcessPage.readPage(is);
231 } catch (IOException iOException) {
232 err().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e);
237 String className = p.className();
238 if (className.isEmpty()) {
239 int indx = p.xhtml().indexOf('.');
240 className = p.xhtml().substring(0, indx);
243 StringWriter body = new StringWriter();
244 List<String> propsGetSet = new ArrayList<>();
245 List<String> functions = new ArrayList<>();
246 Map<String, Collection<String>> propsDeps = new HashMap<>();
247 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
250 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
253 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
256 if (!generateReceive(e, body, className, e.getEnclosedElements(), functions)) {
260 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
261 w = new OutputStreamWriter(java.openOutputStream());
263 w.append("package " + pkg + ";\n");
264 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
265 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
266 w.append("final class ").append(className).append(" {\n");
267 w.append(" private boolean locked;\n");
268 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
271 if (pp != null) for (String id : pp.ids()) {
272 String tag = pp.tagNameForId(id);
273 String type = type(tag);
274 w.append(" ").append("public final ").
275 append(type).append(' ').append(cnstnt(id)).append(" = new ").
276 append(type).append("(\"").append(id).append("\");\n");
279 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
280 w.append(body.toString());
281 if (!propsGetSet.isEmpty()) {
282 w.write("public " + className + " applyBindings() {\n");
283 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
284 w.write(className + ".class, this, ");
285 writeStringArray(propsGetSet, w);
287 writeStringArray(functions, w);
288 w.write(");\n return this;\n}\n");
290 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
291 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
298 } catch (IOException ex) {
299 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
305 private static String type(String tag) {
306 if (tag.equals("title")) {
309 if (tag.equals("button")) {
312 if (tag.equals("input")) {
315 if (tag.equals("canvas")) {
318 if (tag.equals("img")) {
324 private static String cnstnt(String id) {
325 return id.replace('.', '_').replace('-', '_');
328 private boolean initializeOnClick(
329 String className, TypeElement type, Writer w, ProcessPage pp
330 ) throws IOException {
332 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
333 { //for (Element clazz : pe.getEnclosedElements()) {
334 // if (clazz.getKind() != ElementKind.CLASS) {
337 w.append(" public ").append(className).append("() {\n");
338 StringBuilder dispatch = new StringBuilder();
340 for (Element method : type.getEnclosedElements()) {
341 On oc = method.getAnnotation(On.class);
343 for (String id : oc.id()) {
345 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
349 if (pp.tagNameForId(id) == null) {
350 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
354 ExecutableElement ee = (ExecutableElement)method;
355 CharSequence params = wrapParams(ee, id, className, "ev", null);
356 if (!ee.getModifiers().contains(Modifier.STATIC)) {
357 err().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
361 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
362 err().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
366 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
367 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
370 append(" case ").append(dispatchCnt).append(": ").
371 append(type.getSimpleName().toString()).
372 append('.').append(ee.getSimpleName()).append("(").
374 append("); break;\n");
381 if (dispatchCnt > 0) {
382 w.append("class OnDispatch implements OnHandler {\n");
383 w.append(" private final int dispatch;\n");
384 w.append(" OnDispatch(int d) { dispatch = d; }\n");
385 w.append(" public void onEvent(Object ev) {\n");
386 w.append(" switch (dispatch) {\n");
399 public Iterable<? extends Completion> getCompletions(
400 Element element, AnnotationMirror annotation,
401 ExecutableElement member, String userText
403 if (!userText.startsWith("\"")) {
404 return Collections.emptyList();
407 Element cls = findClass(element);
408 Page p = cls.getAnnotation(Page.class);
409 String pkg = findPkgName(cls);
412 InputStream is = openStream(pkg, p.xhtml());
413 pp = ProcessPage.readPage(is);
415 } catch (IOException iOException) {
416 return Collections.emptyList();
419 List<Completion> cc = new ArrayList<>();
420 userText = userText.substring(1);
421 for (String id : pp.ids()) {
422 if (id.startsWith(userText)) {
423 cc.add(Completions.of("\"" + id + "\"", id));
429 private static Element findClass(Element e) {
433 Page p = e.getAnnotation(Page.class);
437 return e.getEnclosingElement();
440 private boolean generateProperties(
442 Writer w, Property[] properties,
443 Collection<String> props, Map<String,Collection<String>> deps
444 ) throws IOException {
446 for (Property p : properties) {
448 tn = typeName(where, p);
449 String[] gs = toGetSet(p.name(), tn, p.array());
452 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
454 final Collection<String> dependants = deps.get(p.name());
455 if (dependants != null) {
456 for (String depProp : dependants) {
464 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
465 w.write(" if (locked) throw new IllegalStateException();\n");
466 w.write(" prop_" + p.name() + ".assign(ko);\n");
467 w.write(" return prop_" + p.name() + ";\n");
470 w.write("private " + tn + " prop_" + p.name() + ";\n");
471 w.write("public " + tn + " " + gs[0] + "() {\n");
472 w.write(" if (locked) throw new IllegalStateException();\n");
473 w.write(" return prop_" + p.name() + ";\n");
475 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
476 w.write(" if (locked) throw new IllegalStateException();\n");
477 w.write(" prop_" + p.name() + " = v;\n");
478 w.write(" if (ko != null) {\n");
479 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
480 final Collection<String> dependants = deps.get(p.name());
481 if (dependants != null) {
482 for (String depProp : dependants) {
483 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
498 private boolean generateComputedProperties(
499 Writer w, Property[] fixedProps,
500 Collection<? extends Element> arr, Collection<String> props,
501 Map<String,Collection<String>> deps
502 ) throws IOException {
504 for (Element e : arr) {
505 if (e.getKind() != ElementKind.METHOD) {
508 if (e.getAnnotation(ComputedProperty.class) == null) {
511 ExecutableElement ee = (ExecutableElement)e;
512 final TypeMirror rt = ee.getReturnType();
513 final Types tu = processingEnv.getTypeUtils();
514 TypeMirror ert = tu.erasure(rt);
515 String tn = fqn(ert, ee);
516 boolean array = false;
517 if (tn.equals("java.util.List")) {
521 final String sn = ee.getSimpleName().toString();
522 String[] gs = toGetSet(sn, tn, array);
524 w.write("public " + tn + " " + gs[0] + "() {\n");
525 w.write(" if (locked) throw new IllegalStateException();\n");
527 for (VariableElement pe : ee.getParameters()) {
528 final String dn = pe.getSimpleName().toString();
530 if (!verifyPropName(pe, dn, fixedProps)) {
534 final String dt = fqn(pe.asType(), ee);
535 String[] call = toGetSet(dn, dt, false);
536 w.write(" " + dt + " arg" + (++arg) + " = ");
537 w.write(call[0] + "();\n");
539 Collection<String> depends = deps.get(dn);
540 if (depends == null) {
541 depends = new LinkedHashSet<>();
542 deps.put(dn, depends);
547 w.write(" locked = true;\n");
548 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
550 for (int i = 1; i <= arg; i++) {
556 w.write(" } finally {\n");
557 w.write(" locked = false;\n");
561 props.add(e.getSimpleName().toString());
570 private static String[] toGetSet(String name, String type, boolean array) {
571 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
572 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
573 if ("int".equals(type)) {
576 if ("double".equals(type)) {
580 if ("boolean".equals(type)) {
584 final String nu = n.replace('.', '_');
586 return new String[] {
589 "get" + nu + "__Ljava_util_List_2",
596 pref + nu + "__" + bck2brwsrType,
597 "set" + nu + "__V" + bck2brwsrType
601 private String typeName(Element where, Property p) {
603 boolean[] isModel = { false };
604 boolean[] isEnum = { false };
605 ret = checkType(p, isModel, isEnum);
607 String bt = findBoxedType(ret);
612 if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) {
613 String bt = findBoxedType(ret);
616 Diagnostic.Kind.ERROR,
617 "Only primitive types supported in the mapping. Not " + ret,
625 private static String findBoxedType(String ret) {
626 if (ret.equals("boolean")) {
627 return Boolean.class.getName();
629 if (ret.equals("byte")) {
630 return Byte.class.getName();
632 if (ret.equals("short")) {
633 return Short.class.getName();
635 if (ret.equals("char")) {
636 return Character.class.getName();
638 if (ret.equals("int")) {
639 return Integer.class.getName();
641 if (ret.equals("long")) {
642 return Long.class.getName();
644 if (ret.equals("float")) {
645 return Float.class.getName();
647 if (ret.equals("double")) {
648 return Double.class.getName();
653 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
654 StringBuilder sb = new StringBuilder();
656 for (Property property : existingProps) {
657 if (property.name().equals(propName)) {
662 sb.append(property.name());
666 err().printMessage(Diagnostic.Kind.ERROR,
667 propName + " is not one of known properties: " + sb
673 private static String findPkgName(Element e) {
675 if (e.getKind() == ElementKind.PACKAGE) {
676 return ((PackageElement)e).getQualifiedName().toString();
678 e = e.getEnclosingElement();
682 private boolean generateFunctions(
683 Element clazz, StringWriter body, String className,
684 List<? extends Element> enclosedElements, List<String> functions
686 for (Element m : enclosedElements) {
687 if (m.getKind() != ElementKind.METHOD) {
690 ExecutableElement e = (ExecutableElement)m;
691 OnFunction onF = e.getAnnotation(OnFunction.class);
695 if (!e.getModifiers().contains(Modifier.STATIC)) {
697 Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
701 if (e.getModifiers().contains(Modifier.PRIVATE)) {
703 Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
707 if (e.getReturnType().getKind() != TypeKind.VOID) {
709 Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
713 String n = e.getSimpleName().toString();
714 body.append("private void ").append(n).append("(Object data, Object ev) {\n");
715 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
716 body.append(wrapParams(e, null, className, "ev", "data"));
721 functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
726 private boolean generateReceive(
727 Element clazz, StringWriter body, String className,
728 List<? extends Element> enclosedElements, List<String> functions
730 for (Element m : enclosedElements) {
731 if (m.getKind() != ElementKind.METHOD) {
734 ExecutableElement e = (ExecutableElement)m;
735 OnReceive onR = e.getAnnotation(OnReceive.class);
739 if (!e.getModifiers().contains(Modifier.STATIC)) {
741 Diagnostic.Kind.ERROR, "@OnReceive method needs to be static", e
745 if (e.getModifiers().contains(Modifier.PRIVATE)) {
747 Diagnostic.Kind.ERROR, "@OnReceive method cannot be private", e
751 if (e.getReturnType().getKind() != TypeKind.VOID) {
753 Diagnostic.Kind.ERROR, "@OnReceive method should return void", e
757 String modelClass = null;
758 boolean expectsList = false;
759 List<String> args = new ArrayList<>();
761 for (VariableElement ve : e.getParameters()) {
762 TypeMirror modelType = null;
763 if (ve.asType().toString().equals(className)) {
764 args.add(className + ".this");
765 } else if (isModel(ve.asType())) {
766 modelType = ve.asType();
767 } else if (ve.asType().getKind() == TypeKind.ARRAY) {
768 modelType = ((ArrayType)ve.asType()).getComponentType();
771 if (modelType != null) {
772 if (modelClass != null) {
773 err().printMessage(Diagnostic.Kind.ERROR, "There can be only one model class among arguments", e);
775 modelClass = modelType.toString();
785 if (modelClass == null) {
786 err().printMessage(Diagnostic.Kind.ERROR, "The method needs to have one @Model class as parameter", e);
788 String n = e.getSimpleName().toString();
789 body.append("public void ").append(n).append("(");
790 StringBuilder assembleURL = new StringBuilder();
793 for (String p : findParamNames(e, onR.url(), assembleURL)) {
795 body.append("String ").append(p);
799 body.append(") {\n");
800 body.append(" final Object[] result = { null };\n");
802 " class ProcessResult implements Runnable {\n" +
804 " public void run() {\n" +
805 " Object value = result[0];\n");
807 " " + modelClass + "[] arr;\n");
809 " if (value instanceof Object[]) {\n" +
810 " Object[] data = ((Object[])value);\n" +
811 " arr = new " + modelClass + "[data.length];\n" +
812 " for (int i = 0; i < data.length; i++) {\n" +
813 " arr[i] = new " + modelClass + "(data[i]);\n" +
816 " arr = new " + modelClass + "[1];\n" +
817 " arr[0] = new " + modelClass + "(value);\n" +
821 body.append(clazz.getSimpleName()).append(".").append(n).append("(");
823 for (String arg : args) {
834 body.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.loadJSON(\n ");
835 body.append(assembleURL);
836 body.append(", result, new ProcessResult()\n );\n");
837 // body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
838 // body.append(wrapParams(e, null, className, "ev", "data"));
839 // body.append(");\n");
845 private CharSequence wrapParams(
846 ExecutableElement ee, String id, String className, String evName, String dataName
848 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
849 StringBuilder params = new StringBuilder();
850 boolean first = true;
851 for (VariableElement ve : ee.getParameters()) {
856 String toCall = null;
857 if (ve.asType() == stringType) {
858 if (ve.getSimpleName().contentEquals("id")) {
859 params.append('"').append(id).append('"');
862 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
864 if (ve.asType().getKind() == TypeKind.DOUBLE) {
865 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
867 if (ve.asType().getKind() == TypeKind.INT) {
868 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
870 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
871 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
874 if (toCall != null) {
875 params.append(toCall);
876 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
877 params.append(dataName);
878 params.append(", null");
880 params.append(evName);
881 params.append(", \"");
882 params.append(ve.getSimpleName().toString());
888 String rn = fqn(ve.asType(), ee);
889 int last = rn.lastIndexOf('.');
891 rn = rn.substring(last + 1);
893 if (rn.equals(className)) {
894 params.append(className).append(".this");
897 err().printMessage(Diagnostic.Kind.ERROR,
898 "@On method can only accept String named 'id' or " + className + " arguments",
905 private boolean isModel(TypeMirror tm) {
906 final Element e = processingEnv.getTypeUtils().asElement(tm);
910 for (Element ch : e.getEnclosedElements()) {
911 if (ch.getKind() == ElementKind.METHOD) {
912 ExecutableElement ee = (ExecutableElement)ch;
913 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
918 return models.values().contains(e.getSimpleName().toString());
921 private void writeStringArray(List<String> strings, Writer w) throws IOException {
922 w.write("new String[] {\n");
924 for (String n : strings) {
929 w.write(" \"" + n + "\"");
936 private void writeToString(Property[] props, Writer w) throws IOException {
937 w.write(" public String toString() {\n");
938 w.write(" StringBuilder sb = new StringBuilder();\n");
939 w.write(" sb.append('{');\n");
941 for (Property p : props) {
943 w.append(" sb.append(\"" + p.name() + ": \");\n");
944 w.append(" sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
945 w.append(p.name()).append("));\n");
946 sep = " sb.append(',');\n";
948 w.write(" sb.append('}');\n");
949 w.write(" return sb.toString();\n");
952 private void writeClone(String className, Property[] props, Writer w) throws IOException {
953 w.write(" public " + className + " clone() {\n");
954 w.write(" " + className + " ret = new " + className + "();\n");
955 for (Property p : props) {
957 boolean isModel[] = { false };
958 boolean isEnum[] = { false };
959 checkType(p, isModel, isEnum);
961 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
965 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
968 w.write(" return ret;\n");
972 private String inPckName(Element e) {
973 StringBuilder sb = new StringBuilder();
974 while (e.getKind() != ElementKind.PACKAGE) {
975 if (sb.length() == 0) {
976 sb.append(e.getSimpleName());
979 sb.insert(0, e.getSimpleName());
981 e = e.getEnclosingElement();
983 return sb.toString();
986 private String fqn(TypeMirror pt, Element relative) {
987 if (pt.getKind() == TypeKind.ERROR) {
988 final Elements eu = processingEnv.getElementUtils();
989 PackageElement pckg = eu.getPackageOf(relative);
990 return pckg.getQualifiedName() + "." + pt.toString();
992 return pt.toString();
995 private String checkType(Property p, boolean[] isModel, boolean[] isEnum) {
998 ret = p.type().getName();
999 } catch (MirroredTypeException ex) {
1000 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
1001 final Element e = processingEnv.getTypeUtils().asElement(tm);
1002 final Model m = e == null ? null : e.getAnnotation(Model.class);
1004 ret = findPkgName(e) + '.' + m.className();
1006 models.put(e, m.className());
1008 ret = tm.toString();
1010 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1011 enm = processingEnv.getTypeUtils().erasure(enm);
1012 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1017 private Iterable<String> findParamNames(Element e, String url, StringBuilder assembleURL) {
1018 List<String> params = new ArrayList<>();
1020 for (int pos = 0; ;) {
1021 int next = url.indexOf('{', pos);
1023 assembleURL.append('"')
1024 .append(url.substring(pos))
1028 int close = url.indexOf('}', next);
1030 err().printMessage(Diagnostic.Kind.ERROR, "Unbalanced '{' and '}' in " + url, e);
1033 final String paramName = url.substring(next + 1, close);
1034 params.add(paramName);
1035 assembleURL.append('"')
1036 .append(url.substring(pos, next))
1037 .append("\" + ").append(paramName).append(" + ");