Making list of activeTweeters really a list. It is easier to observe its changes.
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.HashSet;
30 import java.util.LinkedHashSet;
31 import java.util.List;
34 import java.util.WeakHashMap;
35 import javax.annotation.processing.AbstractProcessor;
36 import javax.annotation.processing.Completion;
37 import javax.annotation.processing.Completions;
38 import javax.annotation.processing.Messager;
39 import javax.annotation.processing.Processor;
40 import javax.annotation.processing.RoundEnvironment;
41 import javax.annotation.processing.SupportedAnnotationTypes;
42 import javax.lang.model.element.AnnotationMirror;
43 import javax.lang.model.element.Element;
44 import javax.lang.model.element.ElementKind;
45 import javax.lang.model.element.ExecutableElement;
46 import javax.lang.model.element.Modifier;
47 import javax.lang.model.element.PackageElement;
48 import javax.lang.model.element.TypeElement;
49 import javax.lang.model.element.VariableElement;
50 import javax.lang.model.type.ArrayType;
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.OnPropertyChange;
64 import org.apidesign.bck2brwsr.htmlpage.api.OnReceive;
65 import org.apidesign.bck2brwsr.htmlpage.api.Page;
66 import org.apidesign.bck2brwsr.htmlpage.api.Property;
67 import org.openide.util.lookup.ServiceProvider;
69 /** Annotation processor to process an XHTML page and generate appropriate
72 * @author Jaroslav Tulach <jtulach@netbeans.org>
74 @ServiceProvider(service=Processor.class)
75 @SupportedAnnotationTypes({
76 "org.apidesign.bck2brwsr.htmlpage.api.Model",
77 "org.apidesign.bck2brwsr.htmlpage.api.Page",
78 "org.apidesign.bck2brwsr.htmlpage.api.OnFunction",
79 "org.apidesign.bck2brwsr.htmlpage.api.OnReceive",
80 "org.apidesign.bck2brwsr.htmlpage.api.OnPropertyChange",
81 "org.apidesign.bck2brwsr.htmlpage.api.On"
83 public final class PageProcessor extends AbstractProcessor {
84 private final Map<Element,String> models = new WeakHashMap<>();
86 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
88 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
89 if (!processModel(e)) {
93 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
94 if (!processPage(e)) {
98 if (roundEnv.processingOver()) {
104 private InputStream openStream(String pkg, String name) throws IOException {
106 FileObject fo = processingEnv.getFiler().getResource(
107 StandardLocation.SOURCE_PATH, pkg, name);
108 return fo.openInputStream();
109 } catch (IOException ex) {
110 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
114 private Messager err() {
115 return processingEnv.getMessager();
118 private boolean processModel(Element e) {
120 Model m = e.getAnnotation(Model.class);
124 String pkg = findPkgName(e);
126 String className = m.className();
127 models.put(e, className);
129 StringWriter body = new StringWriter();
130 List<String> propsGetSet = new ArrayList<>();
131 List<String> functions = new ArrayList<>();
132 Map<String, Collection<String>> propsDeps = new HashMap<>();
133 Map<String, Collection<String>> functionDeps = new HashMap<>();
134 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
137 if (!generateOnChange(e, propsDeps, m.properties(), className, functionDeps)) {
140 if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps, functionDeps)) {
143 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
146 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
147 w = new OutputStreamWriter(java.openOutputStream());
149 w.append("package " + pkg + ";\n");
150 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
151 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
152 w.append("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
153 w.append("final class ").append(className).append(" implements Cloneable {\n");
154 w.append(" private boolean locked;\n");
155 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
156 w.append(body.toString());
157 w.append(" private static Class<" + inPckName(e) + "> modelFor() { return null; }\n");
158 w.append(" public ").append(className).append("() {\n");
159 w.append(" intKnckt();\n");
161 w.append(" private void intKnckt() {\n");
162 w.append(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
163 writeStringArray(propsGetSet, w);
165 writeStringArray(functions, w);
168 w.append(" ").append(className).append("(Object json) {\n");
170 for (int i = 0; i < propsGetSet.size(); i += 4) {
171 Property p = findProperty(m.properties(), propsGetSet.get(i));
177 w.append(" Object[] ret = new Object[" + values + "];\n");
178 w.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n");
179 for (int i = 0; i < propsGetSet.size(); i += 4) {
180 Property p = findProperty(m.properties(), propsGetSet.get(i));
184 w.append(" \"").append(propsGetSet.get(i)).append("\",\n");
186 w.append(" }, ret);\n");
187 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) {
188 final String pn = propsGetSet.get(i);
189 Property p = findProperty(m.properties(), pn);
193 boolean[] isModel = { false };
194 boolean[] isEnum = { false };
195 String type = checkType(m.properties()[prop++], isModel, isEnum);
197 // w.append(type).append(".valueOf((String)");
199 w.append(" this.prop_").append(pn);
200 w.append(" = null;\n");
201 } else if (p.array()) {
202 w.append("if (ret[" + cnt + "] instanceof Object[]) {\n");
203 w.append(" for (Object e : ((Object[])ret[" + cnt + "])) {\n");
205 w.append(" this.prop_").append(pn).append(".add(new ");
206 w.append(type).append("(e));\n");
208 if (isPrimitive(type)) {
209 w.append(" this.prop_").append(pn).append(".add(((Number)e).");
210 w.append(type).append("Value());\n");
212 w.append(" this.prop_").append(pn).append(".add((");
213 w.append(type).append(")e);\n");
219 if (isPrimitive(type)) {
220 w.append(" this.prop_").append(pn);
221 w.append(" = ((Number)").append("ret[" + cnt + "]).");
222 w.append(type).append("Value();\n");
224 w.append(" this.prop_").append(pn);
225 w.append(" = (").append(type).append(')');
226 w.append("ret[" + cnt + "];\n");
231 w.append(" intKnckt();\n");
233 writeToString(m.properties(), w);
234 writeClone(className, m.properties(), w);
239 } catch (IOException ex) {
240 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
246 private boolean processPage(Element e) {
248 Page p = e.getAnnotation(Page.class);
252 String pkg = findPkgName(e);
255 try (InputStream is = openStream(pkg, p.xhtml())) {
256 pp = ProcessPage.readPage(is);
258 } catch (IOException iOException) {
259 err().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e);
264 String className = p.className();
265 if (className.isEmpty()) {
266 int indx = p.xhtml().indexOf('.');
267 className = p.xhtml().substring(0, indx);
270 StringWriter body = new StringWriter();
271 List<String> propsGetSet = new ArrayList<>();
272 List<String> functions = new ArrayList<>();
273 Map<String, Collection<String>> propsDeps = new HashMap<>();
274 Map<String, Collection<String>> functionDeps = new HashMap<>();
275 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
278 if (!generateOnChange(e, propsDeps, p.properties(), className, functionDeps)) {
281 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps, functionDeps)) {
284 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
287 if (!generateReceive(e, body, className, e.getEnclosedElements(), functions)) {
291 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
292 w = new OutputStreamWriter(java.openOutputStream());
294 w.append("package " + pkg + ";\n");
295 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
296 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
297 w.append("final class ").append(className).append(" {\n");
298 w.append(" private boolean locked;\n");
299 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
302 if (pp != null) for (String id : pp.ids()) {
303 String tag = pp.tagNameForId(id);
304 String type = type(tag);
305 w.append(" ").append("public final ").
306 append(type).append(' ').append(cnstnt(id)).append(" = new ").
307 append(type).append("(\"").append(id).append("\");\n");
310 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
311 w.append(body.toString());
312 if (!propsGetSet.isEmpty()) {
313 w.write("public " + className + " applyBindings() {\n");
314 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
315 w.write(className + ".class, this, ");
316 writeStringArray(propsGetSet, w);
318 writeStringArray(functions, w);
319 w.write(");\n return this;\n}\n");
321 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
322 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
329 } catch (IOException ex) {
330 err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
336 private static String type(String tag) {
337 if (tag.equals("title")) {
340 if (tag.equals("button")) {
343 if (tag.equals("input")) {
346 if (tag.equals("canvas")) {
349 if (tag.equals("img")) {
355 private static String cnstnt(String id) {
356 return id.replace('.', '_').replace('-', '_');
359 private boolean initializeOnClick(
360 String className, TypeElement type, Writer w, ProcessPage pp
361 ) throws IOException {
363 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
364 { //for (Element clazz : pe.getEnclosedElements()) {
365 // if (clazz.getKind() != ElementKind.CLASS) {
368 w.append(" public ").append(className).append("() {\n");
369 StringBuilder dispatch = new StringBuilder();
371 for (Element method : type.getEnclosedElements()) {
372 On oc = method.getAnnotation(On.class);
374 for (String id : oc.id()) {
376 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
380 if (pp.tagNameForId(id) == null) {
381 err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
385 ExecutableElement ee = (ExecutableElement)method;
386 CharSequence params = wrapParams(ee, id, className, "ev", null);
387 if (!ee.getModifiers().contains(Modifier.STATIC)) {
388 err().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
392 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
393 err().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
397 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
398 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
401 append(" case ").append(dispatchCnt).append(": ").
402 append(type.getSimpleName().toString()).
403 append('.').append(ee.getSimpleName()).append("(").
405 append("); break;\n");
412 if (dispatchCnt > 0) {
413 w.append("class OnDispatch implements OnHandler {\n");
414 w.append(" private final int dispatch;\n");
415 w.append(" OnDispatch(int d) { dispatch = d; }\n");
416 w.append(" public void onEvent(Object ev) {\n");
417 w.append(" switch (dispatch) {\n");
430 public Iterable<? extends Completion> getCompletions(
431 Element element, AnnotationMirror annotation,
432 ExecutableElement member, String userText
434 if (!userText.startsWith("\"")) {
435 return Collections.emptyList();
438 Element cls = findClass(element);
439 Page p = cls.getAnnotation(Page.class);
440 String pkg = findPkgName(cls);
443 InputStream is = openStream(pkg, p.xhtml());
444 pp = ProcessPage.readPage(is);
446 } catch (IOException iOException) {
447 return Collections.emptyList();
450 List<Completion> cc = new ArrayList<>();
451 userText = userText.substring(1);
452 for (String id : pp.ids()) {
453 if (id.startsWith(userText)) {
454 cc.add(Completions.of("\"" + id + "\"", id));
460 private static Element findClass(Element e) {
464 Page p = e.getAnnotation(Page.class);
468 return e.getEnclosingElement();
471 private boolean generateProperties(
473 Writer w, Property[] properties,
474 Collection<String> props,
475 Map<String,Collection<String>> deps,
476 Map<String,Collection<String>> functionDeps
477 ) throws IOException {
479 for (Property p : properties) {
481 tn = typeName(where, p);
482 String[] gs = toGetSet(p.name(), tn, p.array());
485 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
487 Collection<String> dependants = deps.get(p.name());
488 if (dependants != null) {
489 for (String depProp : dependants) {
498 dependants = functionDeps.get(p.name());
499 if (dependants != null) {
500 w.write(".onChange(new Runnable() { public void run() {\n");
501 for (String call : dependants) {
508 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
509 w.write(" if (locked) throw new IllegalStateException();\n");
510 w.write(" prop_" + p.name() + ".assign(ko);\n");
511 w.write(" return prop_" + p.name() + ";\n");
514 w.write("private " + tn + " prop_" + p.name() + ";\n");
515 w.write("public " + tn + " " + gs[0] + "() {\n");
516 w.write(" if (locked) throw new IllegalStateException();\n");
517 w.write(" return prop_" + p.name() + ";\n");
519 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
520 w.write(" if (locked) throw new IllegalStateException();\n");
521 w.write(" prop_" + p.name() + " = v;\n");
522 w.write(" if (ko != null) {\n");
523 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
524 Collection<String> dependants = deps.get(p.name());
525 if (dependants != null) {
526 for (String depProp : dependants) {
527 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
531 dependants = functionDeps.get(p.name());
532 if (dependants != null) {
533 for (String call : dependants) {
548 private boolean generateComputedProperties(
549 Writer w, Property[] fixedProps,
550 Collection<? extends Element> arr, Collection<String> props,
551 Map<String,Collection<String>> deps
552 ) throws IOException {
554 for (Element e : arr) {
555 if (e.getKind() != ElementKind.METHOD) {
558 if (e.getAnnotation(ComputedProperty.class) == null) {
561 ExecutableElement ee = (ExecutableElement)e;
562 final TypeMirror rt = ee.getReturnType();
563 final Types tu = processingEnv.getTypeUtils();
564 TypeMirror ert = tu.erasure(rt);
565 String tn = fqn(ert, ee);
566 boolean array = false;
567 if (tn.equals("java.util.List")) {
571 final String sn = ee.getSimpleName().toString();
572 String[] gs = toGetSet(sn, tn, array);
574 w.write("public " + tn + " " + gs[0] + "() {\n");
575 w.write(" if (locked) throw new IllegalStateException();\n");
577 for (VariableElement pe : ee.getParameters()) {
578 final String dn = pe.getSimpleName().toString();
580 if (!verifyPropName(pe, dn, fixedProps)) {
584 final String dt = fqn(pe.asType(), ee);
585 String[] call = toGetSet(dn, dt, false);
586 w.write(" " + dt + " arg" + (++arg) + " = ");
587 w.write(call[0] + "();\n");
589 Collection<String> depends = deps.get(dn);
590 if (depends == null) {
591 depends = new LinkedHashSet<>();
592 deps.put(dn, depends);
597 w.write(" locked = true;\n");
598 w.write(" return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
600 for (int i = 1; i <= arg; i++) {
606 w.write(" } finally {\n");
607 w.write(" locked = false;\n");
611 props.add(e.getSimpleName().toString());
620 private static String[] toGetSet(String name, String type, boolean array) {
621 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
622 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
623 if ("int".equals(type)) {
626 if ("double".equals(type)) {
630 if ("boolean".equals(type)) {
634 final String nu = n.replace('.', '_');
636 return new String[] {
639 "get" + nu + "__Ljava_util_List_2",
646 pref + nu + "__" + bck2brwsrType,
647 "set" + nu + "__V" + bck2brwsrType
651 private String typeName(Element where, Property p) {
653 boolean[] isModel = { false };
654 boolean[] isEnum = { false };
655 ret = checkType(p, isModel, isEnum);
657 String bt = findBoxedType(ret);
662 if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) {
663 String bt = findBoxedType(ret);
666 Diagnostic.Kind.ERROR,
667 "Only primitive types supported in the mapping. Not " + ret,
675 private static String findBoxedType(String ret) {
676 if (ret.equals("boolean")) {
677 return Boolean.class.getName();
679 if (ret.equals("byte")) {
680 return Byte.class.getName();
682 if (ret.equals("short")) {
683 return Short.class.getName();
685 if (ret.equals("char")) {
686 return Character.class.getName();
688 if (ret.equals("int")) {
689 return Integer.class.getName();
691 if (ret.equals("long")) {
692 return Long.class.getName();
694 if (ret.equals("float")) {
695 return Float.class.getName();
697 if (ret.equals("double")) {
698 return Double.class.getName();
703 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
704 StringBuilder sb = new StringBuilder();
706 for (Property property : existingProps) {
707 if (property.name().equals(propName)) {
712 sb.append(property.name());
716 err().printMessage(Diagnostic.Kind.ERROR,
717 propName + " is not one of known properties: " + sb
723 private static String findPkgName(Element e) {
725 if (e.getKind() == ElementKind.PACKAGE) {
726 return ((PackageElement)e).getQualifiedName().toString();
728 e = e.getEnclosingElement();
732 private boolean generateFunctions(
733 Element clazz, StringWriter body, String className,
734 List<? extends Element> enclosedElements, List<String> functions
736 for (Element m : enclosedElements) {
737 if (m.getKind() != ElementKind.METHOD) {
740 ExecutableElement e = (ExecutableElement)m;
741 OnFunction onF = e.getAnnotation(OnFunction.class);
745 if (!e.getModifiers().contains(Modifier.STATIC)) {
747 Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
751 if (e.getModifiers().contains(Modifier.PRIVATE)) {
753 Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
757 if (e.getReturnType().getKind() != TypeKind.VOID) {
759 Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
763 String n = e.getSimpleName().toString();
764 body.append("private void ").append(n).append("(Object data, Object ev) {\n");
765 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
766 body.append(wrapParams(e, null, className, "ev", "data"));
771 functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
776 private boolean generateOnChange(Element clazz, Map<String,Collection<String>> propDeps,
777 Property[] properties, String className,
778 Map<String, Collection<String>> functionDeps
780 for (Element m : clazz.getEnclosedElements()) {
781 if (m.getKind() != ElementKind.METHOD) {
784 ExecutableElement e = (ExecutableElement) m;
785 OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
789 for (String pn : onPC.value()) {
790 if (findProperty(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
791 err().printMessage(Diagnostic.Kind.ERROR, "No property named '" + pn + "' in the model");
795 if (!e.getModifiers().contains(Modifier.STATIC)) {
797 Diagnostic.Kind.ERROR, "@OnPropertyChange method needs to be static", e);
800 if (e.getModifiers().contains(Modifier.PRIVATE)) {
802 Diagnostic.Kind.ERROR, "@OnPropertyChange method cannot be private", e);
805 if (e.getReturnType().getKind() != TypeKind.VOID) {
807 Diagnostic.Kind.ERROR, "@OnPropertyChange method should return void", e);
810 String n = e.getSimpleName().toString();
813 for (String pn : onPC.value()) {
814 StringBuilder call = new StringBuilder();
815 call.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
816 call.append(wrapPropName(e, className, "name", pn));
819 Collection<String> change = functionDeps.get(pn);
820 if (change == null) {
821 change = new ArrayList<>();
822 functionDeps.put(pn, change);
824 change.add(call.toString());
825 for (String dpn : findDerivedFrom(propDeps, pn)) {
826 change = functionDeps.get(dpn);
827 if (change == null) {
828 change = new ArrayList<>();
829 functionDeps.put(dpn, change);
831 change.add(call.toString());
838 private boolean generateReceive(
839 Element clazz, StringWriter body, String className,
840 List<? extends Element> enclosedElements, List<String> functions
842 for (Element m : enclosedElements) {
843 if (m.getKind() != ElementKind.METHOD) {
846 ExecutableElement e = (ExecutableElement)m;
847 OnReceive onR = e.getAnnotation(OnReceive.class);
851 if (!e.getModifiers().contains(Modifier.STATIC)) {
853 Diagnostic.Kind.ERROR, "@OnReceive method needs to be static", e
857 if (e.getModifiers().contains(Modifier.PRIVATE)) {
859 Diagnostic.Kind.ERROR, "@OnReceive method cannot be private", e
863 if (e.getReturnType().getKind() != TypeKind.VOID) {
865 Diagnostic.Kind.ERROR, "@OnReceive method should return void", e
869 String modelClass = null;
870 boolean expectsList = false;
871 List<String> args = new ArrayList<>();
873 for (VariableElement ve : e.getParameters()) {
874 TypeMirror modelType = null;
875 if (ve.asType().toString().equals(className)) {
876 args.add(className + ".this");
877 } else if (isModel(ve.asType())) {
878 modelType = ve.asType();
879 } else if (ve.asType().getKind() == TypeKind.ARRAY) {
880 modelType = ((ArrayType)ve.asType()).getComponentType();
883 if (modelType != null) {
884 if (modelClass != null) {
885 err().printMessage(Diagnostic.Kind.ERROR, "There can be only one model class among arguments", e);
887 modelClass = modelType.toString();
897 if (modelClass == null) {
898 err().printMessage(Diagnostic.Kind.ERROR, "The method needs to have one @Model class as parameter", e);
900 String n = e.getSimpleName().toString();
901 body.append("public void ").append(n).append("(");
902 StringBuilder assembleURL = new StringBuilder();
903 String jsonpVarName = null;
906 boolean skipJSONP = onR.jsonp().isEmpty();
907 for (String p : findParamNames(e, onR.url(), assembleURL)) {
908 if (!skipJSONP && p.equals(onR.jsonp())) {
914 body.append("String ").append(p);
918 err().printMessage(Diagnostic.Kind.ERROR,
919 "Name of jsonp attribute ('" + onR.jsonp() +
920 "') is not used in url attribute '" + onR.url() + "'"
924 body.append(") {\n");
925 body.append(" final Object[] result = { null };\n");
927 " class ProcessResult implements Runnable {\n" +
929 " public void run() {\n" +
930 " Object value = result[0];\n");
932 " " + modelClass + "[] arr;\n");
934 " if (value instanceof Object[]) {\n" +
935 " Object[] data = ((Object[])value);\n" +
936 " arr = new " + modelClass + "[data.length];\n" +
937 " for (int i = 0; i < data.length; i++) {\n" +
938 " arr[i] = new " + modelClass + "(data[i]);\n" +
941 " arr = new " + modelClass + "[1];\n" +
942 " arr[0] = new " + modelClass + "(value);\n" +
946 body.append(clazz.getSimpleName()).append(".").append(n).append("(");
948 for (String arg : args) {
959 body.append(" ProcessResult pr = new ProcessResult();\n");
960 if (jsonpVarName != null) {
961 body.append(" String ").append(jsonpVarName).
962 append(" = org.apidesign.bck2brwsr.htmlpage.ConvertTypes.createJSONP(result, pr);\n");
964 body.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.loadJSON(\n ");
965 body.append(assembleURL);
966 body.append(", result, pr, ").append(jsonpVarName).append("\n );\n");
967 // body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
968 // body.append(wrapParams(e, null, className, "ev", "data"));
969 // body.append(");\n");
975 private CharSequence wrapParams(
976 ExecutableElement ee, String id, String className, String evName, String dataName
978 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
979 StringBuilder params = new StringBuilder();
980 boolean first = true;
981 for (VariableElement ve : ee.getParameters()) {
986 String toCall = null;
987 if (ve.asType() == stringType) {
988 if (ve.getSimpleName().contentEquals("id")) {
989 params.append('"').append(id).append('"');
992 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
994 if (ve.asType().getKind() == TypeKind.DOUBLE) {
995 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
997 if (ve.asType().getKind() == TypeKind.INT) {
998 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
1000 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
1001 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
1004 if (toCall != null) {
1005 params.append(toCall);
1006 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
1007 params.append(dataName);
1008 params.append(", null");
1010 if (evName == null) {
1011 final StringBuilder sb = new StringBuilder();
1012 sb.append("Unexpected string parameter name.");
1013 if (dataName != null) {
1014 sb.append(" Try \"").append(dataName).append("\"");
1016 err().printMessage(Diagnostic.Kind.ERROR, sb.toString(), ee);
1018 params.append(evName);
1019 params.append(", \"");
1020 params.append(ve.getSimpleName().toString());
1021 params.append("\"");
1026 String rn = fqn(ve.asType(), ee);
1027 int last = rn.lastIndexOf('.');
1029 rn = rn.substring(last + 1);
1031 if (rn.equals(className)) {
1032 params.append(className).append(".this");
1035 err().printMessage(Diagnostic.Kind.ERROR,
1036 "@On method can only accept String named 'id' or " + className + " arguments",
1044 private CharSequence wrapPropName(
1045 ExecutableElement ee, String className, String propName, String propValue
1047 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1048 StringBuilder params = new StringBuilder();
1049 boolean first = true;
1050 for (VariableElement ve : ee.getParameters()) {
1052 params.append(", ");
1055 if (ve.asType() == stringType) {
1056 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
1057 params.append('"').append(propValue).append('"');
1059 err().printMessage(Diagnostic.Kind.ERROR, "Unexpected string parameter name. Try \"" + propName + "\".");
1063 String rn = fqn(ve.asType(), ee);
1064 int last = rn.lastIndexOf('.');
1066 rn = rn.substring(last + 1);
1068 if (rn.equals(className)) {
1069 params.append(className).append(".this");
1072 err().printMessage(Diagnostic.Kind.ERROR,
1073 "@OnPropertyChange method can only accept String or " + className + " arguments",
1079 private boolean isModel(TypeMirror tm) {
1080 final Element e = processingEnv.getTypeUtils().asElement(tm);
1084 for (Element ch : e.getEnclosedElements()) {
1085 if (ch.getKind() == ElementKind.METHOD) {
1086 ExecutableElement ee = (ExecutableElement)ch;
1087 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
1092 return models.values().contains(e.getSimpleName().toString());
1095 private void writeStringArray(List<String> strings, Writer w) throws IOException {
1096 w.write("new String[] {\n");
1098 for (String n : strings) {
1103 w.write(" \"" + n + "\"");
1110 private void writeToString(Property[] props, Writer w) throws IOException {
1111 w.write(" public String toString() {\n");
1112 w.write(" StringBuilder sb = new StringBuilder();\n");
1113 w.write(" sb.append('{');\n");
1115 for (Property p : props) {
1117 w.append(" sb.append(\"" + p.name() + ": \");\n");
1118 w.append(" sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
1119 w.append(p.name()).append("));\n");
1120 sep = " sb.append(',');\n";
1122 w.write(" sb.append('}');\n");
1123 w.write(" return sb.toString();\n");
1126 private void writeClone(String className, Property[] props, Writer w) throws IOException {
1127 w.write(" public " + className + " clone() {\n");
1128 w.write(" " + className + " ret = new " + className + "();\n");
1129 for (Property p : props) {
1131 boolean isModel[] = { false };
1132 boolean isEnum[] = { false };
1133 checkType(p, isModel, isEnum);
1135 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
1138 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
1140 w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
1144 w.write(" return ret;\n");
1148 private String inPckName(Element e) {
1149 StringBuilder sb = new StringBuilder();
1150 while (e.getKind() != ElementKind.PACKAGE) {
1151 if (sb.length() == 0) {
1152 sb.append(e.getSimpleName());
1155 sb.insert(0, e.getSimpleName());
1157 e = e.getEnclosingElement();
1159 return sb.toString();
1162 private String fqn(TypeMirror pt, Element relative) {
1163 if (pt.getKind() == TypeKind.ERROR) {
1164 final Elements eu = processingEnv.getElementUtils();
1165 PackageElement pckg = eu.getPackageOf(relative);
1166 return pckg.getQualifiedName() + "." + pt.toString();
1168 return pt.toString();
1171 private String checkType(Property p, boolean[] isModel, boolean[] isEnum) {
1174 ret = p.type().getName();
1175 } catch (MirroredTypeException ex) {
1176 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
1177 final Element e = processingEnv.getTypeUtils().asElement(tm);
1178 final Model m = e == null ? null : e.getAnnotation(Model.class);
1180 ret = findPkgName(e) + '.' + m.className();
1182 models.put(e, m.className());
1184 ret = tm.toString();
1186 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1187 enm = processingEnv.getTypeUtils().erasure(enm);
1188 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1193 private Iterable<String> findParamNames(Element e, String url, StringBuilder assembleURL) {
1194 List<String> params = new ArrayList<>();
1196 for (int pos = 0; ;) {
1197 int next = url.indexOf('{', pos);
1199 assembleURL.append('"')
1200 .append(url.substring(pos))
1204 int close = url.indexOf('}', next);
1206 err().printMessage(Diagnostic.Kind.ERROR, "Unbalanced '{' and '}' in " + url, e);
1209 final String paramName = url.substring(next + 1, close);
1210 params.add(paramName);
1211 assembleURL.append('"')
1212 .append(url.substring(pos, next))
1213 .append("\" + ").append(paramName).append(" + ");
1218 private static Property findProperty(Property[] properties, String propName) {
1219 for (Property p : properties) {
1220 if (propName.equals(p.name())) {
1227 private boolean isPrimitive(String type) {
1229 "int".equals(type) ||
1230 "double".equals(type) ||
1231 "long".equals(type) ||
1232 "short".equals(type) ||
1233 "byte".equals(type) ||
1234 "float".equals(type);
1237 private static Collection<String> findDerivedFrom(Map<String, Collection<String>> propsDeps, String derivedProp) {
1238 Set<String> names = new HashSet<>();
1239 for (Map.Entry<String, Collection<String>> e : propsDeps.entrySet()) {
1240 if (e.getValue().contains(derivedProp)) {
1241 names.add(e.getKey());