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();
126 StringWriter body = new StringWriter();
127 List<String> propsGetSet = new ArrayList<>();
128 List<String> functions = new ArrayList<>();
129 Map<String, Collection<String>> propsDeps = new HashMap<>();
130 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
133 if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
136 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
139 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
140 w = new OutputStreamWriter(java.openOutputStream());
142 w.append("package " + pkg + ";\n");
143 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
144 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
145 w.append("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
146 w.append("final class ").append(className).append(" implements Cloneable {\n");
147 w.append(" private boolean locked;\n");
148 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
149 w.append(body.toString());
150 w.append(" private static Class<" + inPckName(e) + "> modelFor() { return null; }\n");
151 w.append(" public ").append(className).append("() {\n");
152 w.append(" intKnckt();\n");
154 w.append(" private void intKnckt() {\n");
155 w.append(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
156 writeStringArray(propsGetSet, w);
158 writeStringArray(functions, w);
161 w.append(" ").append(className).append("(Object json) {\n");
163 for (int i = 0; i < propsGetSet.size(); i += 4) {
164 if (propsGetSet.get(i + 2) == null) {
169 w.append(" Object[] ret = new Object[" + values + "];\n");
170 w.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n");
171 for (int i = 0; i < propsGetSet.size(); i += 4) {
172 if (propsGetSet.get(i + 2) == null) {
175 w.append(" \"").append(propsGetSet.get(i)).append("\",\n");
177 w.append(" }, ret);\n");
178 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) {
179 if (propsGetSet.get(i + 2) == null) {
182 boolean[] isModel = { false };
183 boolean[] isEnum = { false };
184 String type = checkType(m.properties()[prop++], isModel, isEnum);
185 w.append(" this.prop_").append(propsGetSet.get(i)).append(" = ");
186 boolean close = false;
188 // w.append(type).append(".valueOf((String)");
193 w.append('(').append(type).append(')');
195 w.append("ret[" + cnt++ + "]");
203 w.append(" intKnckt();\n");
205 writeToString(m.properties(), w);
206 writeClone(className, m.properties(), w);
211 } catch (IOException ex) {
212 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
218 private boolean processPage(Element e) {
220 Page p = e.getAnnotation(Page.class);
224 String pkg = findPkgName(e);
227 try (InputStream is = openStream(pkg, p.xhtml())) {
228 pp = ProcessPage.readPage(is);
230 } catch (IOException iOException) {
231 err().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e);
236 String className = p.className();
237 if (className.isEmpty()) {
238 int indx = p.xhtml().indexOf('.');
239 className = p.xhtml().substring(0, indx);
242 StringWriter body = new StringWriter();
243 List<String> propsGetSet = new ArrayList<>();
244 List<String> functions = new ArrayList<>();
245 Map<String, Collection<String>> propsDeps = new HashMap<>();
246 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
249 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
252 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
255 if (!generateReceive(e, body, className, e.getEnclosedElements(), functions)) {
259 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
260 w = new OutputStreamWriter(java.openOutputStream());
262 w.append("package " + pkg + ";\n");
263 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
264 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
265 w.append("final class ").append(className).append(" {\n");
266 w.append(" private boolean locked;\n");
267 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
270 if (pp != null) for (String id : pp.ids()) {
271 String tag = pp.tagNameForId(id);
272 String type = type(tag);
273 w.append(" ").append("public final ").
274 append(type).append(' ').append(cnstnt(id)).append(" = new ").
275 append(type).append("(\"").append(id).append("\");\n");
278 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
279 w.append(body.toString());
280 if (!propsGetSet.isEmpty()) {
281 w.write("public " + className + " applyBindings() {\n");
282 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
283 w.write(className + ".class, this, ");
284 writeStringArray(propsGetSet, w);
286 writeStringArray(functions, w);
287 w.write(");\n return this;\n}\n");
289 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
290 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
297 } catch (IOException ex) {
298 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
304 private static String type(String tag) {
305 if (tag.equals("title")) {
308 if (tag.equals("button")) {
311 if (tag.equals("input")) {
314 if (tag.equals("canvas")) {
317 if (tag.equals("img")) {
323 private static String cnstnt(String id) {
324 return id.replace('.', '_').replace('-', '_');
327 private boolean initializeOnClick(
328 String className, TypeElement type, Writer w, ProcessPage pp
329 ) throws IOException {
331 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
332 { //for (Element clazz : pe.getEnclosedElements()) {
333 // if (clazz.getKind() != ElementKind.CLASS) {
336 w.append(" public ").append(className).append("() {\n");
337 StringBuilder dispatch = new StringBuilder();
339 for (Element method : type.getEnclosedElements()) {
340 On oc = method.getAnnotation(On.class);
342 for (String id : oc.id()) {
344 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
348 if (pp.tagNameForId(id) == null) {
349 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
353 ExecutableElement ee = (ExecutableElement)method;
354 CharSequence params = wrapParams(ee, id, className, "ev", null);
355 if (!ee.getModifiers().contains(Modifier.STATIC)) {
356 err().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
360 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
361 err().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
365 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
366 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
369 append(" case ").append(dispatchCnt).append(": ").
370 append(type.getSimpleName().toString()).
371 append('.').append(ee.getSimpleName()).append("(").
373 append("); break;\n");
380 if (dispatchCnt > 0) {
381 w.append("class OnDispatch implements OnHandler {\n");
382 w.append(" private final int dispatch;\n");
383 w.append(" OnDispatch(int d) { dispatch = d; }\n");
384 w.append(" public void onEvent(Object ev) {\n");
385 w.append(" switch (dispatch) {\n");
398 public Iterable<? extends Completion> getCompletions(
399 Element element, AnnotationMirror annotation,
400 ExecutableElement member, String userText
402 if (!userText.startsWith("\"")) {
403 return Collections.emptyList();
406 Element cls = findClass(element);
407 Page p = cls.getAnnotation(Page.class);
408 String pkg = findPkgName(cls);
411 InputStream is = openStream(pkg, p.xhtml());
412 pp = ProcessPage.readPage(is);
414 } catch (IOException iOException) {
415 return Collections.emptyList();
418 List<Completion> cc = new ArrayList<>();
419 userText = userText.substring(1);
420 for (String id : pp.ids()) {
421 if (id.startsWith(userText)) {
422 cc.add(Completions.of("\"" + id + "\"", id));
428 private static Element findClass(Element e) {
432 Page p = e.getAnnotation(Page.class);
436 return e.getEnclosingElement();
439 private boolean generateProperties(
441 Writer w, Property[] properties,
442 Collection<String> props, Map<String,Collection<String>> deps
443 ) throws IOException {
445 for (Property p : properties) {
447 tn = typeName(where, p);
448 String[] gs = toGetSet(p.name(), tn, p.array());
451 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
453 final Collection<String> dependants = deps.get(p.name());
454 if (dependants != null) {
455 for (String depProp : dependants) {
463 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
464 w.write(" if (locked) throw new IllegalStateException();\n");
465 w.write(" prop_" + p.name() + ".assign(ko);\n");
466 w.write(" return prop_" + p.name() + ";\n");
469 w.write("private " + tn + " prop_" + p.name() + ";\n");
470 w.write("public " + tn + " " + gs[0] + "() {\n");
471 w.write(" if (locked) throw new IllegalStateException();\n");
472 w.write(" return prop_" + p.name() + ";\n");
474 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
475 w.write(" if (locked) throw new IllegalStateException();\n");
476 w.write(" prop_" + p.name() + " = v;\n");
477 w.write(" if (ko != null) {\n");
478 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
479 final Collection<String> dependants = deps.get(p.name());
480 if (dependants != null) {
481 for (String depProp : dependants) {
482 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
497 private boolean generateComputedProperties(
498 Writer w, Property[] fixedProps,
499 Collection<? extends Element> arr, Collection<String> props,
500 Map<String,Collection<String>> deps
501 ) throws IOException {
503 for (Element e : arr) {
504 if (e.getKind() != ElementKind.METHOD) {
507 if (e.getAnnotation(ComputedProperty.class) == null) {
510 ExecutableElement ee = (ExecutableElement)e;
511 final TypeMirror rt = ee.getReturnType();
512 final Types tu = processingEnv.getTypeUtils();
513 TypeMirror ert = tu.erasure(rt);
514 String tn = fqn(ert, ee);
515 boolean array = false;
516 if (tn.equals("java.util.List")) {
520 final String sn = ee.getSimpleName().toString();
521 String[] gs = toGetSet(sn, tn, array);
523 w.write("public " + tn + " " + gs[0] + "() {\n");
524 w.write(" if (locked) throw new IllegalStateException();\n");
526 for (VariableElement pe : ee.getParameters()) {
527 final String dn = pe.getSimpleName().toString();
529 if (!verifyPropName(pe, dn, fixedProps)) {
533 final String dt = fqn(pe.asType(), ee);
534 String[] call = toGetSet(dn, dt, false);
535 w.write(" " + dt + " arg" + (++arg) + " = ");
536 w.write(call[0] + "();\n");
538 Collection<String> depends = deps.get(dn);
539 if (depends == null) {
540 depends = new LinkedHashSet<>();
541 deps.put(dn, depends);
546 w.write(" locked = true;\n");
547 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
549 for (int i = 1; i <= arg; i++) {
555 w.write(" } finally {\n");
556 w.write(" locked = false;\n");
560 props.add(e.getSimpleName().toString());
569 private static String[] toGetSet(String name, String type, boolean array) {
570 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
571 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
572 if ("int".equals(type)) {
575 if ("double".equals(type)) {
579 if ("boolean".equals(type)) {
583 final String nu = n.replace('.', '_');
585 return new String[] {
588 "get" + nu + "__Ljava_util_List_2",
595 pref + nu + "__" + bck2brwsrType,
596 "set" + nu + "__V" + bck2brwsrType
600 private String typeName(Element where, Property p) {
602 boolean[] isModel = { false };
603 boolean[] isEnum = { false };
604 ret = checkType(p, isModel, isEnum);
606 String bt = findBoxedType(ret);
611 if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) {
612 String bt = findBoxedType(ret);
615 Diagnostic.Kind.ERROR,
616 "Only primitive types supported in the mapping. Not " + ret,
624 private static String findBoxedType(String ret) {
625 if (ret.equals("boolean")) {
626 return Boolean.class.getName();
628 if (ret.equals("byte")) {
629 return Byte.class.getName();
631 if (ret.equals("short")) {
632 return Short.class.getName();
634 if (ret.equals("char")) {
635 return Character.class.getName();
637 if (ret.equals("int")) {
638 return Integer.class.getName();
640 if (ret.equals("long")) {
641 return Long.class.getName();
643 if (ret.equals("float")) {
644 return Float.class.getName();
646 if (ret.equals("double")) {
647 return Double.class.getName();
652 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
653 StringBuilder sb = new StringBuilder();
655 for (Property property : existingProps) {
656 if (property.name().equals(propName)) {
661 sb.append(property.name());
665 err().printMessage(Diagnostic.Kind.ERROR,
666 propName + " is not one of known properties: " + sb
672 private static String findPkgName(Element e) {
674 if (e.getKind() == ElementKind.PACKAGE) {
675 return ((PackageElement)e).getQualifiedName().toString();
677 e = e.getEnclosingElement();
681 private boolean generateFunctions(
682 Element clazz, StringWriter body, String className,
683 List<? extends Element> enclosedElements, List<String> functions
685 for (Element m : enclosedElements) {
686 if (m.getKind() != ElementKind.METHOD) {
689 ExecutableElement e = (ExecutableElement)m;
690 OnFunction onF = e.getAnnotation(OnFunction.class);
694 if (!e.getModifiers().contains(Modifier.STATIC)) {
696 Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
700 if (e.getModifiers().contains(Modifier.PRIVATE)) {
702 Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
706 if (e.getReturnType().getKind() != TypeKind.VOID) {
708 Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
712 String n = e.getSimpleName().toString();
713 body.append("private void ").append(n).append("(Object data, Object ev) {\n");
714 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
715 body.append(wrapParams(e, null, className, "ev", "data"));
720 functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
725 private boolean generateReceive(
726 Element clazz, StringWriter body, String className,
727 List<? extends Element> enclosedElements, List<String> functions
729 for (Element m : enclosedElements) {
730 if (m.getKind() != ElementKind.METHOD) {
733 ExecutableElement e = (ExecutableElement)m;
734 OnReceive onR = e.getAnnotation(OnReceive.class);
738 if (!e.getModifiers().contains(Modifier.STATIC)) {
740 Diagnostic.Kind.ERROR, "@OnReceive method needs to be static", e
744 if (e.getModifiers().contains(Modifier.PRIVATE)) {
746 Diagnostic.Kind.ERROR, "@OnReceive method cannot be private", e
750 if (e.getReturnType().getKind() != TypeKind.VOID) {
752 Diagnostic.Kind.ERROR, "@OnReceive method should return void", e
756 String modelClass = null;
757 boolean expectsList = false;
758 List<String> args = new ArrayList<>();
760 for (VariableElement ve : e.getParameters()) {
761 TypeMirror modelType = null;
762 if (ve.asType().toString().equals(className)) {
763 args.add(className + ".this");
764 } else if (isModel(ve.asType())) {
765 modelType = ve.asType();
766 } else if (ve.asType().getKind() == TypeKind.ARRAY) {
767 modelType = ((ArrayType)ve.asType()).getComponentType();
770 if (modelType != null) {
771 if (modelClass != null) {
772 err().printMessage(Diagnostic.Kind.ERROR, "There can be only one model class among arguments", e);
774 modelClass = modelType.toString();
784 if (modelClass == null) {
785 err().printMessage(Diagnostic.Kind.ERROR, "The method needs to have one @Model class as parameter", e);
787 String n = e.getSimpleName().toString();
788 body.append("public void ").append(n).append("(");
789 StringBuilder assembleURL = new StringBuilder();
792 for (String p : findParamNames(e, onR.url(), assembleURL)) {
794 body.append("String ").append(p);
798 body.append(") {\n");
799 body.append(" final Object[] result = { null };\n");
801 " class ProcessResult implements Runnable {\n" +
803 " public void run() {\n" +
804 " Object value = result[0];\n");
806 " " + modelClass + "[] arr;\n");
808 " if (value instanceof Object[]) {\n" +
809 " Object[] data = ((Object[])value);\n" +
810 " arr = new " + modelClass + "[data.length];\n" +
811 " for (int i = 0; i < data.length; i++) {\n" +
812 " arr[i] = new " + modelClass + "(value);\n" +
815 " arr = new " + modelClass + "[1];\n" +
816 " arr[0] = new " + modelClass + "(value);\n" +
820 body.append(clazz.getSimpleName()).append(".").append(n).append("(");
822 for (String arg : args) {
833 body.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.loadJSON(\n ");
834 body.append(assembleURL);
835 body.append(", result, new ProcessResult()\n );\n");
836 // body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
837 // body.append(wrapParams(e, null, className, "ev", "data"));
838 // body.append(");\n");
844 private CharSequence wrapParams(
845 ExecutableElement ee, String id, String className, String evName, String dataName
847 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
848 StringBuilder params = new StringBuilder();
849 boolean first = true;
850 for (VariableElement ve : ee.getParameters()) {
855 String toCall = null;
856 if (ve.asType() == stringType) {
857 if (ve.getSimpleName().contentEquals("id")) {
858 params.append('"').append(id).append('"');
861 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
863 if (ve.asType().getKind() == TypeKind.DOUBLE) {
864 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
866 if (ve.asType().getKind() == TypeKind.INT) {
867 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
869 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
870 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
873 if (toCall != null) {
874 params.append(toCall);
875 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
876 params.append(dataName);
877 params.append(", null");
879 params.append(evName);
880 params.append(", \"");
881 params.append(ve.getSimpleName().toString());
887 String rn = fqn(ve.asType(), ee);
888 int last = rn.lastIndexOf('.');
890 rn = rn.substring(last + 1);
892 if (rn.equals(className)) {
893 params.append(className).append(".this");
896 err().printMessage(Diagnostic.Kind.ERROR,
897 "@On method can only accept String named 'id' or " + className + " arguments",
904 private boolean isModel(TypeMirror tm) {
905 final Element e = processingEnv.getTypeUtils().asElement(tm);
909 for (Element ch : e.getEnclosedElements()) {
910 if (ch.getKind() == ElementKind.METHOD) {
911 ExecutableElement ee = (ExecutableElement)ch;
912 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
917 return models.values().contains(e.getSimpleName().toString());
920 private void writeStringArray(List<String> strings, Writer w) throws IOException {
921 w.write("new String[] {\n");
923 for (String n : strings) {
928 w.write(" \"" + n + "\"");
935 private void writeToString(Property[] props, Writer w) throws IOException {
936 w.write(" public String toString() {\n");
937 w.write(" StringBuilder sb = new StringBuilder();\n");
938 w.write(" sb.append('{');\n");
940 for (Property p : props) {
942 w.append(" sb.append(\"" + p.name() + ": \");\n");
943 w.append(" sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
944 w.append(p.name()).append("));\n");
945 sep = " sb.append(',');\n";
947 w.write(" sb.append('}');\n");
948 w.write(" return sb.toString();\n");
951 private void writeClone(String className, Property[] props, Writer w) throws IOException {
952 w.write(" public " + className + " clone() {\n");
953 w.write(" " + className + " ret = new " + className + "();\n");
954 for (Property p : props) {
956 boolean isModel[] = { false };
957 boolean isEnum[] = { false };
958 checkType(p, isModel, isEnum);
960 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
964 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
967 w.write(" return ret;\n");
971 private String inPckName(Element e) {
972 StringBuilder sb = new StringBuilder();
973 while (e.getKind() != ElementKind.PACKAGE) {
974 if (sb.length() == 0) {
975 sb.append(e.getSimpleName());
978 sb.insert(0, e.getSimpleName());
980 e = e.getEnclosingElement();
982 return sb.toString();
985 private String fqn(TypeMirror pt, Element relative) {
986 if (pt.getKind() == TypeKind.ERROR) {
987 final Elements eu = processingEnv.getElementUtils();
988 PackageElement pckg = eu.getPackageOf(relative);
989 return pckg.getQualifiedName() + "." + pt.toString();
991 return pt.toString();
994 private String checkType(Property p, boolean[] isModel, boolean[] isEnum) {
997 ret = p.type().getName();
998 } catch (MirroredTypeException ex) {
999 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
1000 final Element e = processingEnv.getTypeUtils().asElement(tm);
1001 final Model m = e == null ? null : e.getAnnotation(Model.class);
1003 ret = findPkgName(e) + '.' + m.className();
1005 models.put(e, m.className());
1007 ret = tm.toString();
1009 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1010 enm = processingEnv.getTypeUtils().erasure(enm);
1011 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1016 private Iterable<String> findParamNames(Element e, String url, StringBuilder assembleURL) {
1017 List<String> params = new ArrayList<>();
1019 for (int pos = 0; ;) {
1020 int next = url.indexOf('{', pos);
1022 assembleURL.append('"')
1023 .append(url.substring(pos))
1027 int close = url.indexOf('}', next);
1029 err().printMessage(Diagnostic.Kind.ERROR, "Unbalanced '{' and '}' in " + url, e);
1032 final String paramName = url.substring(next + 1, close);
1033 params.add(paramName);
1034 assembleURL.append('"')
1035 .append(url.substring(pos, next))
1036 .append("\" + ").append(paramName).append(" + ");