json/src/main/java/org/netbeans/html/json/impl/ModelProcessor.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 05 Nov 2015 23:38:18 +0100
changeset 1017 10427ce1c0ee
parent 1014 c89b9f91ed18
child 1023 4f906bde3a2e
child 1026 cda94194f901
permissions -rw-r--r--
#250611: Builder style properties
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     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]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    31  *
    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.
    42  */
    43 package org.netbeans.html.json.impl;
    44 
    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;
    60 import java.util.Map;
    61 import java.util.ResourceBundle;
    62 import java.util.Set;
    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;
   101 
   102 /** Annotation processor to process {@link Model @Model} annotations and
   103  * generate appropriate model classes.
   104  *
   105  * @author Jaroslav Tulach
   106  */
   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"
   117 })
   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[]>();
   122     @Override
   123     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   124         boolean ok = true;
   125         for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
   126             if (!processModel(e)) {
   127                 ok = false;
   128             }
   129         }
   130         if (roundEnv.processingOver()) {
   131             models.clear();
   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) {
   137                     continue;
   138                 }
   139                 Prprt[] props;
   140                 Model m = finalElem.getAnnotation(Model.class);
   141                 if (m == null) {
   142                     continue;
   143                 }
   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);
   150                     if (isEnum[0]) {
   151                         continue;
   152                     }
   153                     if (isPrimitive[0]) {
   154                         continue;
   155                     }
   156                     if (isModel[0]) {
   157                         continue;
   158                     }
   159                     if ("java.lang.String".equals(t)) {
   160                         continue;
   161                     }
   162                     error("The type " + t + " should be defined by @Model annotation", entry.getKey());
   163                 }
   164             }
   165             verify.clear();
   166         }
   167         return ok;
   168     }
   169 
   170     private void error(String msg, Element e) {
   171         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e);
   172     }
   173 
   174     private boolean processModel(Element e) {
   175         boolean ok = true;
   176         Model m = e.getAnnotation(Model.class);
   177         if (m == null) {
   178             return true;
   179         }
   180         String pkg = findPkgName(e);
   181         Writer w;
   182         String className = m.className();
   183         models.put(e, className);
   184         try {
   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);
   193 
   194             if (!generateComputedProperties(className, body, props, e.getEnclosedElements(), propsGetSet, propsDeps)) {
   195                 ok = false;
   196             }
   197             if (!generateOnChange(e, propsDeps, props, className, functionDeps)) {
   198                 ok = false;
   199             }
   200             if (!generateProperties(e, builderPrefix, body, className, props, propsGetSet, propsDeps, functionDeps)) {
   201                 ok = false;
   202             }
   203             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   204                 ok = false;
   205             }
   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);
   211                         ok = false;
   212                     }
   213                 }
   214             }
   215             if (!generateReceive(e, body, className, e.getEnclosedElements(), onReceiveType)) {
   216                 ok = false;
   217             }
   218             if (!generateOperation(e, body, className, e.getEnclosedElements(), functions)) {
   219                 ok = false;
   220             }
   221             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   222             w = new OutputStreamWriter(java.openOutputStream());
   223             try {
   224                 w.append("package " + pkg + ";\n");
   225                 w.append("import net.java.html.json.*;\n");
   226                 final String inPckName = inPckName(e);
   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");
   231                 w.append("  private final org.netbeans.html.json.spi.Proto proto;\n");
   232                 w.append(body.toString());
   233                 w.append("  private ").append(className).append("(net.java.html.BrwsrCtx context) {\n");
   234                 w.append("    this.proto = TYPE.createProto(this, context);\n");
   235                 for (Prprt p : props) {
   236                     if (p.array()) {
   237                         final String tn = typeName(p);
   238                         String[] gs = toGetSet(p.name(), tn, p.array());
   239                         w.write("    this.prop_" + p.name() + " = proto.createList(\""
   240                             + p.name() + "\"");
   241                         if (functionDeps.containsKey(p.name())) {
   242                             int index = Arrays.asList(functionDeps.keySet().toArray()).indexOf(p.name());
   243                             w.write(", " + index);
   244                         } else {
   245                             w.write(", -1");
   246                         }
   247                         Collection<String[]> dependants = propsDeps.get(p.name());
   248                         if (dependants != null) {
   249                             for (String[] depProp : dependants) {
   250                                 w.write(", ");
   251                                 w.write('\"');
   252                                 w.write(depProp[0]);
   253                                 w.write('\"');
   254                             }
   255                         }
   256                         w.write(")");
   257                         w.write(";\n");
   258                     }
   259                 }
   260                 w.append("  };\n");
   261                 w.append("  public ").append(className).append("() {\n");
   262                 w.append("    this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
   263                 for (Prprt p : props) {
   264                     if (!p.array()) {
   265                         boolean[] isModel = {false};
   266                         boolean[] isEnum = {false};
   267                         boolean isPrimitive[] = {false};
   268                         String tn = checkType(p, isModel, isEnum, isPrimitive);
   269                         if (isModel[0]) {
   270                             w.write("    prop_" + p.name() + " = new " + tn + "();\n");
   271                         }
   272                     }
   273                 }
   274                 w.append("  };\n");
   275                 if (props.length > 0 && builderPrefix == null) {
   276                     StringBuilder constructorWithArguments = new StringBuilder();
   277                     constructorWithArguments.append("  public ").append(className).append("(");
   278                     Prprt firstArray = null;
   279                     String sep = "";
   280                     int parameterCount = 0;
   281                     for (Prprt p : props) {
   282                         if (p.array()) {
   283                             if (firstArray == null) {
   284                                 firstArray = p;
   285                             }
   286                             continue;
   287                         }
   288                         String tn = typeName(p);
   289                         constructorWithArguments.append(sep);
   290                         constructorWithArguments.append(tn);
   291                         String[] third = toGetSet(p.name(), tn, false);
   292                         constructorWithArguments.append(" ").append(third[2]);
   293                         sep = ", ";
   294                         parameterCount++;
   295                     }
   296                     if (firstArray != null) {
   297                         String tn;
   298                         boolean[] isModel = {false};
   299                         boolean[] isEnum = {false};
   300                         boolean isPrimitive[] = {false};
   301                         tn = checkType(firstArray, isModel, isEnum, isPrimitive);
   302                         constructorWithArguments.append(sep);
   303                         constructorWithArguments.append(tn);
   304                         String[] third = toGetSet(firstArray.name(), tn, true);
   305                         constructorWithArguments.append("... ").append(third[2]);
   306                         parameterCount++;
   307                     }
   308                     constructorWithArguments.append(") {\n");
   309                     constructorWithArguments.append("    this(net.java.html.BrwsrCtx.findDefault(").append(className).append(".class));\n");
   310                     for (Prprt p : props) {
   311                         if (p.array()) {
   312                             continue;
   313                         }
   314                         String[] third = toGetSet(p.name(), null, false);
   315                         constructorWithArguments.append("    this.prop_" + p.name() + " = " + third[2] + ";\n");
   316                     }
   317                     if (firstArray != null) {
   318                         String[] third = toGetSet(firstArray.name(), null, true);
   319                         constructorWithArguments.append("    proto.initTo(this.prop_" + firstArray.name() + ", " + third[2] + ");\n");
   320                     }
   321                     constructorWithArguments.append("  };\n");
   322                     if (parameterCount < 255) {
   323                         w.write(constructorWithArguments.toString());
   324                     }
   325                 }
   326                 w.append("  private static class Html4JavaType extends org.netbeans.html.json.spi.Proto.Type<").append(className).append("> {\n");
   327                 w.append("    private Html4JavaType() {\n      super(").append(className).append(".class, ").
   328                     append(inPckName).append(".class, " + propsGetSet.size() + ", "
   329                     + functionsCount + ");\n");
   330                 {
   331                     for (int i = 0; i < propsGetSet.size(); i++) {
   332                         w.append("      registerProperty(\"").append(propsGetSet.get(i).name).append("\", ");
   333                         w.append((i) + ", " + propsGetSet.get(i).readOnly + ");\n");
   334                     }
   335                 }
   336                 {
   337                     for (int i = 0; i < functionsCount; i++) {
   338                         w.append("      registerFunction(\"").append((String)functions.get(i * 2)).append("\", ");
   339                         w.append(i + ");\n");
   340                     }
   341                 }
   342                 w.append("    }\n");
   343                 w.append("    @Override public void setValue(" + className + " data, int type, Object value) {\n");
   344                 w.append("      switch (type) {\n");
   345                 for (int i = 0; i < propsGetSet.size(); i++) {
   346                     final GetSet pgs = propsGetSet.get(i);
   347                     if (pgs.readOnly) {
   348                         continue;
   349                     }
   350                     final String set = pgs.setter;
   351                     String tn = pgs.type;
   352                     String btn = findBoxedType(tn);
   353                     if (btn != null) {
   354                         tn = btn;
   355                     }
   356                     w.append("        case " + i + ": ");
   357                     if (pgs.setter != null) {
   358                         w.append("data.").append(strip(pgs.setter)).append("(TYPE.extractValue(" + tn + ".class, value)); return;\n");
   359                     } else {
   360                         w.append("TYPE.replaceValue(data.").append(strip(pgs.getter)).append("(), " + tn + ".class, value); return;\n");
   361                     }
   362                 }
   363                 w.append("      }\n");
   364                 w.append("      throw new UnsupportedOperationException();\n");
   365                 w.append("    }\n");
   366                 w.append("    @Override public Object getValue(" + className + " data, int type) {\n");
   367                 w.append("      switch (type) {\n");
   368                 for (int i = 0; i < propsGetSet.size(); i++) {
   369                     final String get = propsGetSet.get(i).getter;
   370                     if (get != null) {
   371                         w.append("        case " + i + ": return data." + strip(get) + "();\n");
   372                     }
   373                 }
   374                 w.append("      }\n");
   375                 w.append("      throw new UnsupportedOperationException();\n");
   376                 w.append("    }\n");
   377                 w.append("    @Override public void call(" + className + " model, int type, Object data, Object ev) throws Exception {\n");
   378                 w.append("      switch (type) {\n");
   379                 for (int i = 0; i < functions.size(); i += 2) {
   380                     final String name = (String)functions.get(i);
   381                     final Object param = functions.get(i + 1);
   382                     if (param instanceof ExecutableElement) {
   383                         ExecutableElement ee = (ExecutableElement)param;
   384                         w.append("        case " + (i / 2) + ":\n");
   385                         w.append("          ").append(((TypeElement)e).getQualifiedName()).append(".").append(name).append("(");
   386                         w.append(wrapParams(ee, null, className, "model", "ev", "data"));
   387                         w.append(");\n");
   388                         w.append("          return;\n");
   389                     } else {
   390                         String call = (String)param;
   391                         w.append("        case " + (i / 2) + ":\n"); // model." + name + "(data, ev); return;\n");
   392                         w.append("          ").append(call).append("\n");
   393                         w.append("          return;\n");
   394 
   395                     }
   396                 }
   397                 w.append("      }\n");
   398                 w.append("      throw new UnsupportedOperationException();\n");
   399                 w.append("    }\n");
   400                 w.append("    @Override public org.netbeans.html.json.spi.Proto protoFor(Object obj) {\n");
   401                 w.append("      return ((" + className + ")obj).proto;");
   402                 w.append("    }\n");
   403                 w.append("    @Override public void onChange(" + className + " model, int type) {\n");
   404                 w.append("      switch (type) {\n");
   405                 {
   406                     String[] arr = functionDeps.keySet().toArray(new String[0]);
   407                     for (int i = 0; i < arr.length; i++) {
   408                         Collection<String> onChange = functionDeps.get(arr[i]);
   409                         if (onChange != null) {
   410                             w.append("      case " + i + ":\n");
   411                             for (String call : onChange) {
   412                                 w.append("      ").append(call).append("\n");
   413                             }
   414                             w.write("      return;\n");
   415                         }
   416                     }
   417                 }
   418                 w.append("    }\n");
   419                 w.append("      throw new UnsupportedOperationException();\n");
   420                 w.append("    }\n");
   421                 w.append(onReceiveType);
   422                 w.append("    @Override public " + className + " read(net.java.html.BrwsrCtx c, Object json) { return new " + className + "(c, json); }\n");
   423                 w.append("    @Override public " + className + " cloneTo(" + className + " o, net.java.html.BrwsrCtx c) { return o.clone(c); }\n");
   424                 w.append("  }\n");
   425                 w.append("  private ").append(className).append("(net.java.html.BrwsrCtx c, Object json) {\n");
   426                 w.append("    this(c);\n");
   427                 int values = 0;
   428                 for (int i = 0; i < propsGetSet.size(); i++) {
   429                     Prprt p = findPrprt(props, propsGetSet.get(i).name);
   430                     if (p == null) {
   431                         continue;
   432                     }
   433                     values++;
   434                 }
   435                 w.append("    Object[] ret = new Object[" + values + "];\n");
   436                 w.append("    proto.extract(json, new String[] {\n");
   437                 for (int i = 0; i < propsGetSet.size(); i++) {
   438                     Prprt p = findPrprt(props, propsGetSet.get(i).name);
   439                     if (p == null) {
   440                         continue;
   441                     }
   442                     w.append("      \"").append(propsGetSet.get(i).name).append("\",\n");
   443                 }
   444                 w.append("    }, ret);\n");
   445                 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i++) {
   446                     final String pn = propsGetSet.get(i).name;
   447                     Prprt p = findPrprt(props, pn);
   448                     if (p == null || prop >= props.length) {
   449                         continue;
   450                     }
   451                     boolean[] isModel = { false };
   452                     boolean[] isEnum = { false };
   453                     boolean isPrimitive[] = { false };
   454                     String type = checkType(props[prop++], isModel, isEnum, isPrimitive);
   455                     if (p.array()) {
   456                         w.append("    for (Object e : useAsArray(ret[" + cnt + "])) {\n");
   457                         if (isModel[0]) {
   458                             w.append("      this.prop_").append(pn).append(".add(proto.read");
   459                             w.append("(" + type + ".class, e));\n");
   460                         } else if (isEnum[0]) {
   461                             w.append("        this.prop_").append(pn);
   462                             w.append(".add(e == null ? null : ");
   463                             w.append(type).append(".valueOf(TYPE.stringValue(e)));\n");
   464                         } else {
   465                             if (isPrimitive(type)) {
   466                                 if (type.equals("char")) {
   467                                     w.append("        this.prop_").append(pn).append(".add((char)TYPE.numberValue(e).");
   468                                     w.append("intValue());\n");
   469                                 } else {
   470                                     w.append("        this.prop_").append(pn).append(".add(TYPE.numberValue(e).");
   471                                     w.append(type).append("Value());\n");
   472                                 }
   473                             } else {
   474                                 w.append("        this.prop_").append(pn).append(".add((");
   475                                 w.append(type).append(")e);\n");
   476                             }
   477                         }
   478                         w.append("    }\n");
   479                     } else {
   480                         if (isEnum[0]) {
   481                             w.append("    try {\n");
   482                             w.append("    this.prop_").append(pn);
   483                             w.append(" = ret[" + cnt + "] == null ? null : ");
   484                             w.append(type).append(".valueOf(TYPE.stringValue(ret[" + cnt + "]));\n");
   485                             w.append("    } catch (IllegalArgumentException ex) {\n");
   486                             w.append("      ex.printStackTrace();\n");
   487                             w.append("    }\n");
   488                         } else if (isPrimitive(type)) {
   489                             w.append("    this.prop_").append(pn);
   490                             w.append(" = ret[" + cnt + "] == null ? ");
   491                             if ("char".equals(type)) {
   492                                 w.append("0 : (TYPE.charValue(");
   493                             } else if ("boolean".equals(type)) {
   494                                 w.append("false : (TYPE.boolValue(");
   495                             } else {
   496                                 w.append("0 : (TYPE.numberValue(");
   497                             }
   498                             w.append("ret[" + cnt + "])).");
   499                             w.append(type).append("Value();\n");
   500                         } else if (isModel[0]) {
   501                             w.append("    this.prop_").append(pn).append(" = proto.read");
   502                             w.append("(" + type + ".class, ");
   503                             w.append("ret[" + cnt + "]);\n");
   504                         }else {
   505                             w.append("    this.prop_").append(pn);
   506                             w.append(" = (").append(type).append(')');
   507                             w.append("ret[" + cnt + "];\n");
   508                         }
   509                     }
   510                     cnt++;
   511                 }
   512                 w.append("  }\n");
   513                 w.append("  private static Object[] useAsArray(Object o) {\n");
   514                 w.append("    return o instanceof Object[] ? ((Object[])o) : o == null ? new Object[0] : new Object[] { o };\n");
   515                 w.append("  }\n");
   516                 writeToString(props, w);
   517                 writeClone(className, props, w);
   518                 String targetId = findTargetId(e);
   519                 if (targetId != null) {
   520                     w.write("  /** Activates this model instance in the current {@link \n"
   521                         + "net.java.html.json.Models#bind(java.lang.Object, net.java.html.BrwsrCtx) browser context}. \n"
   522                         + "In case of using Knockout technology, this means to \n"
   523                         + "bind JSON like data in this model instance with Knockout tags in \n"
   524                         + "the surrounding HTML page.\n"
   525                     );
   526                     if (targetId != null) {
   527                         w.write("This method binds to element '" + targetId + "' on the page\n");
   528                     }
   529                     w.write(""
   530                         + "@return <code>this</code> object\n"
   531                         + "*/\n"
   532                     );
   533                     w.write("  public " + className + " applyBindings() {\n");
   534                     w.write("    proto.applyBindings();\n");
   535     //                w.write("    proto.applyBindings(id);\n");
   536                     w.write("    return this;\n");
   537                     w.write("  }\n");
   538                 } else {
   539                     w.write("  private " + className + " applyBindings() {\n");
   540                     w.write("    throw new IllegalStateException(\"Please specify targetId=\\\"\\\" in your @Model annotation\");\n");
   541                     w.write("  }\n");
   542                 }
   543                 w.write("  public boolean equals(Object o) {\n");
   544                 w.write("    if (o == this) return true;\n");
   545                 w.write("    if (!(o instanceof " + className + ")) return false;\n");
   546                 w.write("    " + className + " p = (" + className + ")o;\n");
   547                 for (Prprt p : props) {
   548                     w.write("    if (!TYPE.isSame(prop_" + p.name() + ", p.prop_" + p.name() + ")) return false;\n");
   549                 }
   550                 w.write("    return true;\n");
   551                 w.write("  }\n");
   552                 w.write("  public int hashCode() {\n");
   553                 w.write("    int h = " + className + ".class.getName().hashCode();\n");
   554                 for (Prprt p : props) {
   555                     w.write("    h = TYPE.hashPlus(prop_" + p.name() + ", h);\n");
   556                 }
   557                 w.write("    return h;\n");
   558                 w.write("  }\n");
   559                 w.write("}\n");
   560             } finally {
   561                 w.close();
   562             }
   563         } catch (IOException ex) {
   564             error("Can't create " + className + ".java", e);
   565             return false;
   566         }
   567         return ok;
   568     }
   569 
   570     private static String findBuilderPrefix(Element e, Model m) {
   571         if (!m.builder().isEmpty()) {
   572             return m.builder();
   573         }
   574         for (AnnotationMirror am : e.getAnnotationMirrors()) {
   575             for (Map.Entry<? extends Object, ? extends Object> entry : am.getElementValues().entrySet()) {
   576                 if ("builder()".equals(entry.getKey().toString())) {
   577                     return "";
   578                 }
   579             }
   580         }
   581         return null;
   582     }
   583 
   584     private static String builderMethod(String builderPrefix, Prprt p) {
   585         if (builderPrefix.isEmpty()) {
   586             return p.name();
   587         }
   588         return builderPrefix + Character.toUpperCase(p.name().charAt(0)) + p.name().substring(1);
   589     }
   590 
   591     private boolean generateProperties(
   592         Element where, String builderPrefix,
   593         Writer w, String className, Prprt[] properties,
   594         List<GetSet> props,
   595         Map<String,Collection<String[]>> deps,
   596         Map<String,Collection<String>> functionDeps
   597     ) throws IOException {
   598         boolean ok = true;
   599         for (Prprt p : properties) {
   600             final String tn;
   601             tn = typeName(p);
   602             String[] gs = toGetSet(p.name(), tn, p.array());
   603             String castTo;
   604 
   605             if (p.array()) {
   606                 w.write("  private final java.util.List<" + tn + "> prop_" + p.name() + ";\n");
   607 
   608                 castTo = "java.util.List";
   609                 w.write("  public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   610                 w.write("    proto.accessProperty(\"" + p.name() + "\");\n");
   611                 w.write("    return prop_" + p.name() + ";\n");
   612                 w.write("  }\n");
   613                 if (builderPrefix != null) {
   614                     boolean[] isModel = {false};
   615                     boolean[] isEnum = {false};
   616                     boolean isPrimitive[] = {false};
   617                     String ret = checkType(p, isModel, isEnum, isPrimitive);
   618                     w.write("  public " + className + " " + builderMethod(builderPrefix, p) + "(" + ret + "... v) {\n");
   619                     w.write("    proto.accessProperty(\"" + p.name() + "\");\n");
   620                     w.append("   TYPE.replaceValue(prop_").append(p.name()).append(", " + tn + ".class, v);\n");
   621                     w.write("    return this;\n");
   622                     w.write("  }\n");
   623                 }
   624             } else {
   625                 castTo = tn;
   626                 boolean isModel[] = { false };
   627                 boolean isEnum[] = { false };
   628                 boolean isPrimitive[] = { false };
   629                 checkType(p, isModel, isEnum, isPrimitive);
   630                 w.write("  private " + tn + " prop_" + p.name() + ";\n");
   631                 w.write("  public " + tn + " " + gs[0] + "() {\n");
   632                 w.write("    proto.accessProperty(\"" + p.name() + "\");\n");
   633                 w.write("    return prop_" + p.name() + ";\n");
   634                 w.write("  }\n");
   635                 w.write("  public void " + gs[1] + "(" + tn + " v) {\n");
   636                 w.write("    proto.verifyUnlocked();\n");
   637                 w.write("    Object o = prop_" + p.name() + ";\n");
   638                 if (isModel[0]) {
   639                     w.write("    if (o == v) return;\n");
   640                     w.write("    prop_" + p.name() + " = v;\n");
   641                 } else {
   642                     w.write("    if (TYPE.isSame(o , v)) return;\n");
   643                     w.write("    prop_" + p.name() + " = v;\n");
   644                 }
   645                 w.write("    proto.valueHasMutated(\"" + p.name() + "\", o, v);\n");
   646                 {
   647                     Collection<String[]> dependants = deps.get(p.name());
   648                     if (dependants != null) {
   649                         for (String[] pair : dependants) {
   650                             w.write("    proto.valueHasMutated(\"" + pair[0] + "\", null, " + pair[1] + "());\n");
   651                         }
   652                     }
   653                 }
   654                 {
   655                     Collection<String> dependants = functionDeps.get(p.name());
   656                     if (dependants != null) {
   657                         w.append(className).append(" model = ").append(className).append(".this;\n");
   658                         for (String call : dependants) {
   659                             w.append("  ").append(call);
   660                         }
   661                     }
   662                 }
   663                 w.write("  }\n");
   664                 if (builderPrefix != null) {
   665                     w.write("  public " + className + " " + builderMethod(builderPrefix, p) + "(" + tn + " v) {\n");
   666                     w.write("    " + gs[1] + "(v);\n");
   667                     w.write("    return this;\n");
   668                     w.write("  }\n");
   669                 }
   670             }
   671 
   672             for (int i = 0; i < props.size(); i++) {
   673                 if (props.get(i).name.equals(p.name())) {
   674                     error("Cannot have the name " + p.name() + " defined twice", where);
   675                     ok = false;
   676                 }
   677             }
   678 
   679             props.add(new GetSet(
   680                 p.name(),
   681                 gs[0],
   682                 gs[1],
   683                 tn,
   684                 gs[3] == null && !p.array()
   685             ));
   686         }
   687         return ok;
   688     }
   689 
   690     private boolean generateComputedProperties(
   691         String className,
   692         Writer w, Prprt[] fixedProps,
   693         Collection<? extends Element> arr, Collection<GetSet> props,
   694         Map<String,Collection<String[]>> deps
   695     ) throws IOException {
   696         boolean ok = true;
   697         for (Element e : arr) {
   698             if (e.getKind() != ElementKind.METHOD) {
   699                 continue;
   700             }
   701             final ComputedProperty cp = e.getAnnotation(ComputedProperty.class);
   702             final Transitive tp = e.getAnnotation(Transitive.class);
   703             if (cp == null) {
   704                 continue;
   705             }
   706             if (!e.getModifiers().contains(Modifier.STATIC)) {
   707                 error("Method " + e.getSimpleName() + " has to be static when annotated by @ComputedProperty", e);
   708                 ok = false;
   709                 continue;
   710             }
   711             ExecutableElement ee = (ExecutableElement)e;
   712             ExecutableElement write = null;
   713             if (!cp.write().isEmpty()) {
   714                 write = findWrite(ee, (TypeElement)e.getEnclosingElement(), cp.write(), className);
   715                 ok = write != null;
   716             }
   717             final TypeMirror rt = ee.getReturnType();
   718             final Types tu = processingEnv.getTypeUtils();
   719             TypeMirror ert = tu.erasure(rt);
   720             String tn = fqn(ert, ee);
   721             boolean array = false;
   722             final TypeMirror toCheck;
   723             if (tn.equals("java.util.List")) {
   724                 array = true;
   725                 toCheck = ((DeclaredType)rt).getTypeArguments().get(0);
   726             } else {
   727                 toCheck = rt;
   728             }
   729 
   730             final String sn = ee.getSimpleName().toString();
   731 
   732             if (toCheck.getKind().isPrimitive()) {
   733                 // OK
   734             } else {
   735                 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   736                 TypeMirror enumType = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
   737 
   738                 if (tu.isSubtype(toCheck, stringType)) {
   739                     // OK
   740                 } else if (tu.isSubtype(tu.erasure(toCheck), tu.erasure(enumType))) {
   741                     // OK
   742                 } else if (isModel(toCheck)) {
   743                     // OK
   744                 } else {
   745                     try {
   746                         tu.unboxedType(toCheck);
   747                         // boxed types are OK
   748                     } catch (IllegalArgumentException ex) {
   749                         ok = false;
   750                         error(sn + " cannot return " + toCheck, e);
   751                     }
   752                 }
   753             }
   754 
   755             String[] gs = toGetSet(sn, tn, array);
   756 
   757             w.write("  public " + tn);
   758             if (array) {
   759                 w.write("<" + toCheck + ">");
   760             }
   761             w.write(" " + gs[0] + "() {\n");
   762             int arg = 0;
   763             boolean deep = false;
   764             for (VariableElement pe : ee.getParameters()) {
   765                 final String dn = pe.getSimpleName().toString();
   766 
   767                 if (!verifyPropName(pe, dn, fixedProps)) {
   768                     ok = false;
   769                 }
   770                 final TypeMirror pt = pe.asType();
   771                 if (isModel(pt)) {
   772                     deep = true;
   773                 }
   774                 final String dt = fqn(pt, ee);
   775                 if (dt.startsWith("java.util.List") && pt instanceof DeclaredType) {
   776                     final List<? extends TypeMirror> ptArgs = ((DeclaredType)pt).getTypeArguments();
   777                     if (ptArgs.size() == 1 && isModel(ptArgs.get(0))) {
   778                         deep = true;
   779                     }
   780                 }
   781                 String[] call = toGetSet(dn, dt, false);
   782                 w.write("    " + dt + " arg" + (++arg) + " = ");
   783                 w.write(call[0] + "();\n");
   784 
   785                 Collection<String[]> depends = deps.get(dn);
   786                 if (depends == null) {
   787                     depends = new LinkedHashSet<String[]>();
   788                     deps.put(dn, depends);
   789                 }
   790                 depends.add(new String[] { sn, gs[0] });
   791             }
   792             w.write("    try {\n");
   793             if (tp != null) {
   794                 deep = tp.deep();
   795             }
   796             if (deep) {
   797                 w.write("      proto.acquireLock(\"" + sn + "\");\n");
   798             } else {
   799                 w.write("      proto.acquireLock();\n");
   800             }
   801             w.write("      return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
   802             String sep = "";
   803             for (int i = 1; i <= arg; i++) {
   804                 w.write(sep);
   805                 w.write("arg" + i);
   806                 sep = ", ";
   807             }
   808             w.write(");\n");
   809             w.write("    } finally {\n");
   810             w.write("      proto.releaseLock();\n");
   811             w.write("    }\n");
   812             w.write("  }\n");
   813 
   814             if (write == null) {
   815                 props.add(new GetSet(
   816                     e.getSimpleName().toString(),
   817                     gs[0],
   818                     null,
   819                     tn,
   820                     true
   821                 ));
   822             } else {
   823                 w.write("  public void " + gs[4] + "(" + write.getParameters().get(1).asType());
   824                 w.write(" value) {\n");
   825                 w.write("    " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + write.getSimpleName() + "(this, value);\n");
   826                 w.write("  }\n");
   827 
   828                 props.add(new GetSet(
   829                     e.getSimpleName().toString(),
   830                     gs[0],
   831                     gs[4],
   832                     tn,
   833                     false
   834                 ));
   835             }
   836         }
   837 
   838         return ok;
   839     }
   840 
   841     private static String[] toGetSet(String name, String type, boolean array) {
   842         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   843         boolean clazz = "class".equals(name);
   844         String pref = clazz ? "access" : "get";
   845         if ("boolean".equals(type) && !array) {
   846             pref = "is";
   847         }
   848         if (array) {
   849             return new String[] {
   850                 pref + n,
   851                 null,
   852                 "a" + n,
   853                 null,
   854                 "set" + n
   855             };
   856         }
   857         return new String[]{
   858             pref + n,
   859             "set" + n,
   860             "a" + n,
   861             "",
   862             "set" + n
   863         };
   864     }
   865 
   866     private String typeName(Prprt p) {
   867         String ret;
   868         boolean[] isModel = { false };
   869         boolean[] isEnum = { false };
   870         boolean isPrimitive[] = { false };
   871         ret = checkType(p, isModel, isEnum, isPrimitive);
   872         if (p.array()) {
   873             String bt = findBoxedType(ret);
   874             if (bt != null) {
   875                 return bt;
   876             }
   877         }
   878         return ret;
   879     }
   880 
   881     private static String findBoxedType(String ret) {
   882         if (ret.equals("boolean")) {
   883             return Boolean.class.getName();
   884         }
   885         if (ret.equals("byte")) {
   886             return Byte.class.getName();
   887         }
   888         if (ret.equals("short")) {
   889             return Short.class.getName();
   890         }
   891         if (ret.equals("char")) {
   892             return Character.class.getName();
   893         }
   894         if (ret.equals("int")) {
   895             return Integer.class.getName();
   896         }
   897         if (ret.equals("long")) {
   898             return Long.class.getName();
   899         }
   900         if (ret.equals("float")) {
   901             return Float.class.getName();
   902         }
   903         if (ret.equals("double")) {
   904             return Double.class.getName();
   905         }
   906         return null;
   907     }
   908 
   909     private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
   910         StringBuilder sb = new StringBuilder();
   911         String sep = "";
   912         for (Prprt Prprt : existingProps) {
   913             if (Prprt.name().equals(propName)) {
   914                 return true;
   915             }
   916             sb.append(sep);
   917             sb.append('"');
   918             sb.append(Prprt.name());
   919             sb.append('"');
   920             sep = ", ";
   921         }
   922         error(
   923             propName + " is not one of known properties: " + sb
   924             , e
   925         );
   926         return false;
   927     }
   928 
   929     private static String findPkgName(Element e) {
   930         for (;;) {
   931             if (e.getKind() == ElementKind.PACKAGE) {
   932                 return ((PackageElement)e).getQualifiedName().toString();
   933             }
   934             e = e.getEnclosingElement();
   935         }
   936     }
   937 
   938     private boolean generateFunctions(
   939         Element clazz, StringWriter body, String className,
   940         List<? extends Element> enclosedElements, List<Object> functions
   941     ) {
   942         for (Element m : enclosedElements) {
   943             if (m.getKind() != ElementKind.METHOD) {
   944                 continue;
   945             }
   946             ExecutableElement e = (ExecutableElement)m;
   947             Function onF = e.getAnnotation(Function.class);
   948             if (onF == null) {
   949                 continue;
   950             }
   951             if (!e.getModifiers().contains(Modifier.STATIC)) {
   952                 error("@OnFunction method needs to be static", e);
   953                 return false;
   954             }
   955             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   956                 error("@OnFunction method cannot be private", e);
   957                 return false;
   958             }
   959             if (e.getReturnType().getKind() != TypeKind.VOID) {
   960                 error("@OnFunction method should return void", e);
   961                 return false;
   962             }
   963             String n = e.getSimpleName().toString();
   964             functions.add(n);
   965             functions.add(e);
   966         }
   967         return true;
   968     }
   969 
   970     private boolean generateOnChange(Element clazz, Map<String,Collection<String[]>> propDeps,
   971         Prprt[] properties, String className,
   972         Map<String, Collection<String>> functionDeps
   973     ) {
   974         for (Element m : clazz.getEnclosedElements()) {
   975             if (m.getKind() != ElementKind.METHOD) {
   976                 continue;
   977             }
   978             ExecutableElement e = (ExecutableElement) m;
   979             OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
   980             if (onPC == null) {
   981                 continue;
   982             }
   983             for (String pn : onPC.value()) {
   984                 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
   985                     error("No Prprt named '" + pn + "' in the model", clazz);
   986                     return false;
   987                 }
   988             }
   989             if (!e.getModifiers().contains(Modifier.STATIC)) {
   990                 error("@OnPrprtChange method needs to be static", e);
   991                 return false;
   992             }
   993             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   994                 error("@OnPrprtChange method cannot be private", e);
   995                 return false;
   996             }
   997             if (e.getReturnType().getKind() != TypeKind.VOID) {
   998                 error("@OnPrprtChange method should return void", e);
   999                 return false;
  1000             }
  1001             String n = e.getSimpleName().toString();
  1002 
  1003 
  1004             for (String pn : onPC.value()) {
  1005                 StringBuilder call = new StringBuilder();
  1006                 call.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
  1007                 call.append(wrapPropName(e, className, "name", pn));
  1008                 call.append(");\n");
  1009 
  1010                 Collection<String> change = functionDeps.get(pn);
  1011                 if (change == null) {
  1012                     change = new ArrayList<String>();
  1013                     functionDeps.put(pn, change);
  1014                 }
  1015                 change.add(call.toString());
  1016                 for (String dpn : findDerivedFrom(propDeps, pn)) {
  1017                     change = functionDeps.get(dpn);
  1018                     if (change == null) {
  1019                         change = new ArrayList<String>();
  1020                         functionDeps.put(dpn, change);
  1021                     }
  1022                     change.add(call.toString());
  1023                 }
  1024             }
  1025         }
  1026         return true;
  1027     }
  1028 
  1029     private boolean generateOperation(Element clazz,
  1030         StringWriter body, String className,
  1031         List<? extends Element> enclosedElements,
  1032         List<Object> functions
  1033     ) {
  1034         for (Element m : enclosedElements) {
  1035             if (m.getKind() != ElementKind.METHOD) {
  1036                 continue;
  1037             }
  1038             ExecutableElement e = (ExecutableElement)m;
  1039             ModelOperation mO = e.getAnnotation(ModelOperation.class);
  1040             if (mO == null) {
  1041                 continue;
  1042             }
  1043             if (!e.getModifiers().contains(Modifier.STATIC)) {
  1044                 error("@ModelOperation method needs to be static", e);
  1045                 return false;
  1046             }
  1047             if (e.getModifiers().contains(Modifier.PRIVATE)) {
  1048                 error("@ModelOperation method cannot be private", e);
  1049                 return false;
  1050             }
  1051             if (e.getReturnType().getKind() != TypeKind.VOID) {
  1052                 error("@ModelOperation method should return void", e);
  1053                 return false;
  1054             }
  1055             List<String> args = new ArrayList<String>();
  1056             {
  1057                 body.append("  public void ").append(m.getSimpleName()).append("(");
  1058                 String sep = "";
  1059                 boolean checkFirst = true;
  1060                 for (VariableElement ve : e.getParameters()) {
  1061                     final TypeMirror type = ve.asType();
  1062                     CharSequence simpleName;
  1063                     if (type.getKind() == TypeKind.DECLARED) {
  1064                         simpleName = ((DeclaredType)type).asElement().getSimpleName();
  1065                     } else {
  1066                         simpleName = type.toString();
  1067                     }
  1068                     if (checkFirst && simpleName.toString().equals(className)) {
  1069                         checkFirst = false;
  1070                     } else {
  1071                         if (checkFirst) {
  1072                             error("First parameter of @ModelOperation method must be " + className, m);
  1073                             return false;
  1074                         }
  1075                         args.add(ve.getSimpleName().toString());
  1076                         body.append(sep).append("final ");
  1077                         body.append(ve.asType().toString()).append(" ");
  1078                         body.append(ve.toString());
  1079                         sep = ", ";
  1080                     }
  1081                 }
  1082                 body.append(") {\n");
  1083                 int idx = functions.size() / 2;
  1084                 functions.add(m.getSimpleName().toString());
  1085                 body.append("    proto.runInBrowser(" + idx);
  1086                 for (String s : args) {
  1087                     body.append(", ").append(s);
  1088                 }
  1089                 body.append(");\n");
  1090                 body.append("  }\n");
  1091 
  1092                 StringBuilder call = new StringBuilder();
  1093                 call.append("{ Object[] arr = (Object[])data; ");
  1094                 call.append(inPckName(clazz)).append(".").append(m.getSimpleName()).append("(");
  1095                 int i = 0;
  1096                 for (VariableElement ve : e.getParameters()) {
  1097                     if (i++ == 0) {
  1098                         call.append("model");
  1099                         continue;
  1100                     }
  1101                     String type = ve.asType().toString();
  1102                     String boxedType = findBoxedType(type);
  1103                     if (boxedType != null) {
  1104                         type = boxedType;
  1105                     }
  1106                     call.append(", ").append("(").append(type).append(")arr[").append(i - 2).append("]");
  1107                 }
  1108                 call.append("); }");
  1109                 functions.add(call.toString());
  1110             }
  1111 
  1112         }
  1113         return true;
  1114     }
  1115 
  1116 
  1117     private boolean generateReceive(
  1118         Element clazz, StringWriter body, String className,
  1119         List<? extends Element> enclosedElements, StringBuilder inType
  1120     ) {
  1121         boolean ret = generateReceiveImpl(clazz, body, className, enclosedElements, inType);
  1122         if (!ret) {
  1123             inType.setLength(0);
  1124         }
  1125         return ret;
  1126     }
  1127     private boolean generateReceiveImpl(
  1128         Element clazz, StringWriter body, String className,
  1129         List<? extends Element> enclosedElements, StringBuilder inType
  1130     ) {
  1131         inType.append("  @Override public void onMessage(").append(className).append(" model, int index, int type, Object data, Object[] params) {\n");
  1132         inType.append("    switch (index) {\n");
  1133         int index = 0;
  1134         boolean ok = true;
  1135         for (Element m : enclosedElements) {
  1136             if (m.getKind() != ElementKind.METHOD) {
  1137                 continue;
  1138             }
  1139             ExecutableElement e = (ExecutableElement)m;
  1140             OnReceive onR = e.getAnnotation(OnReceive.class);
  1141             if (onR == null) {
  1142                 continue;
  1143             }
  1144             if (!e.getModifiers().contains(Modifier.STATIC)) {
  1145                 error("@OnReceive method needs to be static", e);
  1146                 return false;
  1147             }
  1148             if (e.getModifiers().contains(Modifier.PRIVATE)) {
  1149                 error("@OnReceive method cannot be private", e);
  1150                 return false;
  1151             }
  1152             if (e.getReturnType().getKind() != TypeKind.VOID) {
  1153                 error("@OnReceive method should return void", e);
  1154                 return false;
  1155             }
  1156             if (!onR.jsonp().isEmpty() && !"GET".equals(onR.method())) {
  1157                 error("JSONP works only with GET transport method", e);
  1158             }
  1159             String dataMirror = findDataSpecified(e, onR);
  1160             if ("PUT".equals(onR.method()) && dataMirror == null) {
  1161                 error("PUT method needs to specify a data() class", e);
  1162                 return false;
  1163             }
  1164             if ("POST".equals(onR.method()) && dataMirror == null) {
  1165                 error("POST method needs to specify a data() class", e);
  1166                 return false;
  1167             }
  1168             if (e.getParameters().size() < 2) {
  1169                 error("@OnReceive method needs at least two parameters", e);
  1170             }
  1171             final boolean isWebSocket = "WebSocket".equals(onR.method());
  1172             if (isWebSocket && dataMirror == null) {
  1173                 error("WebSocket method needs to specify a data() class", e);
  1174             }
  1175             int expectsList = 0;
  1176             List<String> args = new ArrayList<String>();
  1177             List<String> params = new ArrayList<String>();
  1178             // first argument is model class
  1179             {
  1180                 TypeMirror type = e.getParameters().get(0).asType();
  1181                 CharSequence simpleName;
  1182                 if (type.getKind() == TypeKind.DECLARED) {
  1183                     simpleName = ((DeclaredType) type).asElement().getSimpleName();
  1184                 } else {
  1185                     simpleName = type.toString();
  1186                 }
  1187                 if (simpleName.toString().equals(className)) {
  1188                     args.add("model");
  1189                 } else {
  1190                     error("First parameter needs to be " + className, e);
  1191                     return false;
  1192                 }
  1193             }
  1194 
  1195             String modelClass;
  1196             {
  1197                 final Types tu = processingEnv.getTypeUtils();
  1198                 TypeMirror type = e.getParameters().get(1).asType();
  1199                 TypeMirror modelType = null;
  1200                 TypeMirror ert = tu.erasure(type);
  1201 
  1202                 if (isModel(type)) {
  1203                     modelType = type;
  1204                 } else if (type.getKind() == TypeKind.ARRAY) {
  1205                     modelType = ((ArrayType)type).getComponentType();
  1206                     expectsList = 1;
  1207                 } else if ("java.util.List".equals(fqn(ert, e))) {
  1208                     List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments();
  1209                     if (typeArgs.size() == 1) {
  1210                         modelType = typeArgs.get(0);
  1211                         expectsList = 2;
  1212                     }
  1213                 } else if (type.toString().equals("java.lang.String")) {
  1214                     modelType = type;
  1215                 }
  1216                 if (modelType == null) {
  1217                     error("Second arguments needs to be a model, String or array or List of models", e);
  1218                     return false;
  1219                 }
  1220                 modelClass = modelType.toString();
  1221                 if (expectsList == 1) {
  1222                     args.add("arr");
  1223                 } else if (expectsList == 2) {
  1224                     args.add("java.util.Arrays.asList(arr)");
  1225                 } else {
  1226                     args.add("arr[0]");
  1227                 }
  1228             }
  1229             String n = e.getSimpleName().toString();
  1230             if (isWebSocket) {
  1231                 body.append("  /** Performs WebSocket communication. Call with <code>null</code> data parameter\n");
  1232                 body.append("  * to open the connection (even if not required). Call with non-null data to\n");
  1233                 body.append("  * send messages to server. Call again with <code>null</code> data to close the socket.\n");
  1234                 body.append("  */\n");
  1235                 if (onR.headers().length > 0) {
  1236                     error("WebSocket spec does not support headers", e);
  1237                 }
  1238             }
  1239             body.append("  public void ").append(n).append("(");
  1240             StringBuilder urlBefore = new StringBuilder();
  1241             StringBuilder urlAfter = new StringBuilder();
  1242             StringBuilder headers = new StringBuilder();
  1243             String jsonpVarName = null;
  1244             {
  1245                 String sep = "";
  1246                 boolean skipJSONP = onR.jsonp().isEmpty();
  1247                 Set<String> receiveParams = new LinkedHashSet<String>();
  1248                 findParamNames(receiveParams, e, onR.url(), onR.jsonp(), urlBefore, urlAfter);
  1249                 for (String headerLine : onR.headers()) {
  1250                     if (headerLine.contains("\r") || headerLine.contains("\n")) {
  1251                         error("Header line cannot contain line separator", e);
  1252                     }
  1253                     findParamNames(receiveParams, e, headerLine, null, headers);
  1254                     headers.append("+ \"\\r\\n\" +\n");
  1255                 }
  1256                 if (headers.length() > 0) {
  1257                     headers.append("\"\"");
  1258                 }
  1259                 for (String p : receiveParams) {
  1260                     if (!skipJSONP && p.equals(onR.jsonp())) {
  1261                         skipJSONP = true;
  1262                         jsonpVarName = p;
  1263                         continue;
  1264                     }
  1265                     body.append(sep);
  1266                     body.append("String ").append(p);
  1267                     sep = ", ";
  1268                 }
  1269                 if (!skipJSONP) {
  1270                     error(
  1271                         "Name of jsonp attribute ('" + onR.jsonp() +
  1272                         "') is not used in url attribute '" + onR.url() + "'", e
  1273                     );
  1274                 }
  1275                 if (dataMirror != null) {
  1276                     body.append(sep).append(dataMirror.toString()).append(" data");
  1277                 }
  1278                 for (int i = 2; i < e.getParameters().size(); i++) {
  1279                     if (isWebSocket) {
  1280                         error("@OnReceive(method=\"WebSocket\") can only have two arguments", e);
  1281                         ok = false;
  1282                     }
  1283 
  1284                     VariableElement ve = e.getParameters().get(i);
  1285                     body.append(sep).append(ve.asType().toString()).append(" ").append(ve.getSimpleName());
  1286                     final String tp = ve.asType().toString();
  1287                     String btn = findBoxedType(tp);
  1288                     if (btn == null) {
  1289                         btn = tp;
  1290                     }
  1291                     args.add("(" + btn + ")params[" + (i - 2) + "]");
  1292                     params.add(ve.getSimpleName().toString());
  1293                     sep = ", ";
  1294                 }
  1295             }
  1296             body.append(") {\n");
  1297             boolean webSocket = onR.method().equals("WebSocket");
  1298             if (webSocket) {
  1299                 if (generateWSReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
  1300                     return false;
  1301                 }
  1302                 body.append("  }\n");
  1303                 body.append("  private Object ws_" + e.getSimpleName() + ";\n");
  1304             } else {
  1305                 if (generateJSONReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
  1306                     ok = false;
  1307                 }
  1308                 body.append("  }\n");
  1309             }
  1310         }
  1311         inType.append("    }\n");
  1312         inType.append("    throw new UnsupportedOperationException(\"index: \" + index + \" type: \" + type);\n");
  1313         inType.append("  }\n");
  1314         return ok;
  1315     }
  1316 
  1317     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) {
  1318         boolean error = false;
  1319         body.append(
  1320             "    case " + index + ": {\n" +
  1321             "      if (type == 2) { /* on error */\n" +
  1322             "        Exception ex = (Exception)data;\n"
  1323             );
  1324         if (onR.onError().isEmpty()) {
  1325             body.append(
  1326                 "        ex.printStackTrace();\n"
  1327                 );
  1328         } else {
  1329             error = !findOnError(e, ((TypeElement)clazz), onR.onError(), className);
  1330             body.append("        ").append(clazz.getSimpleName()).append(".").append(onR.onError()).append("(");
  1331             body.append("model, ex);\n");
  1332         }
  1333         body.append(
  1334             "        return;\n" +
  1335             "      } else if (type == 1) {\n" +
  1336             "        Object[] ev = (Object[])data;\n"
  1337             );
  1338         if (expectsList) {
  1339             body.append(
  1340                 "        " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
  1341                 );
  1342         } else {
  1343             body.append(
  1344                 "        " + modelClass + "[] arr = { null };\n"
  1345                 );
  1346         }
  1347         body.append(
  1348             "        TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
  1349         );
  1350         {
  1351             body.append("        ").append(clazz.getSimpleName()).append(".").append(n).append("(");
  1352             String sep = "";
  1353             for (String arg : args) {
  1354                 body.append(sep);
  1355                 body.append(arg);
  1356                 sep = ", ";
  1357             }
  1358             body.append(");\n");
  1359         }
  1360         body.append(
  1361             "        return;\n" +
  1362             "      }\n" +
  1363             "    }\n"
  1364             );
  1365         method.append("    proto.loadJSONWithHeaders(" + index + ",\n        ");
  1366         method.append(headers.length() == 0 ? "null" : headers).append(",\n        ");
  1367         method.append(urlBefore).append(", ");
  1368         if (jsonpVarName != null) {
  1369             method.append(urlAfter);
  1370         } else {
  1371             method.append("null");
  1372         }
  1373         if (!"GET".equals(onR.method()) || dataMirror != null) {
  1374             method.append(", \"").append(onR.method()).append('"');
  1375             if (dataMirror != null) {
  1376                 method.append(", data");
  1377             } else {
  1378                 method.append(", null");
  1379             }
  1380         } else {
  1381             method.append(", null, null");
  1382         }
  1383         for (String a : params) {
  1384             method.append(", ").append(a);
  1385         }
  1386         method.append(");\n");
  1387         return error;
  1388     }
  1389 
  1390     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) {
  1391         body.append(
  1392             "    case " + index + ": {\n" +
  1393             "      if (type == 0) { /* on open */\n" +
  1394             "        ").append(inPckName(clazz)).append(".").append(n).append("(");
  1395         {
  1396             String sep = "";
  1397             for (String arg : args) {
  1398                 body.append(sep);
  1399                 if (arg.startsWith("arr") || arg.startsWith("java.util.Array")) {
  1400                     body.append("null");
  1401                 } else {
  1402                     body.append(arg);
  1403                 }
  1404                 sep = ", ";
  1405             }
  1406         }
  1407         body.append(");\n");
  1408         body.append(
  1409             "        return;\n" +
  1410             "      } else if (type == 2) { /* on error */\n" +
  1411             "        Exception value = (Exception)data;\n"
  1412             );
  1413         if (onR.onError().isEmpty()) {
  1414             body.append(
  1415                 "        value.printStackTrace();\n"
  1416                 );
  1417         } else {
  1418             if (!findOnError(e, ((TypeElement)clazz), onR.onError(), className)) {
  1419                 return true;
  1420             }
  1421             body.append("        ").append(inPckName(clazz)).append(".").append(onR.onError()).append("(");
  1422             body.append("model, value);\n");
  1423         }
  1424         body.append(
  1425             "        return;\n" +
  1426             "      } else if (type == 1) {\n" +
  1427             "        Object[] ev = (Object[])data;\n"
  1428         );
  1429         if (expectsList) {
  1430             body.append(
  1431                 "        " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
  1432                 );
  1433         } else {
  1434             body.append(
  1435                 "        " + modelClass + "[] arr = { null };\n"
  1436                 );
  1437         }
  1438         body.append(
  1439             "        TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
  1440         );
  1441         {
  1442             body.append("        ").append(inPckName(clazz)).append(".").append(n).append("(");
  1443             String sep = "";
  1444             for (String arg : args) {
  1445                 body.append(sep);
  1446                 body.append(arg);
  1447                 sep = ", ";
  1448             }
  1449             body.append(");\n");
  1450         }
  1451         body.append(
  1452             "        return;\n" +
  1453             "      }"
  1454         );
  1455         if (!onR.onError().isEmpty()) {
  1456             body.append(" else if (type == 3) { /* on close */\n");
  1457             body.append("        ").append(inPckName(clazz)).append(".").append(onR.onError()).append("(");
  1458             body.append("model, null);\n");
  1459             body.append(
  1460                 "        return;" +
  1461                 "      }"
  1462             );
  1463         }
  1464         body.append("\n");
  1465         body.append("    }\n");
  1466         method.append("    if (this.ws_").append(e.getSimpleName()).append(" == null) {\n");
  1467         method.append("      this.ws_").append(e.getSimpleName());
  1468         method.append("= proto.wsOpen(" + index + ", ");
  1469         method.append(urlBefore).append(", data);\n");
  1470         method.append("    } else {\n");
  1471         method.append("      proto.wsSend(this.ws_").append(e.getSimpleName()).append(", ").append(urlBefore).append(", data");
  1472         for (String a : params) {
  1473             method.append(", ").append(a);
  1474         }
  1475         method.append(");\n");
  1476         method.append("    }\n");
  1477         return false;
  1478     }
  1479 
  1480     private CharSequence wrapParams(
  1481         ExecutableElement ee, String id, String className, String classRef, String evName, String dataName
  1482     ) {
  1483         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1484         StringBuilder params = new StringBuilder();
  1485         boolean first = true;
  1486         for (VariableElement ve : ee.getParameters()) {
  1487             if (!first) {
  1488                 params.append(", ");
  1489             }
  1490             first = false;
  1491             String toCall = null;
  1492             String toFinish = null;
  1493             boolean addNull = true;
  1494             if (ve.asType() == stringType) {
  1495                 if (ve.getSimpleName().contentEquals("id")) {
  1496                     params.append('"').append(id).append('"');
  1497                     continue;
  1498                 }
  1499                 toCall = classRef + ".proto.toString(";
  1500             }
  1501             if (ve.asType().getKind() == TypeKind.DOUBLE) {
  1502                 toCall = classRef + ".proto.toNumber(";
  1503                 toFinish = ".doubleValue()";
  1504             }
  1505             if (ve.asType().getKind() == TypeKind.FLOAT) {
  1506                 toCall = classRef + ".proto.toNumber(";
  1507                 toFinish = ".floatValue()";
  1508             }
  1509             if (ve.asType().getKind() == TypeKind.INT) {
  1510                 toCall = classRef + ".proto.toNumber(";
  1511                 toFinish = ".intValue()";
  1512             }
  1513             if (ve.asType().getKind() == TypeKind.BYTE) {
  1514                 toCall = classRef + ".proto.toNumber(";
  1515                 toFinish = ".byteValue()";
  1516             }
  1517             if (ve.asType().getKind() == TypeKind.SHORT) {
  1518                 toCall = classRef + ".proto.toNumber(";
  1519                 toFinish = ".shortValue()";
  1520             }
  1521             if (ve.asType().getKind() == TypeKind.LONG) {
  1522                 toCall = classRef + ".proto.toNumber(";
  1523                 toFinish = ".longValue()";
  1524             }
  1525             if (ve.asType().getKind() == TypeKind.BOOLEAN) {
  1526                 toCall = "\"true\".equals(" + classRef + ".proto.toString(";
  1527                 toFinish = ")";
  1528             }
  1529             if (ve.asType().getKind() == TypeKind.CHAR) {
  1530                 toCall = "(char)" + classRef + ".proto.toNumber(";
  1531                 toFinish = ".intValue()";
  1532             }
  1533             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
  1534                 toCall = classRef + ".proto.toModel(" + ve.asType() + ".class, ";
  1535                 addNull = false;
  1536             }
  1537 
  1538             if (toCall != null) {
  1539                 params.append(toCall);
  1540                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
  1541                     params.append(dataName);
  1542                     if (addNull) {
  1543                         params.append(", null");
  1544                     }
  1545                 } else {
  1546                     if (evName == null) {
  1547                         final StringBuilder sb = new StringBuilder();
  1548                         sb.append("Unexpected string parameter name.");
  1549                         if (dataName != null) {
  1550                             sb.append(" Try \"").append(dataName).append("\"");
  1551                         }
  1552                         error(sb.toString(), ee);
  1553                     }
  1554                     params.append(evName);
  1555                     params.append(", \"");
  1556                     params.append(ve.getSimpleName().toString());
  1557                     params.append("\"");
  1558                 }
  1559                 params.append(")");
  1560                 if (toFinish != null) {
  1561                     params.append(toFinish);
  1562                 }
  1563                 continue;
  1564             }
  1565             String rn = fqn(ve.asType(), ee);
  1566             int last = rn.lastIndexOf('.');
  1567             if (last >= 0) {
  1568                 rn = rn.substring(last + 1);
  1569             }
  1570             if (rn.equals(className)) {
  1571                 params.append(classRef);
  1572                 continue;
  1573             }
  1574             StringBuilder err = new StringBuilder();
  1575             err.append("Argument ").
  1576                 append(ve.getSimpleName()).
  1577                 append(" is not valid. The annotated method can only accept ").
  1578                 append(className).
  1579                 append(" argument");
  1580             if (dataName != null) {
  1581                 err.append(" or argument named '").append(dataName).append("'");
  1582             }
  1583             err.append(".");
  1584             error(err.toString(), ee);
  1585         }
  1586         return params;
  1587     }
  1588 
  1589 
  1590     private CharSequence wrapPropName(
  1591         ExecutableElement ee, String className, String propName, String propValue
  1592     ) {
  1593         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1594         StringBuilder params = new StringBuilder();
  1595         boolean first = true;
  1596         for (VariableElement ve : ee.getParameters()) {
  1597             if (!first) {
  1598                 params.append(", ");
  1599             }
  1600             first = false;
  1601             if (ve.asType() == stringType) {
  1602                 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
  1603                     params.append('"').append(propValue).append('"');
  1604                 } else {
  1605                     error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
  1606                 }
  1607                 continue;
  1608             }
  1609             String rn = fqn(ve.asType(), ee);
  1610             int last = rn.lastIndexOf('.');
  1611             if (last >= 0) {
  1612                 rn = rn.substring(last + 1);
  1613             }
  1614             if (rn.equals(className)) {
  1615                 params.append("model");
  1616                 continue;
  1617             }
  1618             error(
  1619                 "@OnPrprtChange method can only accept String or " + className + " arguments",
  1620                 ee);
  1621         }
  1622         return params;
  1623     }
  1624 
  1625     private boolean isModel(TypeMirror tm) {
  1626         if (tm.getKind() == TypeKind.ERROR) {
  1627             return true;
  1628         }
  1629         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1630         if (e == null) {
  1631             return false;
  1632         }
  1633         for (Element ch : e.getEnclosedElements()) {
  1634             if (ch.getKind() == ElementKind.METHOD) {
  1635                 ExecutableElement ee = (ExecutableElement)ch;
  1636                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
  1637                     return true;
  1638                 }
  1639             }
  1640         }
  1641         return models.values().contains(e.getSimpleName().toString());
  1642     }
  1643 
  1644     private void writeToString(Prprt[] props, Writer w) throws IOException {
  1645         w.write("  public String toString() {\n");
  1646         w.write("    StringBuilder sb = new StringBuilder();\n");
  1647         w.write("    sb.append('{');\n");
  1648         String sep = "";
  1649         for (Prprt p : props) {
  1650             w.write(sep);
  1651             w.append("    sb.append('\"').append(\"" + p.name() + "\")");
  1652                 w.append(".append('\"').append(\":\");\n");
  1653             w.append("    sb.append(TYPE.toJSON(prop_");
  1654             w.append(p.name()).append("));\n");
  1655             sep =    "    sb.append(',');\n";
  1656         }
  1657         w.write("    sb.append('}');\n");
  1658         w.write("    return sb.toString();\n");
  1659         w.write("  }\n");
  1660     }
  1661     private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
  1662         w.write("  public " + className + " clone() {\n");
  1663         w.write("    return clone(proto.getContext());\n");
  1664         w.write("  }\n");
  1665         w.write("  private " + className + " clone(net.java.html.BrwsrCtx ctx) {\n");
  1666         w.write("    " + className + " ret = new " + className + "(ctx);\n");
  1667         for (Prprt p : props) {
  1668             String tn = typeName(p);
  1669             String[] gs = toGetSet(p.name(), tn, p.array());
  1670             if (!p.array()) {
  1671                 boolean isModel[] = { false };
  1672                 boolean isEnum[] = { false };
  1673                 boolean isPrimitive[] = { false };
  1674                 checkType(p, isModel, isEnum, isPrimitive);
  1675                 if (!isModel[0]) {
  1676                     w.write("    ret.prop_" + p.name() + " = " + gs[0] + "();\n");
  1677                     continue;
  1678                 }
  1679                 w.write("    ret.prop_" + p.name() + " =  " + gs[0] + "()  == null ? null : prop_" + p.name() + ".clone();\n");
  1680             } else {
  1681                 w.write("    proto.cloneList(ret." + gs[0] + "(), ctx, prop_" + p.name() + ");\n");
  1682             }
  1683         }
  1684 
  1685         w.write("    return ret;\n");
  1686         w.write("  }\n");
  1687     }
  1688 
  1689     private String inPckName(Element e) {
  1690         StringBuilder sb = new StringBuilder();
  1691         while (e.getKind() != ElementKind.PACKAGE) {
  1692             if (sb.length() == 0) {
  1693                 sb.append(e.getSimpleName());
  1694             } else {
  1695                 sb.insert(0, '.');
  1696                 sb.insert(0, e.getSimpleName());
  1697             }
  1698             e = e.getEnclosingElement();
  1699         }
  1700         return sb.toString();
  1701     }
  1702 
  1703     private String fqn(TypeMirror pt, Element relative) {
  1704         if (pt.getKind() == TypeKind.ERROR) {
  1705             final Elements eu = processingEnv.getElementUtils();
  1706             PackageElement pckg = eu.getPackageOf(relative);
  1707             return pckg.getQualifiedName() + "." + pt.toString();
  1708         }
  1709         return pt.toString();
  1710     }
  1711 
  1712     private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
  1713         TypeMirror tm;
  1714         try {
  1715             String ret = p.typeName(processingEnv);
  1716             TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
  1717             if (e == null) {
  1718                 isModel[0] = true;
  1719                 isEnum[0] = false;
  1720                 isPrimitive[0] = false;
  1721                 return ret;
  1722             }
  1723             tm = e.asType();
  1724         } catch (MirroredTypeException ex) {
  1725             tm = ex.getTypeMirror();
  1726         }
  1727         tm = processingEnv.getTypeUtils().erasure(tm);
  1728         if (isPrimitive[0] = tm.getKind().isPrimitive()) {
  1729             isEnum[0] = false;
  1730             isModel[0] = false;
  1731             return tm.toString();
  1732         }
  1733         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1734         if (e.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
  1735             isModel[0] = true;
  1736             isEnum[0] = false;
  1737             return e.getSimpleName().toString();
  1738         }
  1739 
  1740         final Model m = e == null ? null : e.getAnnotation(Model.class);
  1741         String ret;
  1742         if (m != null) {
  1743             ret = findPkgName(e) + '.' + m.className();
  1744             isModel[0] = true;
  1745             models.put(e, m.className());
  1746         } else if (findModelForMthd(e)) {
  1747             ret = ((TypeElement)e).getQualifiedName().toString();
  1748             isModel[0] = true;
  1749         } else {
  1750             ret = tm.toString();
  1751         }
  1752         TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
  1753         enm = processingEnv.getTypeUtils().erasure(enm);
  1754         isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
  1755         return ret;
  1756     }
  1757 
  1758     private static boolean findModelForMthd(Element clazz) {
  1759         if (clazz == null) {
  1760             return false;
  1761         }
  1762         for (Element e : clazz.getEnclosedElements()) {
  1763             if (e.getKind() == ElementKind.METHOD) {
  1764                 ExecutableElement ee = (ExecutableElement)e;
  1765                 if (
  1766                     ee.getSimpleName().contentEquals("modelFor") &&
  1767                     ee.getParameters().isEmpty()
  1768                 ) {
  1769                     return true;
  1770                 }
  1771             }
  1772         }
  1773         return false;
  1774     }
  1775 
  1776     private void findParamNames(
  1777         Set<String> params, Element e, String url, String jsonParam, StringBuilder... both
  1778     ) {
  1779         int wasJSON = 0;
  1780 
  1781         for (int pos = 0; ;) {
  1782             int next = url.indexOf('{', pos);
  1783             if (next == -1) {
  1784                 both[wasJSON].append('"')
  1785                     .append(url.substring(pos).replace("\"", "\\\""))
  1786                     .append('"');
  1787                 return;
  1788             }
  1789             int close = url.indexOf('}', next);
  1790             if (close == -1) {
  1791                 error("Unbalanced '{' and '}' in " + url, e);
  1792                 return;
  1793             }
  1794             final String paramName = url.substring(next + 1, close);
  1795             params.add(paramName);
  1796             if (paramName.equals(jsonParam) && !jsonParam.isEmpty()) {
  1797                 both[wasJSON].append('"')
  1798                     .append(url.substring(pos, next).replace("\"", "\\\""))
  1799                     .append('"');
  1800                 wasJSON = 1;
  1801             } else {
  1802                 both[wasJSON].append('"')
  1803                     .append(url.substring(pos, next).replace("\"", "\\\""))
  1804                     .append("\" + ").append(paramName).append(" + ");
  1805             }
  1806             pos = close + 1;
  1807         }
  1808     }
  1809 
  1810     private static Prprt findPrprt(Prprt[] properties, String propName) {
  1811         for (Prprt p : properties) {
  1812             if (propName.equals(p.name())) {
  1813                 return p;
  1814             }
  1815         }
  1816         return null;
  1817     }
  1818 
  1819     private boolean isPrimitive(String type) {
  1820         return
  1821             "int".equals(type) ||
  1822             "double".equals(type) ||
  1823             "long".equals(type) ||
  1824             "short".equals(type) ||
  1825             "byte".equals(type) ||
  1826             "char".equals(type) ||
  1827             "boolean".equals(type) ||
  1828             "float".equals(type);
  1829     }
  1830 
  1831     private static Collection<String> findDerivedFrom(Map<String, Collection<String[]>> propsDeps, String derivedProp) {
  1832         Set<String> names = new HashSet<String>();
  1833         for (Map.Entry<String, Collection<String[]>> e : propsDeps.entrySet()) {
  1834             for (String[] pair : e.getValue()) {
  1835                 if (pair[0].equals(derivedProp)) {
  1836                     names.add(e.getKey());
  1837                     break;
  1838                 }
  1839             }
  1840         }
  1841         return names;
  1842     }
  1843 
  1844     private Prprt[] createProps(Element e, Property[] arr) {
  1845         Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
  1846         Prprt[] prev = verify.put(e, ret);
  1847         if (prev != null) {
  1848             error("Two sets of properties for ", e);
  1849         }
  1850         return ret;
  1851     }
  1852 
  1853     private static String strip(String s) {
  1854         int indx = s.indexOf("__");
  1855         if (indx >= 0) {
  1856             return s.substring(0, indx);
  1857         } else {
  1858             return s;
  1859         }
  1860     }
  1861 
  1862     private String findDataSpecified(ExecutableElement e, OnReceive onR) {
  1863         try {
  1864             return onR.data().getName();
  1865         } catch (MirroredTypeException ex) {
  1866             final TypeMirror tm = ex.getTypeMirror();
  1867             String name;
  1868             final Element te = processingEnv.getTypeUtils().asElement(tm);
  1869             if (te.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
  1870                 name = te.getSimpleName().toString();
  1871             } else {
  1872                 name = tm.toString();
  1873             }
  1874             return "java.lang.Object".equals(name) ? null : name;
  1875         } catch (Exception ex) {
  1876             // fallback
  1877         }
  1878 
  1879         AnnotationMirror found = null;
  1880         for (AnnotationMirror am : e.getAnnotationMirrors()) {
  1881             if (am.getAnnotationType().toString().equals(OnReceive.class.getName())) {
  1882                 found = am;
  1883             }
  1884         }
  1885         if (found == null) {
  1886             return null;
  1887         }
  1888 
  1889         for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : found.getElementValues().entrySet()) {
  1890             ExecutableElement ee = entry.getKey();
  1891             AnnotationValue av = entry.getValue();
  1892             if (ee.getSimpleName().contentEquals("data")) {
  1893                 List<? extends Object> values = getAnnoValues(processingEnv, e, found);
  1894                 for (Object v : values) {
  1895                     String sv = v.toString();
  1896                     if (sv.startsWith("data = ") && sv.endsWith(".class")) {
  1897                         return sv.substring(7, sv.length() - 6);
  1898                     }
  1899                 }
  1900                 return "error";
  1901             }
  1902         }
  1903         return null;
  1904     }
  1905 
  1906     static List<? extends Object> getAnnoValues(ProcessingEnvironment pe, Element e, AnnotationMirror am) {
  1907         try {
  1908             Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
  1909             Method m = trees.getMethod("instance", ProcessingEnvironment.class);
  1910             Object instance = m.invoke(null, pe);
  1911             m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
  1912             Object path = m.invoke(instance, e, am);
  1913             m = path.getClass().getMethod("getLeaf");
  1914             Object leaf = m.invoke(path);
  1915             m = leaf.getClass().getMethod("getArguments");
  1916             return (List) m.invoke(leaf);
  1917         } catch (Exception ex) {
  1918             return Collections.emptyList();
  1919         }
  1920     }
  1921 
  1922     private static String findTargetId(Element e) {
  1923         for (AnnotationMirror m : e.getAnnotationMirrors()) {
  1924             if (m.getAnnotationType().toString().equals(Model.class.getName())) {
  1925                 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entrySet : m.getElementValues().entrySet()) {
  1926                     ExecutableElement key = entrySet.getKey();
  1927                     AnnotationValue value = entrySet.getValue();
  1928                     if ("targetId()".equals(key.toString())) {
  1929                         return value.toString();
  1930                     }
  1931                 }
  1932             }
  1933         }
  1934         return null;
  1935     }
  1936 
  1937     private static class Prprt {
  1938         private final Element e;
  1939         private final AnnotationMirror tm;
  1940         private final Property p;
  1941 
  1942         public Prprt(Element e, AnnotationMirror tm, Property p) {
  1943             this.e = e;
  1944             this.tm = tm;
  1945             this.p = p;
  1946         }
  1947 
  1948         String name() {
  1949             return p.name();
  1950         }
  1951 
  1952         boolean array() {
  1953             return p.array();
  1954         }
  1955 
  1956         String typeName(ProcessingEnvironment env) {
  1957             RuntimeException ex;
  1958             try {
  1959                 return p.type().getName();
  1960             } catch (IncompleteAnnotationException e) {
  1961                 ex = e;
  1962             } catch (AnnotationTypeMismatchException e) {
  1963                 ex = e;
  1964             }
  1965             for (Object v : getAnnoValues(env, e, tm)) {
  1966                 String s = v.toString().replace(" ", "");
  1967                 if (s.startsWith("type=") && s.endsWith(".class")) {
  1968                     return s.substring(5, s.length() - 6);
  1969                 }
  1970             }
  1971             throw ex;
  1972         }
  1973 
  1974 
  1975         static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
  1976             if (arr.length == 0) {
  1977                 return new Prprt[0];
  1978             }
  1979 
  1980             if (e.getKind() != ElementKind.CLASS) {
  1981                 throw new IllegalStateException("" + e.getKind());
  1982             }
  1983             TypeElement te = (TypeElement)e;
  1984             List<? extends AnnotationValue> val = null;
  1985             for (AnnotationMirror an : te.getAnnotationMirrors()) {
  1986                 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
  1987                     if (entry.getKey().getSimpleName().contentEquals("properties")) {
  1988                         val = (List)entry.getValue().getValue();
  1989                         break;
  1990                     }
  1991                 }
  1992             }
  1993             if (val == null || val.size() != arr.length) {
  1994                 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
  1995                 return new Prprt[0];
  1996             }
  1997             Prprt[] ret = new Prprt[arr.length];
  1998             BIG: for (int i = 0; i < ret.length; i++) {
  1999                 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
  2000                 ret[i] = new Prprt(e, am, arr[i]);
  2001 
  2002             }
  2003             return ret;
  2004         }
  2005     } // end of Prprt
  2006 
  2007     private static final class GetSet {
  2008         final String name;
  2009         final String getter;
  2010         final String setter;
  2011         final String type;
  2012         final boolean readOnly;
  2013         GetSet(String name, String getter, String setter, String type, boolean readOnly) {
  2014             this.name = name;
  2015             this.getter = getter;
  2016             this.setter = setter;
  2017             this.type = type;
  2018             this.readOnly = readOnly;
  2019         }
  2020     }
  2021 
  2022     @Override
  2023     public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
  2024         final Level l = Level.FINE;
  2025         LOG.log(l, " element: {0}", element);
  2026         LOG.log(l, " annotation: {0}", annotation);
  2027         LOG.log(l, " member: {0}", member);
  2028         LOG.log(l, " userText: {0}", userText);
  2029         LOG.log(l, "str: {0}", annotation.getAnnotationType().toString());
  2030         if (annotation.getAnnotationType().toString().equals(OnReceive.class.getName())) {
  2031             if (member.getSimpleName().contentEquals("method")) {
  2032                 return Arrays.asList(
  2033                     methodOf("GET"),
  2034                     methodOf("POST"),
  2035                     methodOf("PUT"),
  2036                     methodOf("DELETE"),
  2037                     methodOf("HEAD"),
  2038                     methodOf("WebSocket")
  2039                 );
  2040             }
  2041         }
  2042 
  2043         return super.getCompletions(element, annotation, member, userText);
  2044     }
  2045 
  2046     private static final Completion methodOf(String method) {
  2047         ResourceBundle rb = ResourceBundle.getBundle("org.netbeans.html.json.impl.Bundle");
  2048         return Completions.of('"' + method + '"', rb.getString("MSG_Completion_" + method));
  2049     }
  2050 
  2051     private boolean findOnError(ExecutableElement errElem, TypeElement te, String name, String className) {
  2052         String err = null;
  2053         METHODS:
  2054         for (Element e : te.getEnclosedElements()) {
  2055             if (e.getKind() != ElementKind.METHOD) {
  2056                 continue;
  2057             }
  2058             if (!e.getSimpleName().contentEquals(name)) {
  2059                 continue;
  2060             }
  2061             if (!e.getModifiers().contains(Modifier.STATIC)) {
  2062                 errElem = (ExecutableElement) e;
  2063                 err = "Would have to be static";
  2064                 continue;
  2065             }
  2066             ExecutableElement ee = (ExecutableElement) e;
  2067             TypeMirror excType = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
  2068             final List<? extends VariableElement> params = ee.getParameters();
  2069             boolean error = false;
  2070             if (params.size() != 2) {
  2071                 error = true;
  2072             } else {
  2073                 String firstType = params.get(0).asType().toString();
  2074                 int lastDot = firstType.lastIndexOf('.');
  2075                 if (lastDot != -1) {
  2076                     firstType = firstType.substring(lastDot + 1);
  2077                 }
  2078                 if (!firstType.equals(className)) {
  2079                     error = true;
  2080                 }
  2081                 if (!processingEnv.getTypeUtils().isAssignable(excType, params.get(1).asType())) {
  2082                     error = true;
  2083                 }
  2084             }
  2085             if (error) {
  2086                 errElem = (ExecutableElement) e;
  2087                 err = "Error method first argument needs to be " + className + " and second Exception";
  2088                 continue;
  2089             }
  2090             return true;
  2091         }
  2092         if (err == null) {
  2093             err = "Cannot find " + name + "(" + className + ", Exception) method in this class";
  2094         }
  2095         error(err, errElem);
  2096         return false;
  2097     }
  2098 
  2099     private ExecutableElement findWrite(ExecutableElement computedPropElem, TypeElement te, String name, String className) {
  2100         String err = null;
  2101         METHODS:
  2102         for (Element e : te.getEnclosedElements()) {
  2103             if (e.getKind() != ElementKind.METHOD) {
  2104                 continue;
  2105             }
  2106             if (!e.getSimpleName().contentEquals(name)) {
  2107                 continue;
  2108             }
  2109             if (e.equals(computedPropElem)) {
  2110                 continue;
  2111             }
  2112             if (!e.getModifiers().contains(Modifier.STATIC)) {
  2113                 computedPropElem = (ExecutableElement) e;
  2114                 err = "Would have to be static";
  2115                 continue;
  2116             }
  2117             ExecutableElement ee = (ExecutableElement) e;
  2118             if (ee.getReturnType().getKind() != TypeKind.VOID) {
  2119                 computedPropElem = (ExecutableElement) e;
  2120                 err = "Write method has to return void";
  2121                 continue;
  2122             }
  2123             TypeMirror retType = computedPropElem.getReturnType();
  2124             final List<? extends VariableElement> params = ee.getParameters();
  2125             boolean error = false;
  2126             if (params.size() != 2) {
  2127                 error = true;
  2128             } else {
  2129                 String firstType = params.get(0).asType().toString();
  2130                 int lastDot = firstType.lastIndexOf('.');
  2131                 if (lastDot != -1) {
  2132                     firstType = firstType.substring(lastDot + 1);
  2133                 }
  2134                 if (!firstType.equals(className)) {
  2135                     error = true;
  2136                 }
  2137                 if (!processingEnv.getTypeUtils().isAssignable(retType, params.get(1).asType())) {
  2138                     error = true;
  2139                 }
  2140             }
  2141             if (error) {
  2142                 computedPropElem = (ExecutableElement) e;
  2143                 err = "Write method first argument needs to be " + className + " and second " + retType + " or Object";
  2144                 continue;
  2145             }
  2146             return ee;
  2147         }
  2148         if (err == null) {
  2149             err = "Cannot find " + name + "(" + className + ", value) method in this class";
  2150         }
  2151         error(err, computedPropElem);
  2152         return null;
  2153     }
  2154 
  2155 }