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