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(\""
266 if (functionDeps.containsKey(p.name())) {
267 int index = Arrays.asList(functionDeps.keySet().toArray()).indexOf(p.name());
268 w.write(", " + index);
272 Collection<String[]> dependants = propsDeps.get(p.name());
273 if (dependants != null) {
274 for (String[] depProp : dependants) {
286 w.append(" public ").append(className).append("() {\n");
287 w.append(" this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
288 for (Prprt p : props) {
290 boolean[] isModel = {false};
291 boolean[] isEnum = {false};
292 boolean isPrimitive[] = {false};
293 String tn = checkType(p, isModel, isEnum, isPrimitive);
295 w.write(" prop_" + p.name() + " = this;\n");
300 if (props.length > 0 && builderPrefix == null) {
301 StringBuilder constructorWithArguments = new StringBuilder();
302 constructorWithArguments.append(" public ").append(className).append("(");
303 Prprt firstArray = null;
305 int parameterCount = 0;
306 for (Prprt p : props) {
308 if (firstArray == null) {
313 String tn = typeName(p);
314 constructorWithArguments.append(sep);
315 constructorWithArguments.append(tn);
316 String[] third = toGetSet(p.name(), tn, false);
317 constructorWithArguments.append(" ").append(third[2]);
321 if (firstArray != null) {
323 boolean[] isModel = {false};
324 boolean[] isEnum = {false};
325 boolean isPrimitive[] = {false};
326 tn = checkType(firstArray, isModel, isEnum, isPrimitive);
327 constructorWithArguments.append(sep);
328 constructorWithArguments.append(tn);
329 String[] third = toGetSet(firstArray.name(), tn, true);
330 constructorWithArguments.append("... ").append(third[2]);
333 constructorWithArguments.append(") {\n");
334 constructorWithArguments.append(" this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
335 for (Prprt p : props) {
339 String[] third = toGetSet(p.name(), null, false);
340 constructorWithArguments.append(" this.prop_" + p.name() + " = " + third[2] + ";\n");
342 if (firstArray != null) {
343 String[] third = toGetSet(firstArray.name(), null, true);
344 constructorWithArguments.append(" proto.initTo(this.prop_" + firstArray.name() + ", " + third[2] + ");\n");
346 constructorWithArguments.append(" };\n");
347 if (parameterCount < 255) {
348 w.write(constructorWithArguments.toString());
351 w.append(" private static class Html4JavaType extends org.netbeans.html.json.spi.Proto.Type<").append(className).append("> {\n");
352 w.append(" private Html4JavaType() {\n super(").append(className).append(".class, ").
353 append(inPckName).append(".class, " + propsGetSet.size() + ", "
354 + functionsCount + ");\n");
356 for (int i = 0; i < propsGetSet.size(); i++) {
357 w.append(" registerProperty(\"").append(propsGetSet.get(i).name).append("\", ");
358 w.append((i) + ", " + propsGetSet.get(i).readOnly + ");\n");
362 for (int i = 0; i < functionsCount; i++) {
363 w.append(" registerFunction(\"").append((String)functions.get(i * 2)).append("\", ");
364 w.append(i + ");\n");
368 w.append(" @Override public void setValue(" + className + " data, int type, Object value) {\n");
369 w.append(" switch (type) {\n");
370 for (int i = 0; i < propsGetSet.size(); i++) {
371 final GetSet pgs = propsGetSet.get(i);
375 final String set = pgs.setter;
376 String tn = pgs.type;
377 String btn = findBoxedType(tn);
381 w.append(" case " + i + ": ");
382 if (pgs.setter != null) {
383 w.append("data.").append(strip(pgs.setter)).append("(TYPE.extractValue(" + tn + ".class, value)); return;\n");
385 w.append("TYPE.replaceValue(data.").append(strip(pgs.getter)).append("(), " + tn + ".class, value); return;\n");
389 w.append(" throw new UnsupportedOperationException();\n");
391 w.append(" @Override public Object getValue(" + className + " data, int type) {\n");
392 w.append(" switch (type) {\n");
393 for (int i = 0; i < propsGetSet.size(); i++) {
394 final String get = propsGetSet.get(i).getter;
396 w.append(" case " + i + ": return data." + strip(get) + "();\n");
400 w.append(" throw new UnsupportedOperationException();\n");
402 w.append(" @Override public void call(" + className + " model, int type, Object data, Object ev) throws Exception {\n");
403 w.append(" switch (type) {\n");
404 for (int i = 0; i < functions.size(); i += 2) {
405 final String name = (String)functions.get(i);
406 final Object param = functions.get(i + 1);
407 if (param instanceof ExecutableElement) {
408 ExecutableElement ee = (ExecutableElement)param;
409 w.append(" case " + (i / 2) + ":\n");
412 w.append("model.instance");
414 w.append(((TypeElement)e).getQualifiedName());
416 w.append(".").append(name).append("(");
417 w.append(wrapParams(ee, null, className, "model", "ev", "data"));
419 w.append(" return;\n");
421 String call = (String)param;
422 w.append(" case " + (i / 2) + ":\n"); // model." + name + "(data, ev); return;\n");
423 w.append(" ").append(call).append("\n");
424 w.append(" return;\n");
429 w.append(" throw new UnsupportedOperationException();\n");
431 w.append(" @Override public org.netbeans.html.json.spi.Proto protoFor(Object obj) {\n");
432 w.append(" return ((" + className + ")obj).proto;");
434 w.append(" @Override public void onChange(" + className + " model, int type) {\n");
435 w.append(" switch (type) {\n");
437 String[] arr = functionDeps.keySet().toArray(new String[0]);
438 for (int i = 0; i < arr.length; i++) {
439 Collection<String> onChange = functionDeps.get(arr[i]);
440 if (onChange != null) {
441 w.append(" case " + i + ":\n");
442 for (String call : onChange) {
443 w.append(" ").append(call).append("\n");
445 w.write(" return;\n");
450 w.append(" throw new UnsupportedOperationException();\n");
452 w.append(onReceiveType);
453 w.append(" @Override public " + className + " read(net.java.html.BrwsrCtx c, Object json) { return new " + className + "(c, json); }\n");
454 w.append(" @Override public " + className + " cloneTo(" + className + " o, net.java.html.BrwsrCtx c) { return o.clone(c); }\n");
456 w.append(" private ").append(className).append("(net.java.html.BrwsrCtx c, Object json) {\n");
457 w.append(" this(c);\n");
459 for (int i = 0; i < propsGetSet.size(); i++) {
460 Prprt p = findPrprt(props, propsGetSet.get(i).name);
466 w.append(" Object[] ret = new Object[" + values + "];\n");
467 w.append(" proto.extract(json, new String[] {\n");
468 for (int i = 0; i < propsGetSet.size(); i++) {
469 Prprt p = findPrprt(props, propsGetSet.get(i).name);
473 w.append(" \"").append(propsGetSet.get(i).name).append("\",\n");
475 w.append(" }, ret);\n");
476 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i++) {
477 final String pn = propsGetSet.get(i).name;
478 Prprt p = findPrprt(props, pn);
479 if (p == null || prop >= props.length) {
482 boolean[] isModel = { false };
483 boolean[] isEnum = { false };
484 boolean isPrimitive[] = { false };
485 String type = checkType(props[prop++], isModel, isEnum, isPrimitive);
487 w.append(" for (Object e : useAsArray(ret[" + cnt + "])) {\n");
489 w.append(" this.prop_").append(pn).append(".add(proto.read");
490 w.append("(" + type + ".class, e));\n");
491 } else if (isEnum[0]) {
492 w.append(" this.prop_").append(pn);
493 w.append(".add(e == null ? null : ");
494 w.append(type).append(".valueOf(TYPE.stringValue(e)));\n");
496 if (isPrimitive(type)) {
497 if (type.equals("char")) {
498 w.append(" this.prop_").append(pn).append(".add((char)TYPE.numberValue(e).");
499 w.append("intValue());\n");
501 w.append(" this.prop_").append(pn).append(".add(TYPE.numberValue(e).");
502 w.append(type).append("Value());\n");
505 w.append(" this.prop_").append(pn).append(".add((");
506 w.append(type).append(")e);\n");
512 w.append(" try {\n");
513 w.append(" this.prop_").append(pn);
514 w.append(" = ret[" + cnt + "] == null ? null : ");
515 w.append(type).append(".valueOf(TYPE.stringValue(ret[" + cnt + "]));\n");
516 w.append(" } catch (IllegalArgumentException ex) {\n");
517 w.append(" ex.printStackTrace();\n");
519 } else if (isPrimitive(type)) {
520 w.append(" this.prop_").append(pn);
521 w.append(" = ret[" + cnt + "] == null ? ");
522 if ("char".equals(type)) {
523 w.append("0 : (TYPE.charValue(");
524 } else if ("boolean".equals(type)) {
525 w.append("false : (TYPE.boolValue(");
527 w.append("0 : (TYPE.numberValue(");
529 w.append("ret[" + cnt + "])).");
530 w.append(type).append("Value();\n");
531 } else if (isModel[0]) {
532 w.append(" this.prop_").append(pn).append(" = proto.read");
533 w.append("(" + type + ".class, ");
534 w.append("ret[" + cnt + "]);\n");
536 w.append(" this.prop_").append(pn);
537 w.append(" = (").append(type).append(')');
538 w.append("ret[" + cnt + "];\n");
544 w.append(" private static Object[] useAsArray(Object o) {\n");
545 w.append(" return o instanceof Object[] ? ((Object[])o) : o == null ? new Object[0] : new Object[] { o };\n");
547 writeToString(props, w);
548 writeClone(className, props, w);
549 String targetId = findTargetId(e);
550 if (targetId != null) {
551 w.write(" /** Activates this model instance in the current {@link \n"
552 + "net.java.html.json.Models#bind(java.lang.Object, net.java.html.BrwsrCtx) browser context}. \n"
553 + "In case of using Knockout technology, this means to \n"
554 + "bind JSON like data in this model instance with Knockout tags in \n"
555 + "the surrounding HTML page.\n"
557 if (targetId != null) {
558 w.write("This method binds to element '" + targetId + "' on the page\n");
561 + "@return <code>this</code> object\n"
564 w.write(" public " + className + " applyBindings() {\n");
565 w.write(" proto.applyBindings();\n");
566 // w.write(" proto.applyBindings(id);\n");
567 w.write(" return this;\n");
570 w.write(" private " + className + " applyBindings() {\n");
571 w.write(" throw new IllegalStateException(\"Please specify targetId=\\\"\\\" in your @Model annotation\");\n");
574 w.write(" public boolean equals(Object o) {\n");
575 w.write(" if (o == this) return true;\n");
576 w.write(" if (!(o instanceof " + className + ")) return false;\n");
577 w.write(" " + className + " p = (" + className + ")o;\n");
578 for (Prprt p : props) {
579 w.write(" if (!TYPE.isSame(prop_" + p.name() + ", p.prop_" + p.name() + ")) return false;\n");
581 w.write(" return true;\n");
583 w.write(" public int hashCode() {\n");
584 w.write(" int h = " + className + ".class.getName().hashCode();\n");
585 for (Prprt p : props) {
586 w.write(" h = TYPE.hashPlus(prop_" + p.name() + ", h);\n");
588 w.write(" return h;\n");
594 } catch (IOException ex) {
595 error("Can't create " + className + ".java", e);
601 private static String findBuilderPrefix(Element e, Model m) {
602 if (!m.builder().isEmpty()) {
605 for (AnnotationMirror am : e.getAnnotationMirrors()) {
606 for (Map.Entry<? extends Object, ? extends Object> entry : am.getElementValues().entrySet()) {
607 if ("builder()".equals(entry.getKey().toString())) {
615 private static String builderMethod(String builderPrefix, Prprt p) {
616 if (builderPrefix.isEmpty()) {
619 return builderPrefix + Character.toUpperCase(p.name().charAt(0)) + p.name().substring(1);
622 private boolean generateProperties(
623 Element where, String builderPrefix,
624 Writer w, String className, Prprt[] properties,
626 Map<String,Collection<String[]>> deps,
627 Map<String,Collection<String>> functionDeps
628 ) throws IOException {
630 for (Prprt p : properties) {
633 String[] gs = toGetSet(p.name(), tn, p.array());
637 w.write(" private final java.util.List<" + tn + "> prop_" + p.name() + ";\n");
639 castTo = "java.util.List";
640 w.write(" public java.util.List<" + tn + "> " + gs[0] + "() {\n");
641 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
642 w.write(" return prop_" + p.name() + ";\n");
644 if (builderPrefix != null) {
645 boolean[] isModel = {false};
646 boolean[] isEnum = {false};
647 boolean isPrimitive[] = {false};
648 String ret = checkType(p, isModel, isEnum, isPrimitive);
649 w.write(" public " + className + " " + builderMethod(builderPrefix, p) + "(" + ret + "... v) {\n");
650 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
651 w.append(" TYPE.replaceValue(prop_").append(p.name()).append(", " + tn + ".class, v);\n");
652 w.write(" return this;\n");
657 boolean isModel[] = { false };
658 boolean isEnum[] = { false };
659 boolean isPrimitive[] = { false };
660 checkType(p, isModel, isEnum, isPrimitive);
662 w.write(" private /*" + tn + "*/Object prop_" + p.name() + ";\n");
665 w.write(" private " + tn + " prop_" + p.name() + ";\n");
667 w.write(" public " + tn + " " + gs[0] + "() {\n");
668 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
670 w.write(" if (prop_" + p.name() + " == this) prop_" + p.name() + " = new " + tn +"();\n");
672 w.write(" return (" + tn + ")prop_" + p.name() + ";\n");
674 w.write(" public void " + gs[1] + "(" + tn + " v) {\n");
675 w.write(" proto.verifyUnlocked();\n");
676 w.write(" Object o = prop_" + p.name() + ";\n");
678 w.write(" if (o == v) return;\n");
679 w.write(" prop_" + p.name() + " = v;\n");
681 w.write(" if (TYPE.isSame(o , v)) return;\n");
682 w.write(" prop_" + p.name() + " = v;\n");
684 w.write(" proto.valueHasMutated(\"" + p.name() + "\", o, v);\n");
686 Collection<String[]> dependants = deps.get(p.name());
687 if (dependants != null) {
688 for (String[] pair : dependants) {
689 w.write(" proto.valueHasMutated(\"" + pair[0] + "\", null, " + pair[1] + "());\n");
694 Collection<String> dependants = functionDeps.get(p.name());
695 if (dependants != null) {
697 w.append(className).append(" model = ").append(className).append(".this;\n");
698 for (String call : dependants) {
699 w.append(" ").append(call);
704 if (builderPrefix != null) {
705 w.write(" public " + className + " " + builderMethod(builderPrefix, p) + "(" + tn + " v) {\n");
706 w.write(" " + gs[1] + "(v);\n");
707 w.write(" return this;\n");
712 for (int i = 0; i < props.size(); i++) {
713 if (props.get(i).name.equals(p.name())) {
714 error("Cannot have the name " + p.name() + " defined twice", where);
719 props.add(new GetSet(
724 gs[3] == null && !p.array()
730 private boolean generateComputedProperties(
732 Writer w, Prprt[] fixedProps,
733 Collection<? extends Element> arr, Collection<GetSet> props,
734 Map<String,Collection<String[]>> deps
735 ) throws IOException {
737 for (Element e : arr) {
738 if (e.getKind() != ElementKind.METHOD) {
741 final ComputedProperty cp = e.getAnnotation(ComputedProperty.class);
742 final Transitive tp = e.getAnnotation(Transitive.class);
746 if (!e.getModifiers().contains(Modifier.STATIC)) {
747 error("Method " + e.getSimpleName() + " has to be static when annotated by @ComputedProperty", e);
751 ExecutableElement ee = (ExecutableElement)e;
752 ExecutableElement write = null;
753 if (!cp.write().isEmpty()) {
754 write = findWrite(ee, (TypeElement)e.getEnclosingElement(), cp.write(), className);
757 final TypeMirror rt = ee.getReturnType();
758 final Types tu = processingEnv.getTypeUtils();
759 TypeMirror ert = tu.erasure(rt);
760 String tn = fqn(ert, ee);
761 boolean array = false;
762 final TypeMirror toCheck;
763 if (tn.equals("java.util.List")) {
765 toCheck = ((DeclaredType)rt).getTypeArguments().get(0);
770 final String sn = ee.getSimpleName().toString();
772 if (toCheck.getKind().isPrimitive()) {
775 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
776 TypeMirror enumType = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
778 if (tu.isSubtype(toCheck, stringType)) {
780 } else if (tu.isSubtype(tu.erasure(toCheck), tu.erasure(enumType))) {
782 } else if (isModel(toCheck)) {
786 tu.unboxedType(toCheck);
787 // boxed types are OK
788 } catch (IllegalArgumentException ex) {
790 error(sn + " cannot return " + toCheck, e);
795 String[] gs = toGetSet(sn, tn, array);
797 w.write(" public " + tn);
799 w.write("<" + toCheck + ">");
801 w.write(" " + gs[0] + "() {\n");
803 boolean deep = false;
804 for (VariableElement pe : ee.getParameters()) {
805 final String dn = pe.getSimpleName().toString();
807 if (!verifyPropName(pe, dn, fixedProps)) {
810 final TypeMirror pt = pe.asType();
814 final String dt = fqn(pt, ee);
815 if (dt.startsWith("java.util.List") && pt instanceof DeclaredType) {
816 final List<? extends TypeMirror> ptArgs = ((DeclaredType)pt).getTypeArguments();
817 if (ptArgs.size() == 1 && isModel(ptArgs.get(0))) {
821 String[] call = toGetSet(dn, dt, false);
822 w.write(" " + dt + " arg" + (++arg) + " = ");
823 w.write(call[0] + "();\n");
825 Collection<String[]> depends = deps.get(dn);
826 if (depends == null) {
827 depends = new LinkedHashSet<String[]>();
828 deps.put(dn, depends);
830 depends.add(new String[] { sn, gs[0] });
837 w.write(" proto.acquireLock(\"" + sn + "\");\n");
839 w.write(" proto.acquireLock();\n");
841 w.write(" return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
843 for (int i = 1; i <= arg; i++) {
849 w.write(" } finally {\n");
850 w.write(" proto.releaseLock();\n");
855 props.add(new GetSet(
856 e.getSimpleName().toString(),
863 w.write(" public void " + gs[4] + "(" + write.getParameters().get(1).asType());
864 w.write(" value) {\n");
865 w.write(" " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + write.getSimpleName() + "(this, value);\n");
868 props.add(new GetSet(
869 e.getSimpleName().toString(),
881 private static String[] toGetSet(String name, String type, boolean array) {
882 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
883 boolean clazz = "class".equals(name);
884 String pref = clazz ? "access" : "get";
885 if ("boolean".equals(type) && !array) {
889 return new String[] {
906 private String typeName(Prprt p) {
908 boolean[] isModel = { false };
909 boolean[] isEnum = { false };
910 boolean isPrimitive[] = { false };
911 ret = checkType(p, isModel, isEnum, isPrimitive);
913 String bt = findBoxedType(ret);
921 private static String findBoxedType(String ret) {
922 if (ret.equals("boolean")) {
923 return Boolean.class.getName();
925 if (ret.equals("byte")) {
926 return Byte.class.getName();
928 if (ret.equals("short")) {
929 return Short.class.getName();
931 if (ret.equals("char")) {
932 return Character.class.getName();
934 if (ret.equals("int")) {
935 return Integer.class.getName();
937 if (ret.equals("long")) {
938 return Long.class.getName();
940 if (ret.equals("float")) {
941 return Float.class.getName();
943 if (ret.equals("double")) {
944 return Double.class.getName();
949 private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
950 StringBuilder sb = new StringBuilder();
952 for (Prprt Prprt : existingProps) {
953 if (Prprt.name().equals(propName)) {
958 sb.append(Prprt.name());
963 propName + " is not one of known properties: " + sb
969 private static String findPkgName(Element e) {
971 if (e.getKind() == ElementKind.PACKAGE) {
972 return ((PackageElement)e).getQualifiedName().toString();
974 e = e.getEnclosingElement();
978 private boolean generateFunctions(
979 Element clazz, StringWriter body, String className,
980 List<? extends Element> enclosedElements, List<Object> functions
982 boolean instance = clazz.getAnnotation(Model.class).instance();
983 for (Element m : enclosedElements) {
984 if (m.getKind() != ElementKind.METHOD) {
987 ExecutableElement e = (ExecutableElement)m;
988 Function onF = e.getAnnotation(Function.class);
992 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
993 error("@OnFunction method needs to be static", e);
996 if (e.getModifiers().contains(Modifier.PRIVATE)) {
997 error("@OnFunction method cannot be private", e);
1000 if (e.getReturnType().getKind() != TypeKind.VOID) {
1001 error("@OnFunction method should return void", e);
1004 String n = e.getSimpleName().toString();
1011 private boolean generateOnChange(Element clazz, Map<String,Collection<String[]>> propDeps,
1012 Prprt[] properties, String className,
1013 Map<String, Collection<String>> functionDeps
1015 boolean instance = clazz.getAnnotation(Model.class).instance();
1016 for (Element m : clazz.getEnclosedElements()) {
1017 if (m.getKind() != ElementKind.METHOD) {
1020 ExecutableElement e = (ExecutableElement) m;
1021 OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
1025 for (String pn : onPC.value()) {
1026 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
1027 error("No Prprt named '" + pn + "' in the model", clazz);
1031 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1032 error("@OnPrprtChange method needs to be static", e);
1035 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1036 error("@OnPrprtChange method cannot be private", e);
1039 if (e.getReturnType().getKind() != TypeKind.VOID) {
1040 error("@OnPrprtChange method should return void", e);
1043 String n = e.getSimpleName().toString();
1046 for (String pn : onPC.value()) {
1047 StringBuilder call = new StringBuilder();
1048 call.append(" ").append(inPckName(clazz, instance)).append(".").append(n).append("(");
1049 call.append(wrapPropName(e, className, "name", pn));
1050 call.append(");\n");
1052 Collection<String> change = functionDeps.get(pn);
1053 if (change == null) {
1054 change = new ArrayList<String>();
1055 functionDeps.put(pn, change);
1057 change.add(call.toString());
1058 for (String dpn : findDerivedFrom(propDeps, pn)) {
1059 change = functionDeps.get(dpn);
1060 if (change == null) {
1061 change = new ArrayList<String>();
1062 functionDeps.put(dpn, change);
1064 change.add(call.toString());
1071 private boolean generateOperation(Element clazz,
1072 StringWriter body, String className,
1073 List<? extends Element> enclosedElements,
1074 List<Object> functions
1076 boolean instance = clazz.getAnnotation(Model.class).instance();
1077 for (Element m : enclosedElements) {
1078 if (m.getKind() != ElementKind.METHOD) {
1081 ExecutableElement e = (ExecutableElement)m;
1082 ModelOperation mO = e.getAnnotation(ModelOperation.class);
1086 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1087 error("@ModelOperation method needs to be static", e);
1090 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1091 error("@ModelOperation method cannot be private", e);
1094 if (e.getReturnType().getKind() != TypeKind.VOID) {
1095 error("@ModelOperation method should return void", e);
1098 List<String> args = new ArrayList<String>();
1100 body.append(" public void ").append(m.getSimpleName()).append("(");
1102 boolean checkFirst = true;
1103 for (VariableElement ve : e.getParameters()) {
1104 final TypeMirror type = ve.asType();
1105 CharSequence simpleName;
1106 if (type.getKind() == TypeKind.DECLARED) {
1107 simpleName = ((DeclaredType)type).asElement().getSimpleName();
1109 simpleName = type.toString();
1111 if (checkFirst && simpleName.toString().equals(className)) {
1115 error("First parameter of @ModelOperation method must be " + className, m);
1118 args.add(ve.getSimpleName().toString());
1119 body.append(sep).append("final ");
1120 body.append(ve.asType().toString()).append(" ");
1121 body.append(ve.toString());
1125 body.append(") {\n");
1126 int idx = functions.size() / 2;
1127 functions.add(m.getSimpleName().toString());
1128 body.append(" proto.runInBrowser(" + idx);
1129 for (String s : args) {
1130 body.append(", ").append(s);
1132 body.append(");\n");
1133 body.append(" }\n");
1135 StringBuilder call = new StringBuilder();
1136 call.append("{ Object[] arr = (Object[])data; ");
1137 call.append(inPckName(clazz, true)).append(".").append(m.getSimpleName()).append("(");
1139 for (VariableElement ve : e.getParameters()) {
1141 call.append("model");
1144 String type = ve.asType().toString();
1145 String boxedType = findBoxedType(type);
1146 if (boxedType != null) {
1149 call.append(", ").append("(").append(type).append(")arr[").append(i - 2).append("]");
1151 call.append("); }");
1152 functions.add(call.toString());
1160 private boolean generateReceive(
1161 Element clazz, StringWriter body, String className,
1162 List<? extends Element> enclosedElements, StringBuilder inType
1164 boolean ret = generateReceiveImpl(clazz, body, className, enclosedElements, inType);
1166 inType.setLength(0);
1170 private boolean generateReceiveImpl(
1171 Element clazz, StringWriter body, String className,
1172 List<? extends Element> enclosedElements, StringBuilder inType
1174 inType.append(" @Override public void onMessage(").append(className).append(" model, int index, int type, Object data, Object[] params) {\n");
1175 inType.append(" switch (index) {\n");
1178 boolean instance = clazz.getAnnotation(Model.class).instance();
1179 for (Element m : enclosedElements) {
1180 if (m.getKind() != ElementKind.METHOD) {
1183 ExecutableElement e = (ExecutableElement)m;
1184 OnReceive onR = e.getAnnotation(OnReceive.class);
1188 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1189 error("@OnReceive method needs to be static", e);
1192 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1193 error("@OnReceive method cannot be private", e);
1196 if (e.getReturnType().getKind() != TypeKind.VOID) {
1197 error("@OnReceive method should return void", e);
1200 if (!onR.jsonp().isEmpty() && !"GET".equals(onR.method())) {
1201 error("JSONP works only with GET transport method", e);
1203 String dataMirror = findDataSpecified(e, onR);
1204 if ("PUT".equals(onR.method()) && dataMirror == null) {
1205 error("PUT method needs to specify a data() class", e);
1208 if ("POST".equals(onR.method()) && dataMirror == null) {
1209 error("POST method needs to specify a data() class", e);
1212 if (e.getParameters().size() < 2) {
1213 error("@OnReceive method needs at least two parameters", e);
1215 final boolean isWebSocket = "WebSocket".equals(onR.method());
1216 if (isWebSocket && dataMirror == null) {
1217 error("WebSocket method needs to specify a data() class", e);
1219 int expectsList = 0;
1220 List<String> args = new ArrayList<String>();
1221 List<String> params = new ArrayList<String>();
1222 // first argument is model class
1224 TypeMirror type = e.getParameters().get(0).asType();
1225 CharSequence simpleName;
1226 if (type.getKind() == TypeKind.DECLARED) {
1227 simpleName = ((DeclaredType) type).asElement().getSimpleName();
1229 simpleName = type.toString();
1231 if (simpleName.toString().equals(className)) {
1234 error("First parameter needs to be " + className, e);
1241 final Types tu = processingEnv.getTypeUtils();
1242 TypeMirror type = e.getParameters().get(1).asType();
1243 TypeMirror modelType = null;
1244 TypeMirror ert = tu.erasure(type);
1246 if (isModel(type)) {
1248 } else if (type.getKind() == TypeKind.ARRAY) {
1249 modelType = ((ArrayType)type).getComponentType();
1251 } else if ("java.util.List".equals(fqn(ert, e))) {
1252 List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments();
1253 if (typeArgs.size() == 1) {
1254 modelType = typeArgs.get(0);
1257 } else if (type.toString().equals("java.lang.String")) {
1260 if (modelType == null) {
1261 error("Second arguments needs to be a model, String or array or List of models", e);
1264 modelClass = modelType.toString();
1265 if (expectsList == 1) {
1267 } else if (expectsList == 2) {
1268 args.add("java.util.Arrays.asList(arr)");
1273 String n = e.getSimpleName().toString();
1275 body.append(" /** Performs WebSocket communication. Call with <code>null</code> data parameter\n");
1276 body.append(" * to open the connection (even if not required). Call with non-null data to\n");
1277 body.append(" * send messages to server. Call again with <code>null</code> data to close the socket.\n");
1278 body.append(" */\n");
1279 if (onR.headers().length > 0) {
1280 error("WebSocket spec does not support headers", e);
1283 body.append(" public void ").append(n).append("(");
1284 StringBuilder urlBefore = new StringBuilder();
1285 StringBuilder urlAfter = new StringBuilder();
1286 StringBuilder headers = new StringBuilder();
1287 String jsonpVarName = null;
1290 boolean skipJSONP = onR.jsonp().isEmpty();
1291 Set<String> receiveParams = new LinkedHashSet<String>();
1292 findParamNames(receiveParams, e, onR.url(), onR.jsonp(), urlBefore, urlAfter);
1293 for (String headerLine : onR.headers()) {
1294 if (headerLine.contains("\r") || headerLine.contains("\n")) {
1295 error("Header line cannot contain line separator", e);
1297 findParamNames(receiveParams, e, headerLine, null, headers);
1298 headers.append("+ \"\\r\\n\" +\n");
1300 if (headers.length() > 0) {
1301 headers.append("\"\"");
1303 for (String p : receiveParams) {
1304 if (!skipJSONP && p.equals(onR.jsonp())) {
1310 body.append("String ").append(p);
1315 "Name of jsonp attribute ('" + onR.jsonp() +
1316 "') is not used in url attribute '" + onR.url() + "'", e
1319 if (dataMirror != null) {
1320 body.append(sep).append(dataMirror.toString()).append(" data");
1322 for (int i = 2; i < e.getParameters().size(); i++) {
1324 error("@OnReceive(method=\"WebSocket\") can only have two arguments", e);
1328 VariableElement ve = e.getParameters().get(i);
1329 body.append(sep).append(ve.asType().toString()).append(" ").append(ve.getSimpleName());
1330 final String tp = ve.asType().toString();
1331 String btn = findBoxedType(tp);
1335 args.add("(" + btn + ")params[" + (i - 2) + "]");
1336 params.add(ve.getSimpleName().toString());
1340 body.append(") {\n");
1341 boolean webSocket = onR.method().equals("WebSocket");
1343 if (generateWSReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1346 body.append(" }\n");
1347 body.append(" private Object ws_" + e.getSimpleName() + ";\n");
1349 if (generateJSONReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1352 body.append(" }\n");
1355 inType.append(" }\n");
1356 inType.append(" throw new UnsupportedOperationException(\"index: \" + index + \" type: \" + type);\n");
1357 inType.append(" }\n");
1361 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) {
1362 boolean error = false;
1364 " case " + index + ": {\n" +
1365 " if (type == 2) { /* on error */\n" +
1366 " Exception ex = (Exception)data;\n"
1368 if (onR.onError().isEmpty()) {
1370 " ex.printStackTrace();\n"
1373 error = !findOnError(e, ((TypeElement)clazz), onR.onError(), className);
1374 body.append(" ").append(clazz.getSimpleName()).append(".").append(onR.onError()).append("(");
1375 body.append("model, ex);\n");
1379 " } else if (type == 1) {\n" +
1380 " Object[] ev = (Object[])data;\n"
1384 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1388 " " + modelClass + "[] arr = { null };\n"
1392 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1395 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
1397 for (String arg : args) {
1402 body.append(");\n");
1409 method.append(" proto.loadJSONWithHeaders(" + index + ",\n ");
1410 method.append(headers.length() == 0 ? "null" : headers).append(",\n ");
1411 method.append(urlBefore).append(", ");
1412 if (jsonpVarName != null) {
1413 method.append(urlAfter);
1415 method.append("null");
1417 if (!"GET".equals(onR.method()) || dataMirror != null) {
1418 method.append(", \"").append(onR.method()).append('"');
1419 if (dataMirror != null) {
1420 method.append(", data");
1422 method.append(", null");
1425 method.append(", null, null");
1427 for (String a : params) {
1428 method.append(", ").append(a);
1430 method.append(");\n");
1434 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) {
1436 " case " + index + ": {\n" +
1437 " if (type == 0) { /* on open */\n" +
1438 " ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1441 for (String arg : args) {
1443 if (arg.startsWith("arr") || arg.startsWith("java.util.Array")) {
1444 body.append("null");
1451 body.append(");\n");
1454 " } else if (type == 2) { /* on error */\n" +
1455 " Exception value = (Exception)data;\n"
1457 if (onR.onError().isEmpty()) {
1459 " value.printStackTrace();\n"
1462 if (!findOnError(e, ((TypeElement)clazz), onR.onError(), className)) {
1465 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1466 body.append("model, value);\n");
1470 " } else if (type == 1) {\n" +
1471 " Object[] ev = (Object[])data;\n"
1475 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1479 " " + modelClass + "[] arr = { null };\n"
1483 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1486 body.append(" ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1488 for (String arg : args) {
1493 body.append(");\n");
1499 if (!onR.onError().isEmpty()) {
1500 body.append(" else if (type == 3) { /* on close */\n");
1501 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1502 body.append("model, null);\n");
1509 body.append(" }\n");
1510 method.append(" if (this.ws_").append(e.getSimpleName()).append(" == null) {\n");
1511 method.append(" this.ws_").append(e.getSimpleName());
1512 method.append("= proto.wsOpen(" + index + ", ");
1513 method.append(urlBefore).append(", data);\n");
1514 method.append(" } else {\n");
1515 method.append(" proto.wsSend(this.ws_").append(e.getSimpleName()).append(", ").append(urlBefore).append(", data");
1516 for (String a : params) {
1517 method.append(", ").append(a);
1519 method.append(");\n");
1520 method.append(" }\n");
1524 private CharSequence wrapParams(
1525 ExecutableElement ee, String id, String className, String classRef, String evName, String dataName
1527 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1528 StringBuilder params = new StringBuilder();
1529 boolean first = true;
1530 for (VariableElement ve : ee.getParameters()) {
1532 params.append(", ");
1535 String toCall = null;
1536 String toFinish = null;
1537 boolean addNull = true;
1538 if (ve.asType() == stringType) {
1539 if (ve.getSimpleName().contentEquals("id")) {
1540 params.append('"').append(id).append('"');
1543 toCall = classRef + ".proto.toString(";
1545 if (ve.asType().getKind() == TypeKind.DOUBLE) {
1546 toCall = classRef + ".proto.toNumber(";
1547 toFinish = ".doubleValue()";
1549 if (ve.asType().getKind() == TypeKind.FLOAT) {
1550 toCall = classRef + ".proto.toNumber(";
1551 toFinish = ".floatValue()";
1553 if (ve.asType().getKind() == TypeKind.INT) {
1554 toCall = classRef + ".proto.toNumber(";
1555 toFinish = ".intValue()";
1557 if (ve.asType().getKind() == TypeKind.BYTE) {
1558 toCall = classRef + ".proto.toNumber(";
1559 toFinish = ".byteValue()";
1561 if (ve.asType().getKind() == TypeKind.SHORT) {
1562 toCall = classRef + ".proto.toNumber(";
1563 toFinish = ".shortValue()";
1565 if (ve.asType().getKind() == TypeKind.LONG) {
1566 toCall = classRef + ".proto.toNumber(";
1567 toFinish = ".longValue()";
1569 if (ve.asType().getKind() == TypeKind.BOOLEAN) {
1570 toCall = "\"true\".equals(" + classRef + ".proto.toString(";
1573 if (ve.asType().getKind() == TypeKind.CHAR) {
1574 toCall = "(char)" + classRef + ".proto.toNumber(";
1575 toFinish = ".intValue()";
1577 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
1578 toCall = classRef + ".proto.toModel(" + ve.asType() + ".class, ";
1582 if (toCall != null) {
1583 params.append(toCall);
1584 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
1585 params.append(dataName);
1587 params.append(", null");
1590 if (evName == null) {
1591 final StringBuilder sb = new StringBuilder();
1592 sb.append("Unexpected string parameter name.");
1593 if (dataName != null) {
1594 sb.append(" Try \"").append(dataName).append("\"");
1596 error(sb.toString(), ee);
1598 params.append(evName);
1599 params.append(", \"");
1600 params.append(ve.getSimpleName().toString());
1601 params.append("\"");
1604 if (toFinish != null) {
1605 params.append(toFinish);
1609 String rn = fqn(ve.asType(), ee);
1610 int last = rn.lastIndexOf('.');
1612 rn = rn.substring(last + 1);
1614 if (rn.equals(className)) {
1615 params.append(classRef);
1618 StringBuilder err = new StringBuilder();
1619 err.append("Argument ").
1620 append(ve.getSimpleName()).
1621 append(" is not valid. The annotated method can only accept ").
1623 append(" argument");
1624 if (dataName != null) {
1625 err.append(" or argument named '").append(dataName).append("'");
1628 error(err.toString(), ee);
1634 private CharSequence wrapPropName(
1635 ExecutableElement ee, String className, String propName, String propValue
1637 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1638 StringBuilder params = new StringBuilder();
1639 boolean first = true;
1640 for (VariableElement ve : ee.getParameters()) {
1642 params.append(", ");
1645 if (ve.asType() == stringType) {
1646 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
1647 params.append('"').append(propValue).append('"');
1649 error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
1653 String rn = fqn(ve.asType(), ee);
1654 int last = rn.lastIndexOf('.');
1656 rn = rn.substring(last + 1);
1658 if (rn.equals(className)) {
1659 params.append("model");
1663 "@OnPrprtChange method can only accept String or " + className + " arguments",
1669 private boolean isModel(TypeMirror tm) {
1670 if (tm.getKind() == TypeKind.ERROR) {
1673 final Element e = processingEnv.getTypeUtils().asElement(tm);
1677 for (Element ch : e.getEnclosedElements()) {
1678 if (ch.getKind() == ElementKind.METHOD) {
1679 ExecutableElement ee = (ExecutableElement)ch;
1680 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
1685 return models.values().contains(e.getSimpleName().toString());
1688 private void writeToString(Prprt[] props, Writer w) throws IOException {
1689 w.write(" public String toString() {\n");
1690 w.write(" StringBuilder sb = new StringBuilder();\n");
1691 w.write(" sb.append('{');\n");
1693 for (Prprt p : props) {
1695 w.append(" sb.append('\"').append(\"" + p.name() + "\")");
1696 w.append(".append('\"').append(\":\");\n");
1697 w.append(" sb.append(TYPE.toJSON(prop_");
1698 w.append(p.name()).append("));\n");
1699 sep = " sb.append(',');\n";
1701 w.write(" sb.append('}');\n");
1702 w.write(" return sb.toString();\n");
1705 private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
1706 w.write(" public " + className + " clone() {\n");
1707 w.write(" return clone(proto.getContext());\n");
1709 w.write(" private " + className + " clone(net.java.html.BrwsrCtx ctx) {\n");
1710 w.write(" " + className + " ret = new " + className + "(ctx);\n");
1711 for (Prprt p : props) {
1712 String tn = typeName(p);
1713 String[] gs = toGetSet(p.name(), tn, p.array());
1715 boolean isModel[] = { false };
1716 boolean isEnum[] = { false };
1717 boolean isPrimitive[] = { false };
1718 checkType(p, isModel, isEnum, isPrimitive);
1720 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "();\n");
1723 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "() == null ? null : " + gs[0] + "().clone();\n");
1725 w.write(" proto.cloneList(ret." + gs[0] + "(), ctx, prop_" + p.name() + ");\n");
1729 w.write(" return ret;\n");
1733 private String inPckName(Element e, boolean preferInstance) {
1734 if (preferInstance && e.getAnnotation(Model.class).instance()) {
1735 return "model.instance";
1737 StringBuilder sb = new StringBuilder();
1738 while (e.getKind() != ElementKind.PACKAGE) {
1739 if (sb.length() == 0) {
1740 sb.append(e.getSimpleName());
1743 sb.insert(0, e.getSimpleName());
1745 e = e.getEnclosingElement();
1747 return sb.toString();
1750 private String fqn(TypeMirror pt, Element relative) {
1751 if (pt.getKind() == TypeKind.ERROR) {
1752 final Elements eu = processingEnv.getElementUtils();
1753 PackageElement pckg = eu.getPackageOf(relative);
1754 return pckg.getQualifiedName() + "." + pt.toString();
1756 return pt.toString();
1759 private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
1762 String ret = p.typeName(processingEnv);
1763 TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
1767 isPrimitive[0] = false;
1771 } catch (MirroredTypeException ex) {
1772 tm = ex.getTypeMirror();
1774 tm = processingEnv.getTypeUtils().erasure(tm);
1775 if (isPrimitive[0] = tm.getKind().isPrimitive()) {
1778 return tm.toString();
1780 final Element e = processingEnv.getTypeUtils().asElement(tm);
1781 if (e.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1784 return e.getSimpleName().toString();
1787 final Model m = e == null ? null : e.getAnnotation(Model.class);
1790 ret = findPkgName(e) + '.' + m.className();
1792 models.put(e, m.className());
1793 } else if (findModelForMthd(e)) {
1794 ret = ((TypeElement)e).getQualifiedName().toString();
1797 ret = tm.toString();
1799 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1800 enm = processingEnv.getTypeUtils().erasure(enm);
1801 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1805 private static boolean findModelForMthd(Element clazz) {
1806 if (clazz == null) {
1809 for (Element e : clazz.getEnclosedElements()) {
1810 if (e.getKind() == ElementKind.METHOD) {
1811 ExecutableElement ee = (ExecutableElement)e;
1813 ee.getSimpleName().contentEquals("modelFor") &&
1814 ee.getParameters().isEmpty()
1823 private void findParamNames(
1824 Set<String> params, Element e, String url, String jsonParam, StringBuilder... both
1828 for (int pos = 0; ;) {
1829 int next = url.indexOf('{', pos);
1831 both[wasJSON].append('"')
1832 .append(url.substring(pos).replace("\"", "\\\""))
1836 int close = url.indexOf('}', next);
1838 error("Unbalanced '{' and '}' in " + url, e);
1841 final String paramName = url.substring(next + 1, close);
1842 params.add(paramName);
1843 if (paramName.equals(jsonParam) && !jsonParam.isEmpty()) {
1844 both[wasJSON].append('"')
1845 .append(url.substring(pos, next).replace("\"", "\\\""))
1849 both[wasJSON].append('"')
1850 .append(url.substring(pos, next).replace("\"", "\\\""))
1851 .append("\" + ").append(paramName).append(" + ");
1857 private static Prprt findPrprt(Prprt[] properties, String propName) {
1858 for (Prprt p : properties) {
1859 if (propName.equals(p.name())) {
1866 private boolean isPrimitive(String type) {
1868 "int".equals(type) ||
1869 "double".equals(type) ||
1870 "long".equals(type) ||
1871 "short".equals(type) ||
1872 "byte".equals(type) ||
1873 "char".equals(type) ||
1874 "boolean".equals(type) ||
1875 "float".equals(type);
1878 private static Collection<String> findDerivedFrom(Map<String, Collection<String[]>> propsDeps, String derivedProp) {
1879 Set<String> names = new HashSet<String>();
1880 for (Map.Entry<String, Collection<String[]>> e : propsDeps.entrySet()) {
1881 for (String[] pair : e.getValue()) {
1882 if (pair[0].equals(derivedProp)) {
1883 names.add(e.getKey());
1891 private Prprt[] createProps(Element e, Property[] arr) {
1892 Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
1893 Prprt[] prev = verify.put(e, ret);
1895 error("Two sets of properties for ", e);
1900 private static String strip(String s) {
1901 int indx = s.indexOf("__");
1903 return s.substring(0, indx);
1909 private String findDataSpecified(ExecutableElement e, OnReceive onR) {
1911 return onR.data().getName();
1912 } catch (MirroredTypeException ex) {
1913 final TypeMirror tm = ex.getTypeMirror();
1915 final Element te = processingEnv.getTypeUtils().asElement(tm);
1916 if (te.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1917 name = te.getSimpleName().toString();
1919 name = tm.toString();
1921 return "java.lang.Object".equals(name) ? null : name;
1922 } catch (Exception ex) {
1926 AnnotationMirror found = null;
1927 for (AnnotationMirror am : e.getAnnotationMirrors()) {
1928 if (am.getAnnotationType().toString().equals(OnReceive.class.getName())) {
1932 if (found == null) {
1936 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : found.getElementValues().entrySet()) {
1937 ExecutableElement ee = entry.getKey();
1938 AnnotationValue av = entry.getValue();
1939 if (ee.getSimpleName().contentEquals("data")) {
1940 List<? extends Object> values = getAnnoValues(processingEnv, e, found);
1941 for (Object v : values) {
1942 String sv = v.toString();
1943 if (sv.startsWith("data = ") && sv.endsWith(".class")) {
1944 return sv.substring(7, sv.length() - 6);
1953 static List<? extends Object> getAnnoValues(ProcessingEnvironment pe, Element e, AnnotationMirror am) {
1955 Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
1956 Method m = trees.getMethod("instance", ProcessingEnvironment.class);
1957 Object instance = m.invoke(null, pe);
1958 m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
1959 Object path = m.invoke(instance, e, am);
1960 m = path.getClass().getMethod("getLeaf");
1961 Object leaf = m.invoke(path);
1962 m = leaf.getClass().getMethod("getArguments");
1963 return (List) m.invoke(leaf);
1964 } catch (Exception ex) {
1965 return Collections.emptyList();
1969 private static String findTargetId(Element e) {
1970 for (AnnotationMirror m : e.getAnnotationMirrors()) {
1971 if (m.getAnnotationType().toString().equals(Model.class.getName())) {
1972 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entrySet : m.getElementValues().entrySet()) {
1973 ExecutableElement key = entrySet.getKey();
1974 AnnotationValue value = entrySet.getValue();
1975 if ("targetId()".equals(key.toString())) {
1976 return value.toString();
1984 private static class Prprt {
1985 private final Element e;
1986 private final AnnotationMirror tm;
1987 private final Property p;
1989 public Prprt(Element e, AnnotationMirror tm, Property p) {
2003 String typeName(ProcessingEnvironment env) {
2004 RuntimeException ex;
2006 return p.type().getName();
2007 } catch (IncompleteAnnotationException e) {
2009 } catch (AnnotationTypeMismatchException e) {
2012 for (Object v : getAnnoValues(env, e, tm)) {
2013 String s = v.toString().replace(" ", "");
2014 if (s.startsWith("type=") && s.endsWith(".class")) {
2015 return s.substring(5, s.length() - 6);
2022 static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
2023 if (arr.length == 0) {
2024 return new Prprt[0];
2027 if (e.getKind() != ElementKind.CLASS) {
2028 throw new IllegalStateException("" + e.getKind());
2030 TypeElement te = (TypeElement)e;
2031 List<? extends AnnotationValue> val = null;
2032 for (AnnotationMirror an : te.getAnnotationMirrors()) {
2033 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
2034 if (entry.getKey().getSimpleName().contentEquals("properties")) {
2035 val = (List)entry.getValue().getValue();
2040 if (val == null || val.size() != arr.length) {
2041 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
2042 return new Prprt[0];
2044 Prprt[] ret = new Prprt[arr.length];
2045 BIG: for (int i = 0; i < ret.length; i++) {
2046 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
2047 ret[i] = new Prprt(e, am, arr[i]);
2054 private static final class GetSet {
2056 final String getter;
2057 final String setter;
2059 final boolean readOnly;
2060 GetSet(String name, String getter, String setter, String type, boolean readOnly) {
2062 this.getter = getter;
2063 this.setter = setter;
2065 this.readOnly = readOnly;
2070 public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
2071 final Level l = Level.FINE;
2072 LOG.log(l, " element: {0}", element);
2073 LOG.log(l, " annotation: {0}", annotation);
2074 LOG.log(l, " member: {0}", member);
2075 LOG.log(l, " userText: {0}", userText);
2076 LOG.log(l, "str: {0}", annotation.getAnnotationType().toString());
2077 if (annotation.getAnnotationType().toString().equals(OnReceive.class.getName())) {
2078 if (member.getSimpleName().contentEquals("method")) {
2079 return Arrays.asList(
2085 methodOf("WebSocket")
2090 return super.getCompletions(element, annotation, member, userText);
2093 private static final Completion methodOf(String method) {
2094 ResourceBundle rb = ResourceBundle.getBundle("org.netbeans.html.json.impl.Bundle");
2095 return Completions.of('"' + method + '"', rb.getString("MSG_Completion_" + method));
2098 private boolean findOnError(ExecutableElement errElem, TypeElement te, String name, String className) {
2101 for (Element e : te.getEnclosedElements()) {
2102 if (e.getKind() != ElementKind.METHOD) {
2105 if (!e.getSimpleName().contentEquals(name)) {
2108 if (!e.getModifiers().contains(Modifier.STATIC)) {
2109 errElem = (ExecutableElement) e;
2110 err = "Would have to be static";
2113 ExecutableElement ee = (ExecutableElement) e;
2114 TypeMirror excType = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
2115 final List<? extends VariableElement> params = ee.getParameters();
2116 boolean error = false;
2117 if (params.size() != 2) {
2120 String firstType = params.get(0).asType().toString();
2121 int lastDot = firstType.lastIndexOf('.');
2122 if (lastDot != -1) {
2123 firstType = firstType.substring(lastDot + 1);
2125 if (!firstType.equals(className)) {
2128 if (!processingEnv.getTypeUtils().isAssignable(excType, params.get(1).asType())) {
2133 errElem = (ExecutableElement) e;
2134 err = "Error method first argument needs to be " + className + " and second Exception";
2140 err = "Cannot find " + name + "(" + className + ", Exception) method in this class";
2142 error(err, errElem);
2146 private ExecutableElement findWrite(ExecutableElement computedPropElem, TypeElement te, String name, String className) {
2149 for (Element e : te.getEnclosedElements()) {
2150 if (e.getKind() != ElementKind.METHOD) {
2153 if (!e.getSimpleName().contentEquals(name)) {
2156 if (e.equals(computedPropElem)) {
2159 if (!e.getModifiers().contains(Modifier.STATIC)) {
2160 computedPropElem = (ExecutableElement) e;
2161 err = "Would have to be static";
2164 ExecutableElement ee = (ExecutableElement) e;
2165 if (ee.getReturnType().getKind() != TypeKind.VOID) {
2166 computedPropElem = (ExecutableElement) e;
2167 err = "Write method has to return void";
2170 TypeMirror retType = computedPropElem.getReturnType();
2171 final List<? extends VariableElement> params = ee.getParameters();
2172 boolean error = false;
2173 if (params.size() != 2) {
2176 String firstType = params.get(0).asType().toString();
2177 int lastDot = firstType.lastIndexOf('.');
2178 if (lastDot != -1) {
2179 firstType = firstType.substring(lastDot + 1);
2181 if (!firstType.equals(className)) {
2184 if (!processingEnv.getTypeUtils().isAssignable(retType, params.get(1).asType())) {
2189 computedPropElem = (ExecutableElement) e;
2190 err = "Write method first argument needs to be " + className + " and second " + retType + " or Object";
2196 err = "Cannot find " + name + "(" + className + ", value) method in this class";
2198 error(err, computedPropElem);