#258088: Introducing @Property(mutable=false) and making sure the generated Java code yields exceptions when such properties are modified after their use by the technology
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
6 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7 * Other names may be trademarks of their respective owners.
9 * The contents of this file are subject to the terms of either the GNU
10 * General Public License Version 2 only ("GPL") or the Common
11 * Development and Distribution License("CDDL") (collectively, the
12 * "License"). You may not use this file except in compliance with the
13 * License. You can obtain a copy of the License at
14 * http://www.netbeans.org/cddl-gplv2.html
15 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16 * specific language governing permissions and limitations under the
17 * License. When distributing the software, include this License Header
18 * Notice in each file and include the License file at
19 * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
20 * particular file as subject to the "Classpath" exception as provided
21 * by Oracle in the GPL Version 2 section of the License file that
22 * accompanied this code. If applicable, add the following below the
23 * License Header, with the fields enclosed by brackets [] replaced by
24 * your own identifying information:
25 * "Portions Copyrighted [year] [name of copyright owner]"
29 * The Original Software is NetBeans. The Initial Developer of the Original
30 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
32 * If you wish your version of this file to be governed by only the CDDL
33 * or only the GPL Version 2, indicate your decision by adding
34 * "[Contributor] elects to include this software in this distribution
35 * under the [CDDL or GPL Version 2] license." If you do not indicate a
36 * single choice of license, a recipient has the option to distribute
37 * your version of this file under either the CDDL, the GPL Version 2 or
38 * to extend the choice of license to its licensees as provided above.
39 * However, if you add GPL Version 2 code and therefore, elected the GPL
40 * Version 2 license, then the option applies only if the new code is
41 * made subject to such option by the copyright holder.
43 package org.netbeans.html.json.impl;
45 import java.io.IOException;
46 import java.io.OutputStreamWriter;
47 import java.io.StringWriter;
48 import java.io.Writer;
49 import java.lang.annotation.AnnotationTypeMismatchException;
50 import java.lang.annotation.IncompleteAnnotationException;
51 import java.lang.reflect.Method;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Collections;
56 import java.util.HashMap;
57 import java.util.HashSet;
58 import java.util.LinkedHashSet;
59 import java.util.List;
61 import java.util.ResourceBundle;
63 import java.util.WeakHashMap;
64 import java.util.logging.Level;
65 import java.util.logging.Logger;
66 import javax.annotation.processing.AbstractProcessor;
67 import javax.annotation.processing.Completion;
68 import javax.annotation.processing.Completions;
69 import javax.annotation.processing.ProcessingEnvironment;
70 import javax.annotation.processing.Processor;
71 import javax.annotation.processing.RoundEnvironment;
72 import javax.annotation.processing.SupportedAnnotationTypes;
73 import javax.annotation.processing.SupportedSourceVersion;
74 import javax.lang.model.SourceVersion;
75 import javax.lang.model.element.AnnotationMirror;
76 import javax.lang.model.element.AnnotationValue;
77 import javax.lang.model.element.Element;
78 import javax.lang.model.element.ElementKind;
79 import javax.lang.model.element.ExecutableElement;
80 import javax.lang.model.element.Modifier;
81 import javax.lang.model.element.PackageElement;
82 import javax.lang.model.element.TypeElement;
83 import javax.lang.model.element.VariableElement;
84 import javax.lang.model.type.ArrayType;
85 import javax.lang.model.type.DeclaredType;
86 import javax.lang.model.type.MirroredTypeException;
87 import javax.lang.model.type.TypeKind;
88 import javax.lang.model.type.TypeMirror;
89 import javax.lang.model.util.Elements;
90 import javax.lang.model.util.Types;
91 import javax.tools.Diagnostic;
92 import javax.tools.FileObject;
93 import net.java.html.json.ComputedProperty;
94 import net.java.html.json.Function;
95 import net.java.html.json.Model;
96 import net.java.html.json.ModelOperation;
97 import net.java.html.json.OnPropertyChange;
98 import net.java.html.json.OnReceive;
99 import net.java.html.json.Property;
100 import org.openide.util.lookup.ServiceProvider;
102 /** Annotation processor to process {@link Model @Model} annotations and
103 * generate appropriate model classes.
105 * @author Jaroslav Tulach
107 @ServiceProvider(service=Processor.class)
108 @SupportedSourceVersion(SourceVersion.RELEASE_6)
109 @SupportedAnnotationTypes({
110 "net.java.html.json.Model",
111 "net.java.html.json.ModelOperation",
112 "net.java.html.json.Function",
113 "net.java.html.json.OnReceive",
114 "net.java.html.json.OnPropertyChange",
115 "net.java.html.json.ComputedProperty",
116 "net.java.html.json.Property"
118 public final class ModelProcessor extends AbstractProcessor {
119 private static final Logger LOG = Logger.getLogger(ModelProcessor.class.getName());
120 private final Map<Element,String> models = new WeakHashMap<Element,String>();
121 private final Map<Element,Prprt[]> verify = new WeakHashMap<Element,Prprt[]>();
123 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
125 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
126 if (!processModel(e)) {
130 if (roundEnv.processingOver()) {
132 for (Map.Entry<Element, Prprt[]> entry : verify.entrySet()) {
133 TypeElement te = (TypeElement)entry.getKey();
134 String fqn = te.getQualifiedName().toString();
135 Element finalElem = processingEnv.getElementUtils().getTypeElement(fqn);
136 if (finalElem == null) {
140 Model m = finalElem.getAnnotation(Model.class);
144 props = Prprt.wrap(processingEnv, finalElem, m.properties());
145 for (Prprt p : props) {
146 boolean[] isModel = { false };
147 boolean[] isEnum = { false };
148 boolean[] isPrimitive = { false };
149 String t = checkType(p, isModel, isEnum, isPrimitive);
153 if (isPrimitive[0]) {
159 if ("java.lang.String".equals(t)) {
162 error("The type " + t + " should be defined by @Model annotation", entry.getKey());
170 private void error(String msg, Element e) {
171 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e);
174 private boolean processModel(Element e) {
176 Model m = e.getAnnotation(Model.class);
180 String pkg = findPkgName(e);
182 String className = m.className();
183 models.put(e, className);
185 StringWriter body = new StringWriter();
186 StringBuilder onReceiveType = new StringBuilder();
187 List<GetSet> propsGetSet = new ArrayList<GetSet>();
188 List<Object> functions = new ArrayList<Object>();
189 Map<String, Collection<String[]>> propsDeps = new HashMap<String, Collection<String[]>>();
190 Map<String, Collection<String>> functionDeps = new HashMap<String, Collection<String>>();
191 Prprt[] props = createProps(e, m.properties());
192 final String builderPrefix = findBuilderPrefix(e, m);
194 if (!generateComputedProperties(className, body, props, e.getEnclosedElements(), propsGetSet, propsDeps)) {
197 if (!generateOnChange(e, propsDeps, props, className, functionDeps)) {
200 if (!generateProperties(e, builderPrefix, body, className, props, propsGetSet, propsDeps, functionDeps)) {
203 if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
206 int functionsCount = functions.size() / 2;
207 for (int i = 0; i < functions.size(); i += 2) {
208 for (Prprt p : props) {
209 if (p.name().equals(functions.get(i))) {
210 error("Function cannot have the name of an existing property", e);
215 if (!generateReceive(e, body, className, e.getEnclosedElements(), onReceiveType)) {
218 if (!generateOperation(e, body, className, e.getEnclosedElements(), functions)) {
221 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
222 w = new OutputStreamWriter(java.openOutputStream());
224 w.append("package " + pkg + ";\n");
225 w.append("import net.java.html.json.*;\n");
226 final String inPckName = inPckName(e, false);
227 w.append("/** Generated for {@link ").append(inPckName).append("}*/\n");
228 w.append("public final class ").append(className).append(" implements Cloneable {\n");
229 w.append(" private static Class<").append(inPckName).append("> modelFor() { return ").append(inPckName).append(".class; }\n");
230 w.append(" private static final Html4JavaType TYPE = new Html4JavaType();\n");
233 for (Element c : e.getEnclosedElements()) {
234 if (c.getKind() != ElementKind.CONSTRUCTOR) {
238 ExecutableElement ec = (ExecutableElement) c;
239 if (ec.getParameters().size() > 0) {
242 if (ec.getModifiers().contains(Modifier.PRIVATE)) {
250 error("Needs non-private default constructor when instance=true", e);
251 w.append(" private final ").append(inPckName).append(" instance = null;\n");
253 w.append(" private final ").append(inPckName).append(" instance = new ").append(inPckName).append("();\n");
256 w.append(" private final org.netbeans.html.json.spi.Proto proto;\n");
257 w.append(body.toString());
258 w.append(" private ").append(className).append("(net.java.html.BrwsrCtx context) {\n");
259 w.append(" this.proto = TYPE.createProto(this, context);\n");
260 for (Prprt p : props) {
262 final String tn = typeName(p);
263 String[] gs = toGetSet(p.name(), tn, p.array());
264 w.write(" this.prop_" + p.name() + " = proto.createList(\""
267 if (functionDeps.containsKey(p.name())) {
268 int index = Arrays.asList(functionDeps.keySet().toArray()).indexOf(p.name());
269 w.write(", " + index);
274 w.write(", java.lang.Integer.MIN_VALUE");
276 Collection<String[]> dependants = propsDeps.get(p.name());
277 if (dependants != null) {
278 for (String[] depProp : dependants) {
290 w.append(" public ").append(className).append("() {\n");
291 w.append(" this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
292 for (Prprt p : props) {
294 boolean[] isModel = {false};
295 boolean[] isEnum = {false};
296 boolean isPrimitive[] = {false};
297 String tn = checkType(p, isModel, isEnum, isPrimitive);
299 w.write(" prop_" + p.name() + " = this;\n");
304 if (props.length > 0 && builderPrefix == null) {
305 StringBuilder constructorWithArguments = new StringBuilder();
306 constructorWithArguments.append(" public ").append(className).append("(");
307 Prprt firstArray = null;
309 int parameterCount = 0;
310 for (Prprt p : props) {
312 if (firstArray == null) {
317 String tn = typeName(p);
318 constructorWithArguments.append(sep);
319 constructorWithArguments.append(tn);
320 String[] third = toGetSet(p.name(), tn, false);
321 constructorWithArguments.append(" ").append(third[2]);
325 if (firstArray != null) {
327 boolean[] isModel = {false};
328 boolean[] isEnum = {false};
329 boolean isPrimitive[] = {false};
330 tn = checkType(firstArray, isModel, isEnum, isPrimitive);
331 constructorWithArguments.append(sep);
332 constructorWithArguments.append(tn);
333 String[] third = toGetSet(firstArray.name(), tn, true);
334 constructorWithArguments.append("... ").append(third[2]);
337 constructorWithArguments.append(") {\n");
338 constructorWithArguments.append(" this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
339 for (Prprt p : props) {
343 String[] third = toGetSet(p.name(), null, false);
344 constructorWithArguments.append(" this.prop_" + p.name() + " = " + third[2] + ";\n");
346 if (firstArray != null) {
347 String[] third = toGetSet(firstArray.name(), null, true);
348 constructorWithArguments.append(" proto.initTo(this.prop_" + firstArray.name() + ", " + third[2] + ");\n");
350 constructorWithArguments.append(" };\n");
351 if (parameterCount < 255) {
352 w.write(constructorWithArguments.toString());
355 w.append(" private static class Html4JavaType extends org.netbeans.html.json.spi.Proto.Type<").append(className).append("> {\n");
356 w.append(" private Html4JavaType() {\n super(").append(className).append(".class, ").
357 append(inPckName).append(".class, " + propsGetSet.size() + ", "
358 + functionsCount + ");\n");
360 for (int i = 0; i < propsGetSet.size(); i++) {
361 w.append(" registerProperty(\"").append(propsGetSet.get(i).name).append("\", ");
362 w.append((i) + ", " + propsGetSet.get(i).readOnly + ");\n");
366 for (int i = 0; i < functionsCount; i++) {
367 w.append(" registerFunction(\"").append((String)functions.get(i * 2)).append("\", ");
368 w.append(i + ");\n");
372 w.append(" @Override public void setValue(" + className + " data, int type, Object value) {\n");
373 w.append(" switch (type) {\n");
374 for (int i = 0; i < propsGetSet.size(); i++) {
375 final GetSet pgs = propsGetSet.get(i);
379 final String set = pgs.setter;
380 String tn = pgs.type;
381 String btn = findBoxedType(tn);
385 w.append(" case " + i + ": ");
386 if (pgs.setter != null) {
387 w.append("data.").append(strip(pgs.setter)).append("(TYPE.extractValue(" + tn + ".class, value)); return;\n");
389 w.append("TYPE.replaceValue(data.").append(strip(pgs.getter)).append("(), " + tn + ".class, value); return;\n");
393 w.append(" throw new UnsupportedOperationException();\n");
395 w.append(" @Override public Object getValue(" + className + " data, int type) {\n");
396 w.append(" switch (type) {\n");
397 for (int i = 0; i < propsGetSet.size(); i++) {
398 final String get = propsGetSet.get(i).getter;
400 w.append(" case " + i + ": return data." + strip(get) + "();\n");
404 w.append(" throw new UnsupportedOperationException();\n");
406 w.append(" @Override public void call(" + className + " model, int type, Object data, Object ev) throws Exception {\n");
407 w.append(" switch (type) {\n");
408 for (int i = 0; i < functions.size(); i += 2) {
409 final String name = (String)functions.get(i);
410 final Object param = functions.get(i + 1);
411 if (param instanceof ExecutableElement) {
412 ExecutableElement ee = (ExecutableElement)param;
413 w.append(" case " + (i / 2) + ":\n");
416 w.append("model.instance");
418 w.append(((TypeElement)e).getQualifiedName());
420 w.append(".").append(name).append("(");
421 w.append(wrapParams(ee, null, className, "model", "ev", "data"));
423 w.append(" return;\n");
425 String call = (String)param;
426 w.append(" case " + (i / 2) + ":\n"); // model." + name + "(data, ev); return;\n");
427 w.append(" ").append(call).append("\n");
428 w.append(" return;\n");
433 w.append(" throw new UnsupportedOperationException();\n");
435 w.append(" @Override public org.netbeans.html.json.spi.Proto protoFor(Object obj) {\n");
436 w.append(" return ((" + className + ")obj).proto;");
438 w.append(" @Override public void onChange(" + className + " model, int type) {\n");
439 w.append(" switch (type) {\n");
441 String[] arr = functionDeps.keySet().toArray(new String[0]);
442 for (int i = 0; i < arr.length; i++) {
443 Collection<String> onChange = functionDeps.get(arr[i]);
444 if (onChange != null) {
445 w.append(" case " + i + ":\n");
446 for (String call : onChange) {
447 w.append(" ").append(call).append("\n");
449 w.write(" return;\n");
454 w.append(" throw new UnsupportedOperationException();\n");
456 w.append(onReceiveType);
457 w.append(" @Override public " + className + " read(net.java.html.BrwsrCtx c, Object json) { return new " + className + "(c, json); }\n");
458 w.append(" @Override public " + className + " cloneTo(" + className + " o, net.java.html.BrwsrCtx c) { return o.clone(c); }\n");
460 w.append(" private ").append(className).append("(net.java.html.BrwsrCtx c, Object json) {\n");
461 w.append(" this(c);\n");
463 for (int i = 0; i < propsGetSet.size(); i++) {
464 Prprt p = findPrprt(props, propsGetSet.get(i).name);
470 w.append(" Object[] ret = new Object[" + values + "];\n");
471 w.append(" proto.extract(json, new String[] {\n");
472 for (int i = 0; i < propsGetSet.size(); i++) {
473 Prprt p = findPrprt(props, propsGetSet.get(i).name);
477 w.append(" \"").append(propsGetSet.get(i).name).append("\",\n");
479 w.append(" }, ret);\n");
480 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i++) {
481 final String pn = propsGetSet.get(i).name;
482 Prprt p = findPrprt(props, pn);
483 if (p == null || prop >= props.length) {
486 boolean[] isModel = { false };
487 boolean[] isEnum = { false };
488 boolean isPrimitive[] = { false };
489 String type = checkType(props[prop++], isModel, isEnum, isPrimitive);
491 w.append(" for (Object e : useAsArray(ret[" + cnt + "])) {\n");
493 w.append(" this.prop_").append(pn).append(".add(proto.read");
494 w.append("(" + type + ".class, e));\n");
495 } else if (isEnum[0]) {
496 w.append(" this.prop_").append(pn);
497 w.append(".add(e == null ? null : ");
498 w.append(type).append(".valueOf(TYPE.stringValue(e)));\n");
500 if (isPrimitive(type)) {
501 if (type.equals("char")) {
502 w.append(" this.prop_").append(pn).append(".add((char)TYPE.numberValue(e).");
503 w.append("intValue());\n");
505 w.append(" this.prop_").append(pn).append(".add(TYPE.numberValue(e).");
506 w.append(type).append("Value());\n");
509 w.append(" this.prop_").append(pn).append(".add((");
510 w.append(type).append(")e);\n");
516 w.append(" try {\n");
517 w.append(" this.prop_").append(pn);
518 w.append(" = ret[" + cnt + "] == null ? null : ");
519 w.append(type).append(".valueOf(TYPE.stringValue(ret[" + cnt + "]));\n");
520 w.append(" } catch (IllegalArgumentException ex) {\n");
521 w.append(" ex.printStackTrace();\n");
523 } else if (isPrimitive(type)) {
524 w.append(" this.prop_").append(pn);
525 w.append(" = ret[" + cnt + "] == null ? ");
526 if ("char".equals(type)) {
527 w.append("0 : (TYPE.charValue(");
528 } else if ("boolean".equals(type)) {
529 w.append("false : (TYPE.boolValue(");
531 w.append("0 : (TYPE.numberValue(");
533 w.append("ret[" + cnt + "])).");
534 w.append(type).append("Value();\n");
535 } else if (isModel[0]) {
536 w.append(" this.prop_").append(pn).append(" = proto.read");
537 w.append("(" + type + ".class, ");
538 w.append("ret[" + cnt + "]);\n");
540 w.append(" this.prop_").append(pn);
541 w.append(" = (").append(type).append(')');
542 w.append("ret[" + cnt + "];\n");
548 w.append(" private static Object[] useAsArray(Object o) {\n");
549 w.append(" return o instanceof Object[] ? ((Object[])o) : o == null ? new Object[0] : new Object[] { o };\n");
551 writeToString(props, w);
552 writeClone(className, props, w);
553 String targetId = findTargetId(e);
554 if (targetId != null) {
555 w.write(" /** Activates this model instance in the current {@link \n"
556 + "net.java.html.json.Models#bind(java.lang.Object, net.java.html.BrwsrCtx) browser context}. \n"
557 + "In case of using Knockout technology, this means to \n"
558 + "bind JSON like data in this model instance with Knockout tags in \n"
559 + "the surrounding HTML page.\n"
561 if (targetId != null) {
562 w.write("This method binds to element '" + targetId + "' on the page\n");
565 + "@return <code>this</code> object\n"
568 w.write(" public " + className + " applyBindings() {\n");
569 w.write(" proto.applyBindings();\n");
570 // w.write(" proto.applyBindings(id);\n");
571 w.write(" return this;\n");
574 w.write(" private " + className + " applyBindings() {\n");
575 w.write(" throw new IllegalStateException(\"Please specify targetId=\\\"\\\" in your @Model annotation\");\n");
578 w.write(" public boolean equals(Object o) {\n");
579 w.write(" if (o == this) return true;\n");
580 w.write(" if (!(o instanceof " + className + ")) return false;\n");
581 w.write(" " + className + " p = (" + className + ")o;\n");
582 for (Prprt p : props) {
583 w.write(" if (!TYPE.isSame(prop_" + p.name() + ", p.prop_" + p.name() + ")) return false;\n");
585 w.write(" return true;\n");
587 w.write(" public int hashCode() {\n");
588 w.write(" int h = " + className + ".class.getName().hashCode();\n");
589 for (Prprt p : props) {
590 w.write(" h = TYPE.hashPlus(prop_" + p.name() + ", h);\n");
592 w.write(" return h;\n");
598 } catch (IOException ex) {
599 error("Can't create " + className + ".java", e);
605 private static String findBuilderPrefix(Element e, Model m) {
606 if (!m.builder().isEmpty()) {
609 for (AnnotationMirror am : e.getAnnotationMirrors()) {
610 for (Map.Entry<? extends Object, ? extends Object> entry : am.getElementValues().entrySet()) {
611 if ("builder()".equals(entry.getKey().toString())) {
619 private static String builderMethod(String builderPrefix, Prprt p) {
620 if (builderPrefix.isEmpty()) {
623 return builderPrefix + Character.toUpperCase(p.name().charAt(0)) + p.name().substring(1);
626 private boolean generateProperties(
627 Element where, String builderPrefix,
628 Writer w, String className, Prprt[] properties,
630 Map<String,Collection<String[]>> deps,
631 Map<String,Collection<String>> functionDeps
632 ) throws IOException {
634 for (Prprt p : properties) {
637 String[] gs = toGetSet(p.name(), tn, p.array());
641 w.write(" private final java.util.List<" + tn + "> prop_" + p.name() + ";\n");
643 castTo = "java.util.List";
644 w.write(" public java.util.List<" + tn + "> " + gs[0] + "() {\n");
645 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
646 w.write(" return prop_" + p.name() + ";\n");
648 if (builderPrefix != null) {
649 boolean[] isModel = {false};
650 boolean[] isEnum = {false};
651 boolean isPrimitive[] = {false};
652 String ret = checkType(p, isModel, isEnum, isPrimitive);
653 w.write(" public " + className + " " + builderMethod(builderPrefix, p) + "(" + ret + "... v) {\n");
654 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
655 w.append(" TYPE.replaceValue(prop_").append(p.name()).append(", " + tn + ".class, v);\n");
656 w.write(" return this;\n");
661 boolean isModel[] = { false };
662 boolean isEnum[] = { false };
663 boolean isPrimitive[] = { false };
664 checkType(p, isModel, isEnum, isPrimitive);
666 w.write(" private /*" + tn + "*/Object prop_" + p.name() + ";\n");
669 w.write(" private " + tn + " prop_" + p.name() + ";\n");
671 w.write(" public " + tn + " " + gs[0] + "() {\n");
672 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
674 w.write(" if (prop_" + p.name() + " == this) prop_" + p.name() + " = new " + tn +"();\n");
676 w.write(" return (" + tn + ")prop_" + p.name() + ";\n");
678 w.write(" public void " + gs[1] + "(" + tn + " v) {\n");
680 w.write(" proto.initTo(null, null);\n");
682 w.write(" proto.verifyUnlocked();\n");
683 w.write(" Object o = prop_" + p.name() + ";\n");
685 w.write(" if (o == v) return;\n");
686 w.write(" prop_" + p.name() + " = v;\n");
688 w.write(" if (TYPE.isSame(o , v)) return;\n");
689 w.write(" prop_" + p.name() + " = v;\n");
691 w.write(" proto.valueHasMutated(\"" + p.name() + "\", o, v);\n");
693 Collection<String[]> dependants = deps.get(p.name());
694 if (dependants != null) {
695 for (String[] pair : dependants) {
696 w.write(" proto.valueHasMutated(\"" + pair[0] + "\", null, " + pair[1] + "());\n");
701 Collection<String> dependants = functionDeps.get(p.name());
702 if (dependants != null) {
704 w.append(className).append(" model = ").append(className).append(".this;\n");
705 for (String call : dependants) {
706 w.append(" ").append(call);
711 if (builderPrefix != null) {
712 w.write(" public " + className + " " + builderMethod(builderPrefix, p) + "(" + tn + " v) {\n");
713 w.write(" " + gs[1] + "(v);\n");
714 w.write(" return this;\n");
719 for (int i = 0; i < props.size(); i++) {
720 if (props.get(i).name.equals(p.name())) {
721 error("Cannot have the name " + p.name() + " defined twice", where);
726 props.add(new GetSet(
731 gs[3] == null && !p.array()
737 private boolean generateComputedProperties(
739 Writer w, Prprt[] fixedProps,
740 Collection<? extends Element> arr, Collection<GetSet> props,
741 Map<String,Collection<String[]>> deps
742 ) throws IOException {
744 for (Element e : arr) {
745 if (e.getKind() != ElementKind.METHOD) {
748 final ComputedProperty cp = e.getAnnotation(ComputedProperty.class);
749 final Transitive tp = e.getAnnotation(Transitive.class);
753 if (!e.getModifiers().contains(Modifier.STATIC)) {
754 error("Method " + e.getSimpleName() + " has to be static when annotated by @ComputedProperty", e);
758 ExecutableElement ee = (ExecutableElement)e;
759 ExecutableElement write = null;
760 if (!cp.write().isEmpty()) {
761 write = findWrite(ee, (TypeElement)e.getEnclosingElement(), cp.write(), className);
764 final TypeMirror rt = ee.getReturnType();
765 final Types tu = processingEnv.getTypeUtils();
766 TypeMirror ert = tu.erasure(rt);
767 String tn = fqn(ert, ee);
768 boolean array = false;
769 final TypeMirror toCheck;
770 if (tn.equals("java.util.List")) {
772 toCheck = ((DeclaredType)rt).getTypeArguments().get(0);
777 final String sn = ee.getSimpleName().toString();
779 if (toCheck.getKind().isPrimitive()) {
782 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
783 TypeMirror enumType = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
785 if (tu.isSubtype(toCheck, stringType)) {
787 } else if (tu.isSubtype(tu.erasure(toCheck), tu.erasure(enumType))) {
789 } else if (isModel(toCheck)) {
793 tu.unboxedType(toCheck);
794 // boxed types are OK
795 } catch (IllegalArgumentException ex) {
797 error(sn + " cannot return " + toCheck, e);
802 String[] gs = toGetSet(sn, tn, array);
804 w.write(" public " + tn);
806 w.write("<" + toCheck + ">");
808 w.write(" " + gs[0] + "() {\n");
810 boolean deep = false;
811 for (VariableElement pe : ee.getParameters()) {
812 final String dn = pe.getSimpleName().toString();
814 if (!verifyPropName(pe, dn, fixedProps)) {
817 final TypeMirror pt = pe.asType();
821 final String dt = fqn(pt, ee);
822 if (dt.startsWith("java.util.List") && pt instanceof DeclaredType) {
823 final List<? extends TypeMirror> ptArgs = ((DeclaredType)pt).getTypeArguments();
824 if (ptArgs.size() == 1 && isModel(ptArgs.get(0))) {
828 String[] call = toGetSet(dn, dt, false);
829 w.write(" " + dt + " arg" + (++arg) + " = ");
830 w.write(call[0] + "();\n");
832 Collection<String[]> depends = deps.get(dn);
833 if (depends == null) {
834 depends = new LinkedHashSet<String[]>();
835 deps.put(dn, depends);
837 depends.add(new String[] { sn, gs[0] });
844 w.write(" proto.acquireLock(\"" + sn + "\");\n");
846 w.write(" proto.acquireLock();\n");
848 w.write(" return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
850 for (int i = 1; i <= arg; i++) {
856 w.write(" } finally {\n");
857 w.write(" proto.releaseLock();\n");
862 props.add(new GetSet(
863 e.getSimpleName().toString(),
870 w.write(" public void " + gs[4] + "(" + write.getParameters().get(1).asType());
871 w.write(" value) {\n");
872 w.write(" " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + write.getSimpleName() + "(this, value);\n");
875 props.add(new GetSet(
876 e.getSimpleName().toString(),
888 private static String[] toGetSet(String name, String type, boolean array) {
889 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
890 boolean clazz = "class".equals(name);
891 String pref = clazz ? "access" : "get";
892 if ("boolean".equals(type) && !array) {
896 return new String[] {
913 private String typeName(Prprt p) {
915 boolean[] isModel = { false };
916 boolean[] isEnum = { false };
917 boolean isPrimitive[] = { false };
918 ret = checkType(p, isModel, isEnum, isPrimitive);
920 String bt = findBoxedType(ret);
928 private static String findBoxedType(String ret) {
929 if (ret.equals("boolean")) {
930 return Boolean.class.getName();
932 if (ret.equals("byte")) {
933 return Byte.class.getName();
935 if (ret.equals("short")) {
936 return Short.class.getName();
938 if (ret.equals("char")) {
939 return Character.class.getName();
941 if (ret.equals("int")) {
942 return Integer.class.getName();
944 if (ret.equals("long")) {
945 return Long.class.getName();
947 if (ret.equals("float")) {
948 return Float.class.getName();
950 if (ret.equals("double")) {
951 return Double.class.getName();
956 private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
957 StringBuilder sb = new StringBuilder();
959 for (Prprt Prprt : existingProps) {
960 if (Prprt.name().equals(propName)) {
965 sb.append(Prprt.name());
970 propName + " is not one of known properties: " + sb
976 private static String findPkgName(Element e) {
978 if (e.getKind() == ElementKind.PACKAGE) {
979 return ((PackageElement)e).getQualifiedName().toString();
981 e = e.getEnclosingElement();
985 private boolean generateFunctions(
986 Element clazz, StringWriter body, String className,
987 List<? extends Element> enclosedElements, List<Object> functions
989 boolean instance = clazz.getAnnotation(Model.class).instance();
990 for (Element m : enclosedElements) {
991 if (m.getKind() != ElementKind.METHOD) {
994 ExecutableElement e = (ExecutableElement)m;
995 Function onF = e.getAnnotation(Function.class);
999 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1000 error("@OnFunction method needs to be static", e);
1003 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1004 error("@OnFunction method cannot be private", e);
1007 if (e.getReturnType().getKind() != TypeKind.VOID) {
1008 error("@OnFunction method should return void", e);
1011 String n = e.getSimpleName().toString();
1018 private boolean generateOnChange(Element clazz, Map<String,Collection<String[]>> propDeps,
1019 Prprt[] properties, String className,
1020 Map<String, Collection<String>> functionDeps
1022 boolean instance = clazz.getAnnotation(Model.class).instance();
1023 for (Element m : clazz.getEnclosedElements()) {
1024 if (m.getKind() != ElementKind.METHOD) {
1027 ExecutableElement e = (ExecutableElement) m;
1028 OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
1032 for (String pn : onPC.value()) {
1033 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
1034 error("No Prprt named '" + pn + "' in the model", clazz);
1038 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1039 error("@OnPrprtChange method needs to be static", e);
1042 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1043 error("@OnPrprtChange method cannot be private", e);
1046 if (e.getReturnType().getKind() != TypeKind.VOID) {
1047 error("@OnPrprtChange method should return void", e);
1050 String n = e.getSimpleName().toString();
1053 for (String pn : onPC.value()) {
1054 StringBuilder call = new StringBuilder();
1055 call.append(" ").append(inPckName(clazz, instance)).append(".").append(n).append("(");
1056 call.append(wrapPropName(e, className, "name", pn));
1057 call.append(");\n");
1059 Collection<String> change = functionDeps.get(pn);
1060 if (change == null) {
1061 change = new ArrayList<String>();
1062 functionDeps.put(pn, change);
1064 change.add(call.toString());
1065 for (String dpn : findDerivedFrom(propDeps, pn)) {
1066 change = functionDeps.get(dpn);
1067 if (change == null) {
1068 change = new ArrayList<String>();
1069 functionDeps.put(dpn, change);
1071 change.add(call.toString());
1078 private boolean generateOperation(Element clazz,
1079 StringWriter body, String className,
1080 List<? extends Element> enclosedElements,
1081 List<Object> functions
1083 boolean instance = clazz.getAnnotation(Model.class).instance();
1084 for (Element m : enclosedElements) {
1085 if (m.getKind() != ElementKind.METHOD) {
1088 ExecutableElement e = (ExecutableElement)m;
1089 ModelOperation mO = e.getAnnotation(ModelOperation.class);
1093 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1094 error("@ModelOperation method needs to be static", e);
1097 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1098 error("@ModelOperation method cannot be private", e);
1101 if (e.getReturnType().getKind() != TypeKind.VOID) {
1102 error("@ModelOperation method should return void", e);
1105 List<String> args = new ArrayList<String>();
1107 body.append(" /** @see " + clazz.getSimpleName() + "#" + m.getSimpleName() + " */\n");
1108 body.append(" public void ").append(m.getSimpleName()).append("(");
1110 boolean checkFirst = true;
1111 for (VariableElement ve : e.getParameters()) {
1112 final TypeMirror type = ve.asType();
1113 CharSequence simpleName;
1114 if (type.getKind() == TypeKind.DECLARED) {
1115 simpleName = ((DeclaredType)type).asElement().getSimpleName();
1117 simpleName = type.toString();
1119 if (checkFirst && simpleName.toString().equals(className)) {
1123 error("First parameter of @ModelOperation method must be " + className, m);
1126 args.add(ve.getSimpleName().toString());
1127 body.append(sep).append("final ");
1128 body.append(ve.asType().toString()).append(" ");
1129 body.append(ve.toString());
1133 body.append(") {\n");
1134 int idx = functions.size() / 2;
1135 functions.add(m.getSimpleName().toString());
1136 body.append(" proto.runInBrowser(" + idx);
1137 for (String s : args) {
1138 body.append(", ").append(s);
1140 body.append(");\n");
1141 body.append(" }\n");
1143 StringBuilder call = new StringBuilder();
1144 call.append("{ Object[] arr = (Object[])data; ");
1145 call.append(inPckName(clazz, true)).append(".").append(m.getSimpleName()).append("(");
1147 for (VariableElement ve : e.getParameters()) {
1149 call.append("model");
1152 String type = ve.asType().toString();
1153 String boxedType = findBoxedType(type);
1154 if (boxedType != null) {
1157 call.append(", ").append("(").append(type).append(")arr[").append(i - 2).append("]");
1159 call.append("); }");
1160 functions.add(call.toString());
1168 private boolean generateReceive(
1169 Element clazz, StringWriter body, String className,
1170 List<? extends Element> enclosedElements, StringBuilder inType
1172 boolean ret = generateReceiveImpl(clazz, body, className, enclosedElements, inType);
1174 inType.setLength(0);
1178 private boolean generateReceiveImpl(
1179 Element clazz, StringWriter body, String className,
1180 List<? extends Element> enclosedElements, StringBuilder inType
1182 inType.append(" @Override public void onMessage(").append(className).append(" model, int index, int type, Object data, Object[] params) {\n");
1183 inType.append(" switch (index) {\n");
1186 boolean instance = clazz.getAnnotation(Model.class).instance();
1187 for (Element m : enclosedElements) {
1188 if (m.getKind() != ElementKind.METHOD) {
1191 ExecutableElement e = (ExecutableElement)m;
1192 OnReceive onR = e.getAnnotation(OnReceive.class);
1196 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1197 error("@OnReceive method needs to be static", e);
1200 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1201 error("@OnReceive method cannot be private", e);
1204 if (e.getReturnType().getKind() != TypeKind.VOID) {
1205 error("@OnReceive method should return void", e);
1208 if (!onR.jsonp().isEmpty() && !"GET".equals(onR.method())) {
1209 error("JSONP works only with GET transport method", e);
1211 String dataMirror = findDataSpecified(e, onR);
1212 if ("PUT".equals(onR.method()) && dataMirror == null) {
1213 error("PUT method needs to specify a data() class", e);
1216 if ("POST".equals(onR.method()) && dataMirror == null) {
1217 error("POST method needs to specify a data() class", e);
1220 if (e.getParameters().size() < 2) {
1221 error("@OnReceive method needs at least two parameters", e);
1223 final boolean isWebSocket = "WebSocket".equals(onR.method());
1224 if (isWebSocket && dataMirror == null) {
1225 error("WebSocket method needs to specify a data() class", e);
1227 int expectsList = 0;
1228 List<String> args = new ArrayList<String>();
1229 List<String> params = new ArrayList<String>();
1230 // first argument is model class
1232 TypeMirror type = e.getParameters().get(0).asType();
1233 CharSequence simpleName;
1234 if (type.getKind() == TypeKind.DECLARED) {
1235 simpleName = ((DeclaredType) type).asElement().getSimpleName();
1237 simpleName = type.toString();
1239 if (simpleName.toString().equals(className)) {
1242 error("First parameter needs to be " + className, e);
1249 final Types tu = processingEnv.getTypeUtils();
1250 TypeMirror type = e.getParameters().get(1).asType();
1251 TypeMirror modelType = null;
1252 TypeMirror ert = tu.erasure(type);
1254 if (isModel(type)) {
1256 } else if (type.getKind() == TypeKind.ARRAY) {
1257 modelType = ((ArrayType)type).getComponentType();
1259 } else if ("java.util.List".equals(fqn(ert, e))) {
1260 List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments();
1261 if (typeArgs.size() == 1) {
1262 modelType = typeArgs.get(0);
1265 } else if (type.toString().equals("java.lang.String")) {
1268 if (modelType == null) {
1269 error("Second arguments needs to be a model, String or array or List of models", e);
1272 modelClass = modelType.toString();
1273 if (expectsList == 1) {
1275 } else if (expectsList == 2) {
1276 args.add("java.util.Arrays.asList(arr)");
1281 String n = e.getSimpleName().toString();
1283 body.append(" /** Performs WebSocket communication. Call with <code>null</code> data parameter\n");
1284 body.append(" * to open the connection (even if not required). Call with non-null data to\n");
1285 body.append(" * send messages to server. Call again with <code>null</code> data to close the socket.\n");
1286 body.append(" */\n");
1287 if (onR.headers().length > 0) {
1288 error("WebSocket spec does not support headers", e);
1291 body.append(" public void ").append(n).append("(");
1292 StringBuilder urlBefore = new StringBuilder();
1293 StringBuilder urlAfter = new StringBuilder();
1294 StringBuilder headers = new StringBuilder();
1295 String jsonpVarName = null;
1298 boolean skipJSONP = onR.jsonp().isEmpty();
1299 Set<String> receiveParams = new LinkedHashSet<String>();
1300 findParamNames(receiveParams, e, onR.url(), onR.jsonp(), urlBefore, urlAfter);
1301 for (String headerLine : onR.headers()) {
1302 if (headerLine.contains("\r") || headerLine.contains("\n")) {
1303 error("Header line cannot contain line separator", e);
1305 findParamNames(receiveParams, e, headerLine, null, headers);
1306 headers.append("+ \"\\r\\n\" +\n");
1308 if (headers.length() > 0) {
1309 headers.append("\"\"");
1311 for (String p : receiveParams) {
1312 if (!skipJSONP && p.equals(onR.jsonp())) {
1318 body.append("String ").append(p);
1323 "Name of jsonp attribute ('" + onR.jsonp() +
1324 "') is not used in url attribute '" + onR.url() + "'", e
1327 if (dataMirror != null) {
1328 body.append(sep).append(dataMirror.toString()).append(" data");
1330 for (int i = 2; i < e.getParameters().size(); i++) {
1332 error("@OnReceive(method=\"WebSocket\") can only have two arguments", e);
1336 VariableElement ve = e.getParameters().get(i);
1337 body.append(sep).append(ve.asType().toString()).append(" ").append(ve.getSimpleName());
1338 final String tp = ve.asType().toString();
1339 String btn = findBoxedType(tp);
1343 args.add("(" + btn + ")params[" + (i - 2) + "]");
1344 params.add(ve.getSimpleName().toString());
1348 body.append(") {\n");
1349 boolean webSocket = onR.method().equals("WebSocket");
1351 if (generateWSReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1354 body.append(" }\n");
1355 body.append(" private Object ws_" + e.getSimpleName() + ";\n");
1357 if (generateJSONReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1360 body.append(" }\n");
1363 inType.append(" }\n");
1364 inType.append(" throw new UnsupportedOperationException(\"index: \" + index + \" type: \" + type);\n");
1365 inType.append(" }\n");
1369 private boolean generateJSONReceiveBody(int index, StringWriter method, StringBuilder body, OnReceive onR, ExecutableElement e, Element clazz, String className, boolean expectsList, String modelClass, String n, List<String> args, List<String> params, StringBuilder urlBefore, String jsonpVarName, StringBuilder urlAfter, String dataMirror, StringBuilder headers) {
1370 boolean error = false;
1372 " case " + index + ": {\n" +
1373 " if (type == 2) { /* on error */\n" +
1374 " Exception ex = (Exception)data;\n"
1376 if (onR.onError().isEmpty()) {
1378 " ex.printStackTrace();\n"
1381 error = !findOnError(e, ((TypeElement)clazz), onR.onError(), className);
1382 body.append(" ").append(clazz.getSimpleName()).append(".").append(onR.onError()).append("(");
1383 body.append("model, ex);\n");
1387 " } else if (type == 1) {\n" +
1388 " Object[] ev = (Object[])data;\n"
1392 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1396 " " + modelClass + "[] arr = { null };\n"
1400 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1403 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
1405 for (String arg : args) {
1410 body.append(");\n");
1417 method.append(" proto.loadJSONWithHeaders(" + index + ",\n ");
1418 method.append(headers.length() == 0 ? "null" : headers).append(",\n ");
1419 method.append(urlBefore).append(", ");
1420 if (jsonpVarName != null) {
1421 method.append(urlAfter);
1423 method.append("null");
1425 if (!"GET".equals(onR.method()) || dataMirror != null) {
1426 method.append(", \"").append(onR.method()).append('"');
1427 if (dataMirror != null) {
1428 method.append(", data");
1430 method.append(", null");
1433 method.append(", null, null");
1435 for (String a : params) {
1436 method.append(", ").append(a);
1438 method.append(");\n");
1442 private boolean generateWSReceiveBody(int index, StringWriter method, StringBuilder body, OnReceive onR, ExecutableElement e, Element clazz, String className, boolean expectsList, String modelClass, String n, List<String> args, List<String> params, StringBuilder urlBefore, String jsonpVarName, StringBuilder urlAfter, String dataMirror, StringBuilder headers) {
1444 " case " + index + ": {\n" +
1445 " if (type == 0) { /* on open */\n" +
1446 " ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1449 for (String arg : args) {
1451 if (arg.startsWith("arr") || arg.startsWith("java.util.Array")) {
1452 body.append("null");
1459 body.append(");\n");
1462 " } else if (type == 2) { /* on error */\n" +
1463 " Exception value = (Exception)data;\n"
1465 if (onR.onError().isEmpty()) {
1467 " value.printStackTrace();\n"
1470 if (!findOnError(e, ((TypeElement)clazz), onR.onError(), className)) {
1473 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1474 body.append("model, value);\n");
1478 " } else if (type == 1) {\n" +
1479 " Object[] ev = (Object[])data;\n"
1483 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1487 " " + modelClass + "[] arr = { null };\n"
1491 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1494 body.append(" ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1496 for (String arg : args) {
1501 body.append(");\n");
1507 if (!onR.onError().isEmpty()) {
1508 body.append(" else if (type == 3) { /* on close */\n");
1509 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1510 body.append("model, null);\n");
1517 body.append(" }\n");
1518 method.append(" if (this.ws_").append(e.getSimpleName()).append(" == null) {\n");
1519 method.append(" this.ws_").append(e.getSimpleName());
1520 method.append("= proto.wsOpen(" + index + ", ");
1521 method.append(urlBefore).append(", data);\n");
1522 method.append(" } else {\n");
1523 method.append(" proto.wsSend(this.ws_").append(e.getSimpleName()).append(", ").append(urlBefore).append(", data");
1524 for (String a : params) {
1525 method.append(", ").append(a);
1527 method.append(");\n");
1528 method.append(" }\n");
1532 private CharSequence wrapParams(
1533 ExecutableElement ee, String id, String className, String classRef, String evName, String dataName
1535 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1536 StringBuilder params = new StringBuilder();
1537 boolean first = true;
1538 for (VariableElement ve : ee.getParameters()) {
1540 params.append(", ");
1543 String toCall = null;
1544 String toFinish = null;
1545 boolean addNull = true;
1546 if (ve.asType() == stringType) {
1547 if (ve.getSimpleName().contentEquals("id")) {
1548 params.append('"').append(id).append('"');
1551 toCall = classRef + ".proto.toString(";
1553 if (ve.asType().getKind() == TypeKind.DOUBLE) {
1554 toCall = classRef + ".proto.toNumber(";
1555 toFinish = ".doubleValue()";
1557 if (ve.asType().getKind() == TypeKind.FLOAT) {
1558 toCall = classRef + ".proto.toNumber(";
1559 toFinish = ".floatValue()";
1561 if (ve.asType().getKind() == TypeKind.INT) {
1562 toCall = classRef + ".proto.toNumber(";
1563 toFinish = ".intValue()";
1565 if (ve.asType().getKind() == TypeKind.BYTE) {
1566 toCall = classRef + ".proto.toNumber(";
1567 toFinish = ".byteValue()";
1569 if (ve.asType().getKind() == TypeKind.SHORT) {
1570 toCall = classRef + ".proto.toNumber(";
1571 toFinish = ".shortValue()";
1573 if (ve.asType().getKind() == TypeKind.LONG) {
1574 toCall = classRef + ".proto.toNumber(";
1575 toFinish = ".longValue()";
1577 if (ve.asType().getKind() == TypeKind.BOOLEAN) {
1578 toCall = "\"true\".equals(" + classRef + ".proto.toString(";
1581 if (ve.asType().getKind() == TypeKind.CHAR) {
1582 toCall = "(char)" + classRef + ".proto.toNumber(";
1583 toFinish = ".intValue()";
1585 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
1586 toCall = classRef + ".proto.toModel(" + ve.asType() + ".class, ";
1590 if (toCall != null) {
1591 params.append(toCall);
1592 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
1593 params.append(dataName);
1595 params.append(", null");
1598 if (evName == null) {
1599 final StringBuilder sb = new StringBuilder();
1600 sb.append("Unexpected string parameter name.");
1601 if (dataName != null) {
1602 sb.append(" Try \"").append(dataName).append("\"");
1604 error(sb.toString(), ee);
1606 params.append(evName);
1607 params.append(", \"");
1608 params.append(ve.getSimpleName().toString());
1609 params.append("\"");
1612 if (toFinish != null) {
1613 params.append(toFinish);
1617 String rn = fqn(ve.asType(), ee);
1618 int last = rn.lastIndexOf('.');
1620 rn = rn.substring(last + 1);
1622 if (rn.equals(className)) {
1623 params.append(classRef);
1626 StringBuilder err = new StringBuilder();
1627 err.append("Argument ").
1628 append(ve.getSimpleName()).
1629 append(" is not valid. The annotated method can only accept ").
1631 append(" argument");
1632 if (dataName != null) {
1633 err.append(" or argument named '").append(dataName).append("'");
1636 error(err.toString(), ee);
1642 private CharSequence wrapPropName(
1643 ExecutableElement ee, String className, String propName, String propValue
1645 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1646 StringBuilder params = new StringBuilder();
1647 boolean first = true;
1648 for (VariableElement ve : ee.getParameters()) {
1650 params.append(", ");
1653 if (ve.asType() == stringType) {
1654 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
1655 params.append('"').append(propValue).append('"');
1657 error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
1661 String rn = fqn(ve.asType(), ee);
1662 int last = rn.lastIndexOf('.');
1664 rn = rn.substring(last + 1);
1666 if (rn.equals(className)) {
1667 params.append("model");
1671 "@OnPrprtChange method can only accept String or " + className + " arguments",
1677 private boolean isModel(TypeMirror tm) {
1678 if (tm.getKind() == TypeKind.ERROR) {
1681 final Element e = processingEnv.getTypeUtils().asElement(tm);
1685 for (Element ch : e.getEnclosedElements()) {
1686 if (ch.getKind() == ElementKind.METHOD) {
1687 ExecutableElement ee = (ExecutableElement)ch;
1688 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
1693 return models.values().contains(e.getSimpleName().toString());
1696 private void writeToString(Prprt[] props, Writer w) throws IOException {
1697 w.write(" public String toString() {\n");
1698 w.write(" StringBuilder sb = new StringBuilder();\n");
1699 w.write(" sb.append('{');\n");
1701 for (Prprt p : props) {
1703 w.append(" sb.append('\"').append(\"" + p.name() + "\")");
1704 w.append(".append('\"').append(\":\");\n");
1705 w.append(" sb.append(TYPE.toJSON(prop_");
1706 w.append(p.name()).append("));\n");
1707 sep = " sb.append(',');\n";
1709 w.write(" sb.append('}');\n");
1710 w.write(" return sb.toString();\n");
1713 private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
1714 w.write(" public " + className + " clone() {\n");
1715 w.write(" return clone(proto.getContext());\n");
1717 w.write(" private " + className + " clone(net.java.html.BrwsrCtx ctx) {\n");
1718 w.write(" " + className + " ret = new " + className + "(ctx);\n");
1719 for (Prprt p : props) {
1720 String tn = typeName(p);
1721 String[] gs = toGetSet(p.name(), tn, p.array());
1723 boolean isModel[] = { false };
1724 boolean isEnum[] = { false };
1725 boolean isPrimitive[] = { false };
1726 checkType(p, isModel, isEnum, isPrimitive);
1728 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "();\n");
1731 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "() == null ? null : " + gs[0] + "().clone();\n");
1733 w.write(" proto.cloneList(ret." + gs[0] + "(), ctx, prop_" + p.name() + ");\n");
1737 w.write(" return ret;\n");
1741 private String inPckName(Element e, boolean preferInstance) {
1742 if (preferInstance && e.getAnnotation(Model.class).instance()) {
1743 return "model.instance";
1745 StringBuilder sb = new StringBuilder();
1746 while (e.getKind() != ElementKind.PACKAGE) {
1747 if (sb.length() == 0) {
1748 sb.append(e.getSimpleName());
1751 sb.insert(0, e.getSimpleName());
1753 e = e.getEnclosingElement();
1755 return sb.toString();
1758 private String fqn(TypeMirror pt, Element relative) {
1759 if (pt.getKind() == TypeKind.ERROR) {
1760 final Elements eu = processingEnv.getElementUtils();
1761 PackageElement pckg = eu.getPackageOf(relative);
1762 return pckg.getQualifiedName() + "." + pt.toString();
1764 return pt.toString();
1767 private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
1770 String ret = p.typeName(processingEnv);
1771 TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
1775 isPrimitive[0] = false;
1779 } catch (MirroredTypeException ex) {
1780 tm = ex.getTypeMirror();
1782 tm = processingEnv.getTypeUtils().erasure(tm);
1783 if (isPrimitive[0] = tm.getKind().isPrimitive()) {
1786 return tm.toString();
1788 final Element e = processingEnv.getTypeUtils().asElement(tm);
1789 if (e.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1792 return e.getSimpleName().toString();
1795 final Model m = e == null ? null : e.getAnnotation(Model.class);
1798 ret = findPkgName(e) + '.' + m.className();
1800 models.put(e, m.className());
1801 } else if (findModelForMthd(e)) {
1802 ret = ((TypeElement)e).getQualifiedName().toString();
1805 ret = tm.toString();
1807 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1808 enm = processingEnv.getTypeUtils().erasure(enm);
1809 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1813 private static boolean findModelForMthd(Element clazz) {
1814 if (clazz == null) {
1817 for (Element e : clazz.getEnclosedElements()) {
1818 if (e.getKind() == ElementKind.METHOD) {
1819 ExecutableElement ee = (ExecutableElement)e;
1821 ee.getSimpleName().contentEquals("modelFor") &&
1822 ee.getParameters().isEmpty()
1831 private void findParamNames(
1832 Set<String> params, Element e, String url, String jsonParam, StringBuilder... both
1836 for (int pos = 0; ;) {
1837 int next = url.indexOf('{', pos);
1839 both[wasJSON].append('"')
1840 .append(url.substring(pos).replace("\"", "\\\""))
1844 int close = url.indexOf('}', next);
1846 error("Unbalanced '{' and '}' in " + url, e);
1849 final String paramName = url.substring(next + 1, close);
1850 params.add(paramName);
1851 if (paramName.equals(jsonParam) && !jsonParam.isEmpty()) {
1852 both[wasJSON].append('"')
1853 .append(url.substring(pos, next).replace("\"", "\\\""))
1857 both[wasJSON].append('"')
1858 .append(url.substring(pos, next).replace("\"", "\\\""))
1859 .append("\" + ").append(paramName).append(" + ");
1865 private static Prprt findPrprt(Prprt[] properties, String propName) {
1866 for (Prprt p : properties) {
1867 if (propName.equals(p.name())) {
1874 private boolean isPrimitive(String type) {
1876 "int".equals(type) ||
1877 "double".equals(type) ||
1878 "long".equals(type) ||
1879 "short".equals(type) ||
1880 "byte".equals(type) ||
1881 "char".equals(type) ||
1882 "boolean".equals(type) ||
1883 "float".equals(type);
1886 private static Collection<String> findDerivedFrom(Map<String, Collection<String[]>> propsDeps, String derivedProp) {
1887 Set<String> names = new HashSet<String>();
1888 for (Map.Entry<String, Collection<String[]>> e : propsDeps.entrySet()) {
1889 for (String[] pair : e.getValue()) {
1890 if (pair[0].equals(derivedProp)) {
1891 names.add(e.getKey());
1899 private Prprt[] createProps(Element e, Property[] arr) {
1900 Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
1901 Prprt[] prev = verify.put(e, ret);
1903 error("Two sets of properties for ", e);
1908 private static String strip(String s) {
1909 int indx = s.indexOf("__");
1911 return s.substring(0, indx);
1917 private String findDataSpecified(ExecutableElement e, OnReceive onR) {
1919 return onR.data().getName();
1920 } catch (MirroredTypeException ex) {
1921 final TypeMirror tm = ex.getTypeMirror();
1923 final Element te = processingEnv.getTypeUtils().asElement(tm);
1924 if (te.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1925 name = te.getSimpleName().toString();
1927 name = tm.toString();
1929 return "java.lang.Object".equals(name) ? null : name;
1930 } catch (Exception ex) {
1934 AnnotationMirror found = null;
1935 for (AnnotationMirror am : e.getAnnotationMirrors()) {
1936 if (am.getAnnotationType().toString().equals(OnReceive.class.getName())) {
1940 if (found == null) {
1944 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : found.getElementValues().entrySet()) {
1945 ExecutableElement ee = entry.getKey();
1946 AnnotationValue av = entry.getValue();
1947 if (ee.getSimpleName().contentEquals("data")) {
1948 List<? extends Object> values = getAnnoValues(processingEnv, e, found);
1949 for (Object v : values) {
1950 String sv = v.toString();
1951 if (sv.startsWith("data = ") && sv.endsWith(".class")) {
1952 return sv.substring(7, sv.length() - 6);
1961 static List<? extends Object> getAnnoValues(ProcessingEnvironment pe, Element e, AnnotationMirror am) {
1963 Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
1964 Method m = trees.getMethod("instance", ProcessingEnvironment.class);
1965 Object instance = m.invoke(null, pe);
1966 m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
1967 Object path = m.invoke(instance, e, am);
1968 m = path.getClass().getMethod("getLeaf");
1969 Object leaf = m.invoke(path);
1970 m = leaf.getClass().getMethod("getArguments");
1971 return (List) m.invoke(leaf);
1972 } catch (Exception ex) {
1973 return Collections.emptyList();
1977 private static String findTargetId(Element e) {
1978 for (AnnotationMirror m : e.getAnnotationMirrors()) {
1979 if (m.getAnnotationType().toString().equals(Model.class.getName())) {
1980 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entrySet : m.getElementValues().entrySet()) {
1981 ExecutableElement key = entrySet.getKey();
1982 AnnotationValue value = entrySet.getValue();
1983 if ("targetId()".equals(key.toString())) {
1984 return value.toString();
1992 private static class Prprt {
1993 private final Element e;
1994 private final AnnotationMirror tm;
1995 private final Property p;
1997 public Prprt(Element e, AnnotationMirror tm, Property p) {
2015 String typeName(ProcessingEnvironment env) {
2016 RuntimeException ex;
2018 return p.type().getName();
2019 } catch (IncompleteAnnotationException e) {
2021 } catch (AnnotationTypeMismatchException e) {
2024 for (Object v : getAnnoValues(env, e, tm)) {
2025 String s = v.toString().replace(" ", "");
2026 if (s.startsWith("type=") && s.endsWith(".class")) {
2027 return s.substring(5, s.length() - 6);
2034 static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
2035 if (arr.length == 0) {
2036 return new Prprt[0];
2039 if (e.getKind() != ElementKind.CLASS) {
2040 throw new IllegalStateException("" + e.getKind());
2042 TypeElement te = (TypeElement)e;
2043 List<? extends AnnotationValue> val = null;
2044 for (AnnotationMirror an : te.getAnnotationMirrors()) {
2045 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
2046 if (entry.getKey().getSimpleName().contentEquals("properties")) {
2047 val = (List)entry.getValue().getValue();
2052 if (val == null || val.size() != arr.length) {
2053 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
2054 return new Prprt[0];
2056 Prprt[] ret = new Prprt[arr.length];
2057 BIG: for (int i = 0; i < ret.length; i++) {
2058 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
2059 ret[i] = new Prprt(e, am, arr[i]);
2066 private static final class GetSet {
2068 final String getter;
2069 final String setter;
2071 final boolean readOnly;
2072 GetSet(String name, String getter, String setter, String type, boolean readOnly) {
2074 this.getter = getter;
2075 this.setter = setter;
2077 this.readOnly = readOnly;
2082 public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
2083 final Level l = Level.FINE;
2084 LOG.log(l, " element: {0}", element);
2085 LOG.log(l, " annotation: {0}", annotation);
2086 LOG.log(l, " member: {0}", member);
2087 LOG.log(l, " userText: {0}", userText);
2088 LOG.log(l, "str: {0}", annotation.getAnnotationType().toString());
2089 if (annotation.getAnnotationType().toString().equals(OnReceive.class.getName())) {
2090 if (member.getSimpleName().contentEquals("method")) {
2091 return Arrays.asList(
2097 methodOf("WebSocket")
2102 return super.getCompletions(element, annotation, member, userText);
2105 private static final Completion methodOf(String method) {
2106 ResourceBundle rb = ResourceBundle.getBundle("org.netbeans.html.json.impl.Bundle");
2107 return Completions.of('"' + method + '"', rb.getString("MSG_Completion_" + method));
2110 private boolean findOnError(ExecutableElement errElem, TypeElement te, String name, String className) {
2113 for (Element e : te.getEnclosedElements()) {
2114 if (e.getKind() != ElementKind.METHOD) {
2117 if (!e.getSimpleName().contentEquals(name)) {
2120 if (!e.getModifiers().contains(Modifier.STATIC)) {
2121 errElem = (ExecutableElement) e;
2122 err = "Would have to be static";
2125 ExecutableElement ee = (ExecutableElement) e;
2126 TypeMirror excType = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
2127 final List<? extends VariableElement> params = ee.getParameters();
2128 boolean error = false;
2129 if (params.size() != 2) {
2132 String firstType = params.get(0).asType().toString();
2133 int lastDot = firstType.lastIndexOf('.');
2134 if (lastDot != -1) {
2135 firstType = firstType.substring(lastDot + 1);
2137 if (!firstType.equals(className)) {
2140 if (!processingEnv.getTypeUtils().isAssignable(excType, params.get(1).asType())) {
2145 errElem = (ExecutableElement) e;
2146 err = "Error method first argument needs to be " + className + " and second Exception";
2152 err = "Cannot find " + name + "(" + className + ", Exception) method in this class";
2154 error(err, errElem);
2158 private ExecutableElement findWrite(ExecutableElement computedPropElem, TypeElement te, String name, String className) {
2161 for (Element e : te.getEnclosedElements()) {
2162 if (e.getKind() != ElementKind.METHOD) {
2165 if (!e.getSimpleName().contentEquals(name)) {
2168 if (e.equals(computedPropElem)) {
2171 if (!e.getModifiers().contains(Modifier.STATIC)) {
2172 computedPropElem = (ExecutableElement) e;
2173 err = "Would have to be static";
2176 ExecutableElement ee = (ExecutableElement) e;
2177 if (ee.getReturnType().getKind() != TypeKind.VOID) {
2178 computedPropElem = (ExecutableElement) e;
2179 err = "Write method has to return void";
2182 TypeMirror retType = computedPropElem.getReturnType();
2183 final List<? extends VariableElement> params = ee.getParameters();
2184 boolean error = false;
2185 if (params.size() != 2) {
2188 String firstType = params.get(0).asType().toString();
2189 int lastDot = firstType.lastIndexOf('.');
2190 if (lastDot != -1) {
2191 firstType = firstType.substring(lastDot + 1);
2193 if (!firstType.equals(className)) {
2196 if (!processingEnv.getTypeUtils().isAssignable(retType, params.get(1).asType())) {
2201 computedPropElem = (ExecutableElement) e;
2202 err = "Write method first argument needs to be " + className + " and second " + retType + " or Object";
2208 err = "Cannot find " + name + "(" + className + ", value) method in this class";
2210 error(err, computedPropElem);