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