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