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() + " = new " + tn + "();\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);
661 w.write(" private " + tn + " prop_" + p.name() + ";\n");
662 w.write(" public " + tn + " " + gs[0] + "() {\n");
663 w.write(" proto.accessProperty(\"" + p.name() + "\");\n");
664 w.write(" return prop_" + p.name() + ";\n");
666 w.write(" public void " + gs[1] + "(" + tn + " v) {\n");
667 w.write(" proto.verifyUnlocked();\n");
668 w.write(" Object o = prop_" + p.name() + ";\n");
670 w.write(" if (o == v) return;\n");
671 w.write(" prop_" + p.name() + " = v;\n");
673 w.write(" if (TYPE.isSame(o , v)) return;\n");
674 w.write(" prop_" + p.name() + " = v;\n");
676 w.write(" proto.valueHasMutated(\"" + p.name() + "\", o, v);\n");
678 Collection<String[]> dependants = deps.get(p.name());
679 if (dependants != null) {
680 for (String[] pair : dependants) {
681 w.write(" proto.valueHasMutated(\"" + pair[0] + "\", null, " + pair[1] + "());\n");
686 Collection<String> dependants = functionDeps.get(p.name());
687 if (dependants != null) {
689 w.append(className).append(" model = ").append(className).append(".this;\n");
690 for (String call : dependants) {
691 w.append(" ").append(call);
696 if (builderPrefix != null) {
697 w.write(" public " + className + " " + builderMethod(builderPrefix, p) + "(" + tn + " v) {\n");
698 w.write(" " + gs[1] + "(v);\n");
699 w.write(" return this;\n");
704 for (int i = 0; i < props.size(); i++) {
705 if (props.get(i).name.equals(p.name())) {
706 error("Cannot have the name " + p.name() + " defined twice", where);
711 props.add(new GetSet(
716 gs[3] == null && !p.array()
722 private boolean generateComputedProperties(
724 Writer w, Prprt[] fixedProps,
725 Collection<? extends Element> arr, Collection<GetSet> props,
726 Map<String,Collection<String[]>> deps
727 ) throws IOException {
729 for (Element e : arr) {
730 if (e.getKind() != ElementKind.METHOD) {
733 final ComputedProperty cp = e.getAnnotation(ComputedProperty.class);
734 final Transitive tp = e.getAnnotation(Transitive.class);
738 if (!e.getModifiers().contains(Modifier.STATIC)) {
739 error("Method " + e.getSimpleName() + " has to be static when annotated by @ComputedProperty", e);
743 ExecutableElement ee = (ExecutableElement)e;
744 ExecutableElement write = null;
745 if (!cp.write().isEmpty()) {
746 write = findWrite(ee, (TypeElement)e.getEnclosingElement(), cp.write(), className);
749 final TypeMirror rt = ee.getReturnType();
750 final Types tu = processingEnv.getTypeUtils();
751 TypeMirror ert = tu.erasure(rt);
752 String tn = fqn(ert, ee);
753 boolean array = false;
754 final TypeMirror toCheck;
755 if (tn.equals("java.util.List")) {
757 toCheck = ((DeclaredType)rt).getTypeArguments().get(0);
762 final String sn = ee.getSimpleName().toString();
764 if (toCheck.getKind().isPrimitive()) {
767 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
768 TypeMirror enumType = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
770 if (tu.isSubtype(toCheck, stringType)) {
772 } else if (tu.isSubtype(tu.erasure(toCheck), tu.erasure(enumType))) {
774 } else if (isModel(toCheck)) {
778 tu.unboxedType(toCheck);
779 // boxed types are OK
780 } catch (IllegalArgumentException ex) {
782 error(sn + " cannot return " + toCheck, e);
787 String[] gs = toGetSet(sn, tn, array);
789 w.write(" public " + tn);
791 w.write("<" + toCheck + ">");
793 w.write(" " + gs[0] + "() {\n");
795 boolean deep = false;
796 for (VariableElement pe : ee.getParameters()) {
797 final String dn = pe.getSimpleName().toString();
799 if (!verifyPropName(pe, dn, fixedProps)) {
802 final TypeMirror pt = pe.asType();
806 final String dt = fqn(pt, ee);
807 if (dt.startsWith("java.util.List") && pt instanceof DeclaredType) {
808 final List<? extends TypeMirror> ptArgs = ((DeclaredType)pt).getTypeArguments();
809 if (ptArgs.size() == 1 && isModel(ptArgs.get(0))) {
813 String[] call = toGetSet(dn, dt, false);
814 w.write(" " + dt + " arg" + (++arg) + " = ");
815 w.write(call[0] + "();\n");
817 Collection<String[]> depends = deps.get(dn);
818 if (depends == null) {
819 depends = new LinkedHashSet<String[]>();
820 deps.put(dn, depends);
822 depends.add(new String[] { sn, gs[0] });
829 w.write(" proto.acquireLock(\"" + sn + "\");\n");
831 w.write(" proto.acquireLock();\n");
833 w.write(" return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
835 for (int i = 1; i <= arg; i++) {
841 w.write(" } finally {\n");
842 w.write(" proto.releaseLock();\n");
847 props.add(new GetSet(
848 e.getSimpleName().toString(),
855 w.write(" public void " + gs[4] + "(" + write.getParameters().get(1).asType());
856 w.write(" value) {\n");
857 w.write(" " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + write.getSimpleName() + "(this, value);\n");
860 props.add(new GetSet(
861 e.getSimpleName().toString(),
873 private static String[] toGetSet(String name, String type, boolean array) {
874 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
875 boolean clazz = "class".equals(name);
876 String pref = clazz ? "access" : "get";
877 if ("boolean".equals(type) && !array) {
881 return new String[] {
898 private String typeName(Prprt p) {
900 boolean[] isModel = { false };
901 boolean[] isEnum = { false };
902 boolean isPrimitive[] = { false };
903 ret = checkType(p, isModel, isEnum, isPrimitive);
905 String bt = findBoxedType(ret);
913 private static String findBoxedType(String ret) {
914 if (ret.equals("boolean")) {
915 return Boolean.class.getName();
917 if (ret.equals("byte")) {
918 return Byte.class.getName();
920 if (ret.equals("short")) {
921 return Short.class.getName();
923 if (ret.equals("char")) {
924 return Character.class.getName();
926 if (ret.equals("int")) {
927 return Integer.class.getName();
929 if (ret.equals("long")) {
930 return Long.class.getName();
932 if (ret.equals("float")) {
933 return Float.class.getName();
935 if (ret.equals("double")) {
936 return Double.class.getName();
941 private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
942 StringBuilder sb = new StringBuilder();
944 for (Prprt Prprt : existingProps) {
945 if (Prprt.name().equals(propName)) {
950 sb.append(Prprt.name());
955 propName + " is not one of known properties: " + sb
961 private static String findPkgName(Element e) {
963 if (e.getKind() == ElementKind.PACKAGE) {
964 return ((PackageElement)e).getQualifiedName().toString();
966 e = e.getEnclosingElement();
970 private boolean generateFunctions(
971 Element clazz, StringWriter body, String className,
972 List<? extends Element> enclosedElements, List<Object> functions
974 boolean instance = clazz.getAnnotation(Model.class).instance();
975 for (Element m : enclosedElements) {
976 if (m.getKind() != ElementKind.METHOD) {
979 ExecutableElement e = (ExecutableElement)m;
980 Function onF = e.getAnnotation(Function.class);
984 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
985 error("@OnFunction method needs to be static", e);
988 if (e.getModifiers().contains(Modifier.PRIVATE)) {
989 error("@OnFunction method cannot be private", e);
992 if (e.getReturnType().getKind() != TypeKind.VOID) {
993 error("@OnFunction method should return void", e);
996 String n = e.getSimpleName().toString();
1003 private boolean generateOnChange(Element clazz, Map<String,Collection<String[]>> propDeps,
1004 Prprt[] properties, String className,
1005 Map<String, Collection<String>> functionDeps
1007 boolean instance = clazz.getAnnotation(Model.class).instance();
1008 for (Element m : clazz.getEnclosedElements()) {
1009 if (m.getKind() != ElementKind.METHOD) {
1012 ExecutableElement e = (ExecutableElement) m;
1013 OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
1017 for (String pn : onPC.value()) {
1018 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
1019 error("No Prprt named '" + pn + "' in the model", clazz);
1023 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1024 error("@OnPrprtChange method needs to be static", e);
1027 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1028 error("@OnPrprtChange method cannot be private", e);
1031 if (e.getReturnType().getKind() != TypeKind.VOID) {
1032 error("@OnPrprtChange method should return void", e);
1035 String n = e.getSimpleName().toString();
1038 for (String pn : onPC.value()) {
1039 StringBuilder call = new StringBuilder();
1040 call.append(" ").append(inPckName(clazz, instance)).append(".").append(n).append("(");
1041 call.append(wrapPropName(e, className, "name", pn));
1042 call.append(");\n");
1044 Collection<String> change = functionDeps.get(pn);
1045 if (change == null) {
1046 change = new ArrayList<String>();
1047 functionDeps.put(pn, change);
1049 change.add(call.toString());
1050 for (String dpn : findDerivedFrom(propDeps, pn)) {
1051 change = functionDeps.get(dpn);
1052 if (change == null) {
1053 change = new ArrayList<String>();
1054 functionDeps.put(dpn, change);
1056 change.add(call.toString());
1063 private boolean generateOperation(Element clazz,
1064 StringWriter body, String className,
1065 List<? extends Element> enclosedElements,
1066 List<Object> functions
1068 boolean instance = clazz.getAnnotation(Model.class).instance();
1069 for (Element m : enclosedElements) {
1070 if (m.getKind() != ElementKind.METHOD) {
1073 ExecutableElement e = (ExecutableElement)m;
1074 ModelOperation mO = e.getAnnotation(ModelOperation.class);
1078 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1079 error("@ModelOperation method needs to be static", e);
1082 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1083 error("@ModelOperation method cannot be private", e);
1086 if (e.getReturnType().getKind() != TypeKind.VOID) {
1087 error("@ModelOperation method should return void", e);
1090 List<String> args = new ArrayList<String>();
1092 body.append(" public void ").append(m.getSimpleName()).append("(");
1094 boolean checkFirst = true;
1095 for (VariableElement ve : e.getParameters()) {
1096 final TypeMirror type = ve.asType();
1097 CharSequence simpleName;
1098 if (type.getKind() == TypeKind.DECLARED) {
1099 simpleName = ((DeclaredType)type).asElement().getSimpleName();
1101 simpleName = type.toString();
1103 if (checkFirst && simpleName.toString().equals(className)) {
1107 error("First parameter of @ModelOperation method must be " + className, m);
1110 args.add(ve.getSimpleName().toString());
1111 body.append(sep).append("final ");
1112 body.append(ve.asType().toString()).append(" ");
1113 body.append(ve.toString());
1117 body.append(") {\n");
1118 int idx = functions.size() / 2;
1119 functions.add(m.getSimpleName().toString());
1120 body.append(" proto.runInBrowser(" + idx);
1121 for (String s : args) {
1122 body.append(", ").append(s);
1124 body.append(");\n");
1125 body.append(" }\n");
1127 StringBuilder call = new StringBuilder();
1128 call.append("{ Object[] arr = (Object[])data; ");
1129 call.append(inPckName(clazz, true)).append(".").append(m.getSimpleName()).append("(");
1131 for (VariableElement ve : e.getParameters()) {
1133 call.append("model");
1136 String type = ve.asType().toString();
1137 String boxedType = findBoxedType(type);
1138 if (boxedType != null) {
1141 call.append(", ").append("(").append(type).append(")arr[").append(i - 2).append("]");
1143 call.append("); }");
1144 functions.add(call.toString());
1152 private boolean generateReceive(
1153 Element clazz, StringWriter body, String className,
1154 List<? extends Element> enclosedElements, StringBuilder inType
1156 boolean ret = generateReceiveImpl(clazz, body, className, enclosedElements, inType);
1158 inType.setLength(0);
1162 private boolean generateReceiveImpl(
1163 Element clazz, StringWriter body, String className,
1164 List<? extends Element> enclosedElements, StringBuilder inType
1166 inType.append(" @Override public void onMessage(").append(className).append(" model, int index, int type, Object data, Object[] params) {\n");
1167 inType.append(" switch (index) {\n");
1170 boolean instance = clazz.getAnnotation(Model.class).instance();
1171 for (Element m : enclosedElements) {
1172 if (m.getKind() != ElementKind.METHOD) {
1175 ExecutableElement e = (ExecutableElement)m;
1176 OnReceive onR = e.getAnnotation(OnReceive.class);
1180 if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
1181 error("@OnReceive method needs to be static", e);
1184 if (e.getModifiers().contains(Modifier.PRIVATE)) {
1185 error("@OnReceive method cannot be private", e);
1188 if (e.getReturnType().getKind() != TypeKind.VOID) {
1189 error("@OnReceive method should return void", e);
1192 if (!onR.jsonp().isEmpty() && !"GET".equals(onR.method())) {
1193 error("JSONP works only with GET transport method", e);
1195 String dataMirror = findDataSpecified(e, onR);
1196 if ("PUT".equals(onR.method()) && dataMirror == null) {
1197 error("PUT method needs to specify a data() class", e);
1200 if ("POST".equals(onR.method()) && dataMirror == null) {
1201 error("POST method needs to specify a data() class", e);
1204 if (e.getParameters().size() < 2) {
1205 error("@OnReceive method needs at least two parameters", e);
1207 final boolean isWebSocket = "WebSocket".equals(onR.method());
1208 if (isWebSocket && dataMirror == null) {
1209 error("WebSocket method needs to specify a data() class", e);
1211 int expectsList = 0;
1212 List<String> args = new ArrayList<String>();
1213 List<String> params = new ArrayList<String>();
1214 // first argument is model class
1216 TypeMirror type = e.getParameters().get(0).asType();
1217 CharSequence simpleName;
1218 if (type.getKind() == TypeKind.DECLARED) {
1219 simpleName = ((DeclaredType) type).asElement().getSimpleName();
1221 simpleName = type.toString();
1223 if (simpleName.toString().equals(className)) {
1226 error("First parameter needs to be " + className, e);
1233 final Types tu = processingEnv.getTypeUtils();
1234 TypeMirror type = e.getParameters().get(1).asType();
1235 TypeMirror modelType = null;
1236 TypeMirror ert = tu.erasure(type);
1238 if (isModel(type)) {
1240 } else if (type.getKind() == TypeKind.ARRAY) {
1241 modelType = ((ArrayType)type).getComponentType();
1243 } else if ("java.util.List".equals(fqn(ert, e))) {
1244 List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments();
1245 if (typeArgs.size() == 1) {
1246 modelType = typeArgs.get(0);
1249 } else if (type.toString().equals("java.lang.String")) {
1252 if (modelType == null) {
1253 error("Second arguments needs to be a model, String or array or List of models", e);
1256 modelClass = modelType.toString();
1257 if (expectsList == 1) {
1259 } else if (expectsList == 2) {
1260 args.add("java.util.Arrays.asList(arr)");
1265 String n = e.getSimpleName().toString();
1267 body.append(" /** Performs WebSocket communication. Call with <code>null</code> data parameter\n");
1268 body.append(" * to open the connection (even if not required). Call with non-null data to\n");
1269 body.append(" * send messages to server. Call again with <code>null</code> data to close the socket.\n");
1270 body.append(" */\n");
1271 if (onR.headers().length > 0) {
1272 error("WebSocket spec does not support headers", e);
1275 body.append(" public void ").append(n).append("(");
1276 StringBuilder urlBefore = new StringBuilder();
1277 StringBuilder urlAfter = new StringBuilder();
1278 StringBuilder headers = new StringBuilder();
1279 String jsonpVarName = null;
1282 boolean skipJSONP = onR.jsonp().isEmpty();
1283 Set<String> receiveParams = new LinkedHashSet<String>();
1284 findParamNames(receiveParams, e, onR.url(), onR.jsonp(), urlBefore, urlAfter);
1285 for (String headerLine : onR.headers()) {
1286 if (headerLine.contains("\r") || headerLine.contains("\n")) {
1287 error("Header line cannot contain line separator", e);
1289 findParamNames(receiveParams, e, headerLine, null, headers);
1290 headers.append("+ \"\\r\\n\" +\n");
1292 if (headers.length() > 0) {
1293 headers.append("\"\"");
1295 for (String p : receiveParams) {
1296 if (!skipJSONP && p.equals(onR.jsonp())) {
1302 body.append("String ").append(p);
1307 "Name of jsonp attribute ('" + onR.jsonp() +
1308 "') is not used in url attribute '" + onR.url() + "'", e
1311 if (dataMirror != null) {
1312 body.append(sep).append(dataMirror.toString()).append(" data");
1314 for (int i = 2; i < e.getParameters().size(); i++) {
1316 error("@OnReceive(method=\"WebSocket\") can only have two arguments", e);
1320 VariableElement ve = e.getParameters().get(i);
1321 body.append(sep).append(ve.asType().toString()).append(" ").append(ve.getSimpleName());
1322 final String tp = ve.asType().toString();
1323 String btn = findBoxedType(tp);
1327 args.add("(" + btn + ")params[" + (i - 2) + "]");
1328 params.add(ve.getSimpleName().toString());
1332 body.append(") {\n");
1333 boolean webSocket = onR.method().equals("WebSocket");
1335 if (generateWSReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1338 body.append(" }\n");
1339 body.append(" private Object ws_" + e.getSimpleName() + ";\n");
1341 if (generateJSONReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
1344 body.append(" }\n");
1347 inType.append(" }\n");
1348 inType.append(" throw new UnsupportedOperationException(\"index: \" + index + \" type: \" + type);\n");
1349 inType.append(" }\n");
1353 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) {
1354 boolean error = false;
1356 " case " + index + ": {\n" +
1357 " if (type == 2) { /* on error */\n" +
1358 " Exception ex = (Exception)data;\n"
1360 if (onR.onError().isEmpty()) {
1362 " ex.printStackTrace();\n"
1365 error = !findOnError(e, ((TypeElement)clazz), onR.onError(), className);
1366 body.append(" ").append(clazz.getSimpleName()).append(".").append(onR.onError()).append("(");
1367 body.append("model, ex);\n");
1371 " } else if (type == 1) {\n" +
1372 " Object[] ev = (Object[])data;\n"
1376 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1380 " " + modelClass + "[] arr = { null };\n"
1384 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1387 body.append(" ").append(clazz.getSimpleName()).append(".").append(n).append("(");
1389 for (String arg : args) {
1394 body.append(");\n");
1401 method.append(" proto.loadJSONWithHeaders(" + index + ",\n ");
1402 method.append(headers.length() == 0 ? "null" : headers).append(",\n ");
1403 method.append(urlBefore).append(", ");
1404 if (jsonpVarName != null) {
1405 method.append(urlAfter);
1407 method.append("null");
1409 if (!"GET".equals(onR.method()) || dataMirror != null) {
1410 method.append(", \"").append(onR.method()).append('"');
1411 if (dataMirror != null) {
1412 method.append(", data");
1414 method.append(", null");
1417 method.append(", null, null");
1419 for (String a : params) {
1420 method.append(", ").append(a);
1422 method.append(");\n");
1426 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) {
1428 " case " + index + ": {\n" +
1429 " if (type == 0) { /* on open */\n" +
1430 " ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1433 for (String arg : args) {
1435 if (arg.startsWith("arr") || arg.startsWith("java.util.Array")) {
1436 body.append("null");
1443 body.append(");\n");
1446 " } else if (type == 2) { /* on error */\n" +
1447 " Exception value = (Exception)data;\n"
1449 if (onR.onError().isEmpty()) {
1451 " value.printStackTrace();\n"
1454 if (!findOnError(e, ((TypeElement)clazz), onR.onError(), className)) {
1457 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1458 body.append("model, value);\n");
1462 " } else if (type == 1) {\n" +
1463 " Object[] ev = (Object[])data;\n"
1467 " " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
1471 " " + modelClass + "[] arr = { null };\n"
1475 " TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
1478 body.append(" ").append(inPckName(clazz, true)).append(".").append(n).append("(");
1480 for (String arg : args) {
1485 body.append(");\n");
1491 if (!onR.onError().isEmpty()) {
1492 body.append(" else if (type == 3) { /* on close */\n");
1493 body.append(" ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
1494 body.append("model, null);\n");
1501 body.append(" }\n");
1502 method.append(" if (this.ws_").append(e.getSimpleName()).append(" == null) {\n");
1503 method.append(" this.ws_").append(e.getSimpleName());
1504 method.append("= proto.wsOpen(" + index + ", ");
1505 method.append(urlBefore).append(", data);\n");
1506 method.append(" } else {\n");
1507 method.append(" proto.wsSend(this.ws_").append(e.getSimpleName()).append(", ").append(urlBefore).append(", data");
1508 for (String a : params) {
1509 method.append(", ").append(a);
1511 method.append(");\n");
1512 method.append(" }\n");
1516 private CharSequence wrapParams(
1517 ExecutableElement ee, String id, String className, String classRef, String evName, String dataName
1519 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1520 StringBuilder params = new StringBuilder();
1521 boolean first = true;
1522 for (VariableElement ve : ee.getParameters()) {
1524 params.append(", ");
1527 String toCall = null;
1528 String toFinish = null;
1529 boolean addNull = true;
1530 if (ve.asType() == stringType) {
1531 if (ve.getSimpleName().contentEquals("id")) {
1532 params.append('"').append(id).append('"');
1535 toCall = classRef + ".proto.toString(";
1537 if (ve.asType().getKind() == TypeKind.DOUBLE) {
1538 toCall = classRef + ".proto.toNumber(";
1539 toFinish = ".doubleValue()";
1541 if (ve.asType().getKind() == TypeKind.FLOAT) {
1542 toCall = classRef + ".proto.toNumber(";
1543 toFinish = ".floatValue()";
1545 if (ve.asType().getKind() == TypeKind.INT) {
1546 toCall = classRef + ".proto.toNumber(";
1547 toFinish = ".intValue()";
1549 if (ve.asType().getKind() == TypeKind.BYTE) {
1550 toCall = classRef + ".proto.toNumber(";
1551 toFinish = ".byteValue()";
1553 if (ve.asType().getKind() == TypeKind.SHORT) {
1554 toCall = classRef + ".proto.toNumber(";
1555 toFinish = ".shortValue()";
1557 if (ve.asType().getKind() == TypeKind.LONG) {
1558 toCall = classRef + ".proto.toNumber(";
1559 toFinish = ".longValue()";
1561 if (ve.asType().getKind() == TypeKind.BOOLEAN) {
1562 toCall = "\"true\".equals(" + classRef + ".proto.toString(";
1565 if (ve.asType().getKind() == TypeKind.CHAR) {
1566 toCall = "(char)" + classRef + ".proto.toNumber(";
1567 toFinish = ".intValue()";
1569 if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
1570 toCall = classRef + ".proto.toModel(" + ve.asType() + ".class, ";
1574 if (toCall != null) {
1575 params.append(toCall);
1576 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
1577 params.append(dataName);
1579 params.append(", null");
1582 if (evName == null) {
1583 final StringBuilder sb = new StringBuilder();
1584 sb.append("Unexpected string parameter name.");
1585 if (dataName != null) {
1586 sb.append(" Try \"").append(dataName).append("\"");
1588 error(sb.toString(), ee);
1590 params.append(evName);
1591 params.append(", \"");
1592 params.append(ve.getSimpleName().toString());
1593 params.append("\"");
1596 if (toFinish != null) {
1597 params.append(toFinish);
1601 String rn = fqn(ve.asType(), ee);
1602 int last = rn.lastIndexOf('.');
1604 rn = rn.substring(last + 1);
1606 if (rn.equals(className)) {
1607 params.append(classRef);
1610 StringBuilder err = new StringBuilder();
1611 err.append("Argument ").
1612 append(ve.getSimpleName()).
1613 append(" is not valid. The annotated method can only accept ").
1615 append(" argument");
1616 if (dataName != null) {
1617 err.append(" or argument named '").append(dataName).append("'");
1620 error(err.toString(), ee);
1626 private CharSequence wrapPropName(
1627 ExecutableElement ee, String className, String propName, String propValue
1629 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
1630 StringBuilder params = new StringBuilder();
1631 boolean first = true;
1632 for (VariableElement ve : ee.getParameters()) {
1634 params.append(", ");
1637 if (ve.asType() == stringType) {
1638 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
1639 params.append('"').append(propValue).append('"');
1641 error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
1645 String rn = fqn(ve.asType(), ee);
1646 int last = rn.lastIndexOf('.');
1648 rn = rn.substring(last + 1);
1650 if (rn.equals(className)) {
1651 params.append("model");
1655 "@OnPrprtChange method can only accept String or " + className + " arguments",
1661 private boolean isModel(TypeMirror tm) {
1662 if (tm.getKind() == TypeKind.ERROR) {
1665 final Element e = processingEnv.getTypeUtils().asElement(tm);
1669 for (Element ch : e.getEnclosedElements()) {
1670 if (ch.getKind() == ElementKind.METHOD) {
1671 ExecutableElement ee = (ExecutableElement)ch;
1672 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
1677 return models.values().contains(e.getSimpleName().toString());
1680 private void writeToString(Prprt[] props, Writer w) throws IOException {
1681 w.write(" public String toString() {\n");
1682 w.write(" StringBuilder sb = new StringBuilder();\n");
1683 w.write(" sb.append('{');\n");
1685 for (Prprt p : props) {
1687 w.append(" sb.append('\"').append(\"" + p.name() + "\")");
1688 w.append(".append('\"').append(\":\");\n");
1689 w.append(" sb.append(TYPE.toJSON(prop_");
1690 w.append(p.name()).append("));\n");
1691 sep = " sb.append(',');\n";
1693 w.write(" sb.append('}');\n");
1694 w.write(" return sb.toString();\n");
1697 private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
1698 w.write(" public " + className + " clone() {\n");
1699 w.write(" return clone(proto.getContext());\n");
1701 w.write(" private " + className + " clone(net.java.html.BrwsrCtx ctx) {\n");
1702 w.write(" " + className + " ret = new " + className + "(ctx);\n");
1703 for (Prprt p : props) {
1704 String tn = typeName(p);
1705 String[] gs = toGetSet(p.name(), tn, p.array());
1707 boolean isModel[] = { false };
1708 boolean isEnum[] = { false };
1709 boolean isPrimitive[] = { false };
1710 checkType(p, isModel, isEnum, isPrimitive);
1712 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "();\n");
1715 w.write(" ret.prop_" + p.name() + " = " + gs[0] + "() == null ? null : prop_" + p.name() + ".clone();\n");
1717 w.write(" proto.cloneList(ret." + gs[0] + "(), ctx, prop_" + p.name() + ");\n");
1721 w.write(" return ret;\n");
1725 private String inPckName(Element e, boolean preferInstance) {
1726 if (preferInstance && e.getAnnotation(Model.class).instance()) {
1727 return "model.instance";
1729 StringBuilder sb = new StringBuilder();
1730 while (e.getKind() != ElementKind.PACKAGE) {
1731 if (sb.length() == 0) {
1732 sb.append(e.getSimpleName());
1735 sb.insert(0, e.getSimpleName());
1737 e = e.getEnclosingElement();
1739 return sb.toString();
1742 private String fqn(TypeMirror pt, Element relative) {
1743 if (pt.getKind() == TypeKind.ERROR) {
1744 final Elements eu = processingEnv.getElementUtils();
1745 PackageElement pckg = eu.getPackageOf(relative);
1746 return pckg.getQualifiedName() + "." + pt.toString();
1748 return pt.toString();
1751 private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
1754 String ret = p.typeName(processingEnv);
1755 TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
1759 isPrimitive[0] = false;
1763 } catch (MirroredTypeException ex) {
1764 tm = ex.getTypeMirror();
1766 tm = processingEnv.getTypeUtils().erasure(tm);
1767 if (isPrimitive[0] = tm.getKind().isPrimitive()) {
1770 return tm.toString();
1772 final Element e = processingEnv.getTypeUtils().asElement(tm);
1773 if (e.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1776 return e.getSimpleName().toString();
1779 final Model m = e == null ? null : e.getAnnotation(Model.class);
1782 ret = findPkgName(e) + '.' + m.className();
1784 models.put(e, m.className());
1785 } else if (findModelForMthd(e)) {
1786 ret = ((TypeElement)e).getQualifiedName().toString();
1789 ret = tm.toString();
1791 TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
1792 enm = processingEnv.getTypeUtils().erasure(enm);
1793 isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
1797 private static boolean findModelForMthd(Element clazz) {
1798 if (clazz == null) {
1801 for (Element e : clazz.getEnclosedElements()) {
1802 if (e.getKind() == ElementKind.METHOD) {
1803 ExecutableElement ee = (ExecutableElement)e;
1805 ee.getSimpleName().contentEquals("modelFor") &&
1806 ee.getParameters().isEmpty()
1815 private void findParamNames(
1816 Set<String> params, Element e, String url, String jsonParam, StringBuilder... both
1820 for (int pos = 0; ;) {
1821 int next = url.indexOf('{', pos);
1823 both[wasJSON].append('"')
1824 .append(url.substring(pos).replace("\"", "\\\""))
1828 int close = url.indexOf('}', next);
1830 error("Unbalanced '{' and '}' in " + url, e);
1833 final String paramName = url.substring(next + 1, close);
1834 params.add(paramName);
1835 if (paramName.equals(jsonParam) && !jsonParam.isEmpty()) {
1836 both[wasJSON].append('"')
1837 .append(url.substring(pos, next).replace("\"", "\\\""))
1841 both[wasJSON].append('"')
1842 .append(url.substring(pos, next).replace("\"", "\\\""))
1843 .append("\" + ").append(paramName).append(" + ");
1849 private static Prprt findPrprt(Prprt[] properties, String propName) {
1850 for (Prprt p : properties) {
1851 if (propName.equals(p.name())) {
1858 private boolean isPrimitive(String type) {
1860 "int".equals(type) ||
1861 "double".equals(type) ||
1862 "long".equals(type) ||
1863 "short".equals(type) ||
1864 "byte".equals(type) ||
1865 "char".equals(type) ||
1866 "boolean".equals(type) ||
1867 "float".equals(type);
1870 private static Collection<String> findDerivedFrom(Map<String, Collection<String[]>> propsDeps, String derivedProp) {
1871 Set<String> names = new HashSet<String>();
1872 for (Map.Entry<String, Collection<String[]>> e : propsDeps.entrySet()) {
1873 for (String[] pair : e.getValue()) {
1874 if (pair[0].equals(derivedProp)) {
1875 names.add(e.getKey());
1883 private Prprt[] createProps(Element e, Property[] arr) {
1884 Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
1885 Prprt[] prev = verify.put(e, ret);
1887 error("Two sets of properties for ", e);
1892 private static String strip(String s) {
1893 int indx = s.indexOf("__");
1895 return s.substring(0, indx);
1901 private String findDataSpecified(ExecutableElement e, OnReceive onR) {
1903 return onR.data().getName();
1904 } catch (MirroredTypeException ex) {
1905 final TypeMirror tm = ex.getTypeMirror();
1907 final Element te = processingEnv.getTypeUtils().asElement(tm);
1908 if (te.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
1909 name = te.getSimpleName().toString();
1911 name = tm.toString();
1913 return "java.lang.Object".equals(name) ? null : name;
1914 } catch (Exception ex) {
1918 AnnotationMirror found = null;
1919 for (AnnotationMirror am : e.getAnnotationMirrors()) {
1920 if (am.getAnnotationType().toString().equals(OnReceive.class.getName())) {
1924 if (found == null) {
1928 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : found.getElementValues().entrySet()) {
1929 ExecutableElement ee = entry.getKey();
1930 AnnotationValue av = entry.getValue();
1931 if (ee.getSimpleName().contentEquals("data")) {
1932 List<? extends Object> values = getAnnoValues(processingEnv, e, found);
1933 for (Object v : values) {
1934 String sv = v.toString();
1935 if (sv.startsWith("data = ") && sv.endsWith(".class")) {
1936 return sv.substring(7, sv.length() - 6);
1945 static List<? extends Object> getAnnoValues(ProcessingEnvironment pe, Element e, AnnotationMirror am) {
1947 Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
1948 Method m = trees.getMethod("instance", ProcessingEnvironment.class);
1949 Object instance = m.invoke(null, pe);
1950 m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
1951 Object path = m.invoke(instance, e, am);
1952 m = path.getClass().getMethod("getLeaf");
1953 Object leaf = m.invoke(path);
1954 m = leaf.getClass().getMethod("getArguments");
1955 return (List) m.invoke(leaf);
1956 } catch (Exception ex) {
1957 return Collections.emptyList();
1961 private static String findTargetId(Element e) {
1962 for (AnnotationMirror m : e.getAnnotationMirrors()) {
1963 if (m.getAnnotationType().toString().equals(Model.class.getName())) {
1964 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entrySet : m.getElementValues().entrySet()) {
1965 ExecutableElement key = entrySet.getKey();
1966 AnnotationValue value = entrySet.getValue();
1967 if ("targetId()".equals(key.toString())) {
1968 return value.toString();
1976 private static class Prprt {
1977 private final Element e;
1978 private final AnnotationMirror tm;
1979 private final Property p;
1981 public Prprt(Element e, AnnotationMirror tm, Property p) {
1995 String typeName(ProcessingEnvironment env) {
1996 RuntimeException ex;
1998 return p.type().getName();
1999 } catch (IncompleteAnnotationException e) {
2001 } catch (AnnotationTypeMismatchException e) {
2004 for (Object v : getAnnoValues(env, e, tm)) {
2005 String s = v.toString().replace(" ", "");
2006 if (s.startsWith("type=") && s.endsWith(".class")) {
2007 return s.substring(5, s.length() - 6);
2014 static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
2015 if (arr.length == 0) {
2016 return new Prprt[0];
2019 if (e.getKind() != ElementKind.CLASS) {
2020 throw new IllegalStateException("" + e.getKind());
2022 TypeElement te = (TypeElement)e;
2023 List<? extends AnnotationValue> val = null;
2024 for (AnnotationMirror an : te.getAnnotationMirrors()) {
2025 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
2026 if (entry.getKey().getSimpleName().contentEquals("properties")) {
2027 val = (List)entry.getValue().getValue();
2032 if (val == null || val.size() != arr.length) {
2033 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
2034 return new Prprt[0];
2036 Prprt[] ret = new Prprt[arr.length];
2037 BIG: for (int i = 0; i < ret.length; i++) {
2038 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
2039 ret[i] = new Prprt(e, am, arr[i]);
2046 private static final class GetSet {
2048 final String getter;
2049 final String setter;
2051 final boolean readOnly;
2052 GetSet(String name, String getter, String setter, String type, boolean readOnly) {
2054 this.getter = getter;
2055 this.setter = setter;
2057 this.readOnly = readOnly;
2062 public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
2063 final Level l = Level.FINE;
2064 LOG.log(l, " element: {0}", element);
2065 LOG.log(l, " annotation: {0}", annotation);
2066 LOG.log(l, " member: {0}", member);
2067 LOG.log(l, " userText: {0}", userText);
2068 LOG.log(l, "str: {0}", annotation.getAnnotationType().toString());
2069 if (annotation.getAnnotationType().toString().equals(OnReceive.class.getName())) {
2070 if (member.getSimpleName().contentEquals("method")) {
2071 return Arrays.asList(
2077 methodOf("WebSocket")
2082 return super.getCompletions(element, annotation, member, userText);
2085 private static final Completion methodOf(String method) {
2086 ResourceBundle rb = ResourceBundle.getBundle("org.netbeans.html.json.impl.Bundle");
2087 return Completions.of('"' + method + '"', rb.getString("MSG_Completion_" + method));
2090 private boolean findOnError(ExecutableElement errElem, TypeElement te, String name, String className) {
2093 for (Element e : te.getEnclosedElements()) {
2094 if (e.getKind() != ElementKind.METHOD) {
2097 if (!e.getSimpleName().contentEquals(name)) {
2100 if (!e.getModifiers().contains(Modifier.STATIC)) {
2101 errElem = (ExecutableElement) e;
2102 err = "Would have to be static";
2105 ExecutableElement ee = (ExecutableElement) e;
2106 TypeMirror excType = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
2107 final List<? extends VariableElement> params = ee.getParameters();
2108 boolean error = false;
2109 if (params.size() != 2) {
2112 String firstType = params.get(0).asType().toString();
2113 int lastDot = firstType.lastIndexOf('.');
2114 if (lastDot != -1) {
2115 firstType = firstType.substring(lastDot + 1);
2117 if (!firstType.equals(className)) {
2120 if (!processingEnv.getTypeUtils().isAssignable(excType, params.get(1).asType())) {
2125 errElem = (ExecutableElement) e;
2126 err = "Error method first argument needs to be " + className + " and second Exception";
2132 err = "Cannot find " + name + "(" + className + ", Exception) method in this class";
2134 error(err, errElem);
2138 private ExecutableElement findWrite(ExecutableElement computedPropElem, TypeElement te, String name, String className) {
2141 for (Element e : te.getEnclosedElements()) {
2142 if (e.getKind() != ElementKind.METHOD) {
2145 if (!e.getSimpleName().contentEquals(name)) {
2148 if (e.equals(computedPropElem)) {
2151 if (!e.getModifiers().contains(Modifier.STATIC)) {
2152 computedPropElem = (ExecutableElement) e;
2153 err = "Would have to be static";
2156 ExecutableElement ee = (ExecutableElement) e;
2157 if (ee.getReturnType().getKind() != TypeKind.VOID) {
2158 computedPropElem = (ExecutableElement) e;
2159 err = "Write method has to return void";
2162 TypeMirror retType = computedPropElem.getReturnType();
2163 final List<? extends VariableElement> params = ee.getParameters();
2164 boolean error = false;
2165 if (params.size() != 2) {
2168 String firstType = params.get(0).asType().toString();
2169 int lastDot = firstType.lastIndexOf('.');
2170 if (lastDot != -1) {
2171 firstType = firstType.substring(lastDot + 1);
2173 if (!firstType.equals(className)) {
2176 if (!processingEnv.getTypeUtils().isAssignable(retType, params.get(1).asType())) {
2181 computedPropElem = (ExecutableElement) e;
2182 err = "Write method first argument needs to be " + className + " and second " + retType + " or Object";
2188 err = "Cannot find " + name + "(" + className + ", value) method in this class";
2190 error(err, computedPropElem);