json/src/main/java/org/netbeans/html/json/impl/ModelProcessor.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 09 Dec 2015 21:39:13 +0100
changeset 1023 4f906bde3a2e
parent 1017 10427ce1c0ee
child 1030 02568f34628a
permissions -rw-r--r--
#257039: @Model.instance() to allow storage of private (and non-JSON like) state in a model
     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() + " = new " + tn + "();\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                 w.write("  private " + tn + " prop_" + p.name() + ";\n");
   662                 w.write("  public " + tn + " " + gs[0] + "() {\n");
   663                 w.write("    proto.accessProperty(\"" + p.name() + "\");\n");
   664                 w.write("    return prop_" + p.name() + ";\n");
   665                 w.write("  }\n");
   666                 w.write("  public void " + gs[1] + "(" + tn + " v) {\n");
   667                 w.write("    proto.verifyUnlocked();\n");
   668                 w.write("    Object o = prop_" + p.name() + ";\n");
   669                 if (isModel[0]) {
   670                     w.write("    if (o == v) return;\n");
   671                     w.write("    prop_" + p.name() + " = v;\n");
   672                 } else {
   673                     w.write("    if (TYPE.isSame(o , v)) return;\n");
   674                     w.write("    prop_" + p.name() + " = v;\n");
   675                 }
   676                 w.write("    proto.valueHasMutated(\"" + p.name() + "\", o, v);\n");
   677                 {
   678                     Collection<String[]> dependants = deps.get(p.name());
   679                     if (dependants != null) {
   680                         for (String[] pair : dependants) {
   681                             w.write("    proto.valueHasMutated(\"" + pair[0] + "\", null, " + pair[1] + "());\n");
   682                         }
   683                     }
   684                 }
   685                 {
   686                     Collection<String> dependants = functionDeps.get(p.name());
   687                     if (dependants != null) {
   688                         w.append(className).append(" model = ").append(className).append(".this;\n");
   689                         for (String call : dependants) {
   690                             w.append("  ").append(call);
   691                         }
   692                     }
   693                 }
   694                 w.write("  }\n");
   695                 if (builderPrefix != null) {
   696                     w.write("  public " + className + " " + builderMethod(builderPrefix, p) + "(" + tn + " v) {\n");
   697                     w.write("    " + gs[1] + "(v);\n");
   698                     w.write("    return this;\n");
   699                     w.write("  }\n");
   700                 }
   701             }
   702 
   703             for (int i = 0; i < props.size(); i++) {
   704                 if (props.get(i).name.equals(p.name())) {
   705                     error("Cannot have the name " + p.name() + " defined twice", where);
   706                     ok = false;
   707                 }
   708             }
   709 
   710             props.add(new GetSet(
   711                 p.name(),
   712                 gs[0],
   713                 gs[1],
   714                 tn,
   715                 gs[3] == null && !p.array()
   716             ));
   717         }
   718         return ok;
   719     }
   720 
   721     private boolean generateComputedProperties(
   722         String className,
   723         Writer w, Prprt[] fixedProps,
   724         Collection<? extends Element> arr, Collection<GetSet> props,
   725         Map<String,Collection<String[]>> deps
   726     ) throws IOException {
   727         boolean ok = true;
   728         for (Element e : arr) {
   729             if (e.getKind() != ElementKind.METHOD) {
   730                 continue;
   731             }
   732             final ComputedProperty cp = e.getAnnotation(ComputedProperty.class);
   733             final Transitive tp = e.getAnnotation(Transitive.class);
   734             if (cp == null) {
   735                 continue;
   736             }
   737             if (!e.getModifiers().contains(Modifier.STATIC)) {
   738                 error("Method " + e.getSimpleName() + " has to be static when annotated by @ComputedProperty", e);
   739                 ok = false;
   740                 continue;
   741             }
   742             ExecutableElement ee = (ExecutableElement)e;
   743             ExecutableElement write = null;
   744             if (!cp.write().isEmpty()) {
   745                 write = findWrite(ee, (TypeElement)e.getEnclosingElement(), cp.write(), className);
   746                 ok = write != null;
   747             }
   748             final TypeMirror rt = ee.getReturnType();
   749             final Types tu = processingEnv.getTypeUtils();
   750             TypeMirror ert = tu.erasure(rt);
   751             String tn = fqn(ert, ee);
   752             boolean array = false;
   753             final TypeMirror toCheck;
   754             if (tn.equals("java.util.List")) {
   755                 array = true;
   756                 toCheck = ((DeclaredType)rt).getTypeArguments().get(0);
   757             } else {
   758                 toCheck = rt;
   759             }
   760 
   761             final String sn = ee.getSimpleName().toString();
   762 
   763             if (toCheck.getKind().isPrimitive()) {
   764                 // OK
   765             } else {
   766                 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   767                 TypeMirror enumType = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
   768 
   769                 if (tu.isSubtype(toCheck, stringType)) {
   770                     // OK
   771                 } else if (tu.isSubtype(tu.erasure(toCheck), tu.erasure(enumType))) {
   772                     // OK
   773                 } else if (isModel(toCheck)) {
   774                     // OK
   775                 } else {
   776                     try {
   777                         tu.unboxedType(toCheck);
   778                         // boxed types are OK
   779                     } catch (IllegalArgumentException ex) {
   780                         ok = false;
   781                         error(sn + " cannot return " + toCheck, e);
   782                     }
   783                 }
   784             }
   785 
   786             String[] gs = toGetSet(sn, tn, array);
   787 
   788             w.write("  public " + tn);
   789             if (array) {
   790                 w.write("<" + toCheck + ">");
   791             }
   792             w.write(" " + gs[0] + "() {\n");
   793             int arg = 0;
   794             boolean deep = false;
   795             for (VariableElement pe : ee.getParameters()) {
   796                 final String dn = pe.getSimpleName().toString();
   797 
   798                 if (!verifyPropName(pe, dn, fixedProps)) {
   799                     ok = false;
   800                 }
   801                 final TypeMirror pt = pe.asType();
   802                 if (isModel(pt)) {
   803                     deep = true;
   804                 }
   805                 final String dt = fqn(pt, ee);
   806                 if (dt.startsWith("java.util.List") && pt instanceof DeclaredType) {
   807                     final List<? extends TypeMirror> ptArgs = ((DeclaredType)pt).getTypeArguments();
   808                     if (ptArgs.size() == 1 && isModel(ptArgs.get(0))) {
   809                         deep = true;
   810                     }
   811                 }
   812                 String[] call = toGetSet(dn, dt, false);
   813                 w.write("    " + dt + " arg" + (++arg) + " = ");
   814                 w.write(call[0] + "();\n");
   815 
   816                 Collection<String[]> depends = deps.get(dn);
   817                 if (depends == null) {
   818                     depends = new LinkedHashSet<String[]>();
   819                     deps.put(dn, depends);
   820                 }
   821                 depends.add(new String[] { sn, gs[0] });
   822             }
   823             w.write("    try {\n");
   824             if (tp != null) {
   825                 deep = tp.deep();
   826             }
   827             if (deep) {
   828                 w.write("      proto.acquireLock(\"" + sn + "\");\n");
   829             } else {
   830                 w.write("      proto.acquireLock();\n");
   831             }
   832             w.write("      return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
   833             String sep = "";
   834             for (int i = 1; i <= arg; i++) {
   835                 w.write(sep);
   836                 w.write("arg" + i);
   837                 sep = ", ";
   838             }
   839             w.write(");\n");
   840             w.write("    } finally {\n");
   841             w.write("      proto.releaseLock();\n");
   842             w.write("    }\n");
   843             w.write("  }\n");
   844 
   845             if (write == null) {
   846                 props.add(new GetSet(
   847                     e.getSimpleName().toString(),
   848                     gs[0],
   849                     null,
   850                     tn,
   851                     true
   852                 ));
   853             } else {
   854                 w.write("  public void " + gs[4] + "(" + write.getParameters().get(1).asType());
   855                 w.write(" value) {\n");
   856                 w.write("    " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + write.getSimpleName() + "(this, value);\n");
   857                 w.write("  }\n");
   858 
   859                 props.add(new GetSet(
   860                     e.getSimpleName().toString(),
   861                     gs[0],
   862                     gs[4],
   863                     tn,
   864                     false
   865                 ));
   866             }
   867         }
   868 
   869         return ok;
   870     }
   871 
   872     private static String[] toGetSet(String name, String type, boolean array) {
   873         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   874         boolean clazz = "class".equals(name);
   875         String pref = clazz ? "access" : "get";
   876         if ("boolean".equals(type) && !array) {
   877             pref = "is";
   878         }
   879         if (array) {
   880             return new String[] {
   881                 pref + n,
   882                 null,
   883                 "a" + n,
   884                 null,
   885                 "set" + n
   886             };
   887         }
   888         return new String[]{
   889             pref + n,
   890             "set" + n,
   891             "a" + n,
   892             "",
   893             "set" + n
   894         };
   895     }
   896 
   897     private String typeName(Prprt p) {
   898         String ret;
   899         boolean[] isModel = { false };
   900         boolean[] isEnum = { false };
   901         boolean isPrimitive[] = { false };
   902         ret = checkType(p, isModel, isEnum, isPrimitive);
   903         if (p.array()) {
   904             String bt = findBoxedType(ret);
   905             if (bt != null) {
   906                 return bt;
   907             }
   908         }
   909         return ret;
   910     }
   911 
   912     private static String findBoxedType(String ret) {
   913         if (ret.equals("boolean")) {
   914             return Boolean.class.getName();
   915         }
   916         if (ret.equals("byte")) {
   917             return Byte.class.getName();
   918         }
   919         if (ret.equals("short")) {
   920             return Short.class.getName();
   921         }
   922         if (ret.equals("char")) {
   923             return Character.class.getName();
   924         }
   925         if (ret.equals("int")) {
   926             return Integer.class.getName();
   927         }
   928         if (ret.equals("long")) {
   929             return Long.class.getName();
   930         }
   931         if (ret.equals("float")) {
   932             return Float.class.getName();
   933         }
   934         if (ret.equals("double")) {
   935             return Double.class.getName();
   936         }
   937         return null;
   938     }
   939 
   940     private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
   941         StringBuilder sb = new StringBuilder();
   942         String sep = "";
   943         for (Prprt Prprt : existingProps) {
   944             if (Prprt.name().equals(propName)) {
   945                 return true;
   946             }
   947             sb.append(sep);
   948             sb.append('"');
   949             sb.append(Prprt.name());
   950             sb.append('"');
   951             sep = ", ";
   952         }
   953         error(
   954             propName + " is not one of known properties: " + sb
   955             , e
   956         );
   957         return false;
   958     }
   959 
   960     private static String findPkgName(Element e) {
   961         for (;;) {
   962             if (e.getKind() == ElementKind.PACKAGE) {
   963                 return ((PackageElement)e).getQualifiedName().toString();
   964             }
   965             e = e.getEnclosingElement();
   966         }
   967     }
   968 
   969     private boolean generateFunctions(
   970         Element clazz, StringWriter body, String className,
   971         List<? extends Element> enclosedElements, List<Object> functions
   972     ) {
   973         boolean instance = clazz.getAnnotation(Model.class).instance();
   974         for (Element m : enclosedElements) {
   975             if (m.getKind() != ElementKind.METHOD) {
   976                 continue;
   977             }
   978             ExecutableElement e = (ExecutableElement)m;
   979             Function onF = e.getAnnotation(Function.class);
   980             if (onF == null) {
   981                 continue;
   982             }
   983             if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
   984                 error("@OnFunction method needs to be static", e);
   985                 return false;
   986             }
   987             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   988                 error("@OnFunction method cannot be private", e);
   989                 return false;
   990             }
   991             if (e.getReturnType().getKind() != TypeKind.VOID) {
   992                 error("@OnFunction method should return void", e);
   993                 return false;
   994             }
   995             String n = e.getSimpleName().toString();
   996             functions.add(n);
   997             functions.add(e);
   998         }
   999         return true;
  1000     }
  1001 
  1002     private boolean generateOnChange(Element clazz, Map<String,Collection<String[]>> propDeps,
  1003         Prprt[] properties, String className,
  1004         Map<String, Collection<String>> functionDeps
  1005     ) {
  1006         boolean instance = clazz.getAnnotation(Model.class).instance();
  1007         for (Element m : clazz.getEnclosedElements()) {
  1008             if (m.getKind() != ElementKind.METHOD) {
  1009                 continue;
  1010             }
  1011             ExecutableElement e = (ExecutableElement) m;
  1012             OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
  1013             if (onPC == null) {
  1014                 continue;
  1015             }
  1016             for (String pn : onPC.value()) {
  1017                 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
  1018                     error("No Prprt named '" + pn + "' in the model", clazz);
  1019                     return false;
  1020                 }
  1021             }
  1022             if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
  1023                 error("@OnPrprtChange method needs to be static", e);
  1024                 return false;
  1025             }
  1026             if (e.getModifiers().contains(Modifier.PRIVATE)) {
  1027                 error("@OnPrprtChange method cannot be private", e);
  1028                 return false;
  1029             }
  1030             if (e.getReturnType().getKind() != TypeKind.VOID) {
  1031                 error("@OnPrprtChange method should return void", e);
  1032                 return false;
  1033             }
  1034             String n = e.getSimpleName().toString();
  1035 
  1036 
  1037             for (String pn : onPC.value()) {
  1038                 StringBuilder call = new StringBuilder();
  1039                 call.append("  ").append(inPckName(clazz, instance)).append(".").append(n).append("(");
  1040                 call.append(wrapPropName(e, className, "name", pn));
  1041                 call.append(");\n");
  1042 
  1043                 Collection<String> change = functionDeps.get(pn);
  1044                 if (change == null) {
  1045                     change = new ArrayList<String>();
  1046                     functionDeps.put(pn, change);
  1047                 }
  1048                 change.add(call.toString());
  1049                 for (String dpn : findDerivedFrom(propDeps, pn)) {
  1050                     change = functionDeps.get(dpn);
  1051                     if (change == null) {
  1052                         change = new ArrayList<String>();
  1053                         functionDeps.put(dpn, change);
  1054                     }
  1055                     change.add(call.toString());
  1056                 }
  1057             }
  1058         }
  1059         return true;
  1060     }
  1061 
  1062     private boolean generateOperation(Element clazz,
  1063         StringWriter body, String className,
  1064         List<? extends Element> enclosedElements,
  1065         List<Object> functions
  1066     ) {
  1067         boolean instance = clazz.getAnnotation(Model.class).instance();
  1068         for (Element m : enclosedElements) {
  1069             if (m.getKind() != ElementKind.METHOD) {
  1070                 continue;
  1071             }
  1072             ExecutableElement e = (ExecutableElement)m;
  1073             ModelOperation mO = e.getAnnotation(ModelOperation.class);
  1074             if (mO == null) {
  1075                 continue;
  1076             }
  1077             if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
  1078                 error("@ModelOperation method needs to be static", e);
  1079                 return false;
  1080             }
  1081             if (e.getModifiers().contains(Modifier.PRIVATE)) {
  1082                 error("@ModelOperation method cannot be private", e);
  1083                 return false;
  1084             }
  1085             if (e.getReturnType().getKind() != TypeKind.VOID) {
  1086                 error("@ModelOperation method should return void", e);
  1087                 return false;
  1088             }
  1089             List<String> args = new ArrayList<String>();
  1090             {
  1091                 body.append("  public void ").append(m.getSimpleName()).append("(");
  1092                 String sep = "";
  1093                 boolean checkFirst = true;
  1094                 for (VariableElement ve : e.getParameters()) {
  1095                     final TypeMirror type = ve.asType();
  1096                     CharSequence simpleName;
  1097                     if (type.getKind() == TypeKind.DECLARED) {
  1098                         simpleName = ((DeclaredType)type).asElement().getSimpleName();
  1099                     } else {
  1100                         simpleName = type.toString();
  1101                     }
  1102                     if (checkFirst && simpleName.toString().equals(className)) {
  1103                         checkFirst = false;
  1104                     } else {
  1105                         if (checkFirst) {
  1106                             error("First parameter of @ModelOperation method must be " + className, m);
  1107                             return false;
  1108                         }
  1109                         args.add(ve.getSimpleName().toString());
  1110                         body.append(sep).append("final ");
  1111                         body.append(ve.asType().toString()).append(" ");
  1112                         body.append(ve.toString());
  1113                         sep = ", ";
  1114                     }
  1115                 }
  1116                 body.append(") {\n");
  1117                 int idx = functions.size() / 2;
  1118                 functions.add(m.getSimpleName().toString());
  1119                 body.append("    proto.runInBrowser(" + idx);
  1120                 for (String s : args) {
  1121                     body.append(", ").append(s);
  1122                 }
  1123                 body.append(");\n");
  1124                 body.append("  }\n");
  1125 
  1126                 StringBuilder call = new StringBuilder();
  1127                 call.append("{ Object[] arr = (Object[])data; ");
  1128                 call.append(inPckName(clazz, true)).append(".").append(m.getSimpleName()).append("(");
  1129                 int i = 0;
  1130                 for (VariableElement ve : e.getParameters()) {
  1131                     if (i++ == 0) {
  1132                         call.append("model");
  1133                         continue;
  1134                     }
  1135                     String type = ve.asType().toString();
  1136                     String boxedType = findBoxedType(type);
  1137                     if (boxedType != null) {
  1138                         type = boxedType;
  1139                     }
  1140                     call.append(", ").append("(").append(type).append(")arr[").append(i - 2).append("]");
  1141                 }
  1142                 call.append("); }");
  1143                 functions.add(call.toString());
  1144             }
  1145 
  1146         }
  1147         return true;
  1148     }
  1149 
  1150 
  1151     private boolean generateReceive(
  1152         Element clazz, StringWriter body, String className,
  1153         List<? extends Element> enclosedElements, StringBuilder inType
  1154     ) {
  1155         boolean ret = generateReceiveImpl(clazz, body, className, enclosedElements, inType);
  1156         if (!ret) {
  1157             inType.setLength(0);
  1158         }
  1159         return ret;
  1160     }
  1161     private boolean generateReceiveImpl(
  1162         Element clazz, StringWriter body, String className,
  1163         List<? extends Element> enclosedElements, StringBuilder inType
  1164     ) {
  1165         inType.append("  @Override public void onMessage(").append(className).append(" model, int index, int type, Object data, Object[] params) {\n");
  1166         inType.append("    switch (index) {\n");
  1167         int index = 0;
  1168         boolean ok = true;
  1169         boolean instance = clazz.getAnnotation(Model.class).instance();
  1170         for (Element m : enclosedElements) {
  1171             if (m.getKind() != ElementKind.METHOD) {
  1172                 continue;
  1173             }
  1174             ExecutableElement e = (ExecutableElement)m;
  1175             OnReceive onR = e.getAnnotation(OnReceive.class);
  1176             if (onR == null) {
  1177                 continue;
  1178             }
  1179             if (!instance && !e.getModifiers().contains(Modifier.STATIC)) {
  1180                 error("@OnReceive method needs to be static", e);
  1181                 return false;
  1182             }
  1183             if (e.getModifiers().contains(Modifier.PRIVATE)) {
  1184                 error("@OnReceive method cannot be private", e);
  1185                 return false;
  1186             }
  1187             if (e.getReturnType().getKind() != TypeKind.VOID) {
  1188                 error("@OnReceive method should return void", e);
  1189                 return false;
  1190             }
  1191             if (!onR.jsonp().isEmpty() && !"GET".equals(onR.method())) {
  1192                 error("JSONP works only with GET transport method", e);
  1193             }
  1194             String dataMirror = findDataSpecified(e, onR);
  1195             if ("PUT".equals(onR.method()) && dataMirror == null) {
  1196                 error("PUT method needs to specify a data() class", e);
  1197                 return false;
  1198             }
  1199             if ("POST".equals(onR.method()) && dataMirror == null) {
  1200                 error("POST method needs to specify a data() class", e);
  1201                 return false;
  1202             }
  1203             if (e.getParameters().size() < 2) {
  1204                 error("@OnReceive method needs at least two parameters", e);
  1205             }
  1206             final boolean isWebSocket = "WebSocket".equals(onR.method());
  1207             if (isWebSocket && dataMirror == null) {
  1208                 error("WebSocket method needs to specify a data() class", e);
  1209             }
  1210             int expectsList = 0;
  1211             List<String> args = new ArrayList<String>();
  1212             List<String> params = new ArrayList<String>();
  1213             // first argument is model class
  1214             {
  1215                 TypeMirror type = e.getParameters().get(0).asType();
  1216                 CharSequence simpleName;
  1217                 if (type.getKind() == TypeKind.DECLARED) {
  1218                     simpleName = ((DeclaredType) type).asElement().getSimpleName();
  1219                 } else {
  1220                     simpleName = type.toString();
  1221                 }
  1222                 if (simpleName.toString().equals(className)) {
  1223                     args.add("model");
  1224                 } else {
  1225                     error("First parameter needs to be " + className, e);
  1226                     return false;
  1227                 }
  1228             }
  1229 
  1230             String modelClass;
  1231             {
  1232                 final Types tu = processingEnv.getTypeUtils();
  1233                 TypeMirror type = e.getParameters().get(1).asType();
  1234                 TypeMirror modelType = null;
  1235                 TypeMirror ert = tu.erasure(type);
  1236 
  1237                 if (isModel(type)) {
  1238                     modelType = type;
  1239                 } else if (type.getKind() == TypeKind.ARRAY) {
  1240                     modelType = ((ArrayType)type).getComponentType();
  1241                     expectsList = 1;
  1242                 } else if ("java.util.List".equals(fqn(ert, e))) {
  1243                     List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments();
  1244                     if (typeArgs.size() == 1) {
  1245                         modelType = typeArgs.get(0);
  1246                         expectsList = 2;
  1247                     }
  1248                 } else if (type.toString().equals("java.lang.String")) {
  1249                     modelType = type;
  1250                 }
  1251                 if (modelType == null) {
  1252                     error("Second arguments needs to be a model, String or array or List of models", e);
  1253                     return false;
  1254                 }
  1255                 modelClass = modelType.toString();
  1256                 if (expectsList == 1) {
  1257                     args.add("arr");
  1258                 } else if (expectsList == 2) {
  1259                     args.add("java.util.Arrays.asList(arr)");
  1260                 } else {
  1261                     args.add("arr[0]");
  1262                 }
  1263             }
  1264             String n = e.getSimpleName().toString();
  1265             if (isWebSocket) {
  1266                 body.append("  /** Performs WebSocket communication. Call with <code>null</code> data parameter\n");
  1267                 body.append("  * to open the connection (even if not required). Call with non-null data to\n");
  1268                 body.append("  * send messages to server. Call again with <code>null</code> data to close the socket.\n");
  1269                 body.append("  */\n");
  1270                 if (onR.headers().length > 0) {
  1271                     error("WebSocket spec does not support headers", e);
  1272                 }
  1273             }
  1274             body.append("  public void ").append(n).append("(");
  1275             StringBuilder urlBefore = new StringBuilder();
  1276             StringBuilder urlAfter = new StringBuilder();
  1277             StringBuilder headers = new StringBuilder();
  1278             String jsonpVarName = null;
  1279             {
  1280                 String sep = "";
  1281                 boolean skipJSONP = onR.jsonp().isEmpty();
  1282                 Set<String> receiveParams = new LinkedHashSet<String>();
  1283                 findParamNames(receiveParams, e, onR.url(), onR.jsonp(), urlBefore, urlAfter);
  1284                 for (String headerLine : onR.headers()) {
  1285                     if (headerLine.contains("\r") || headerLine.contains("\n")) {
  1286                         error("Header line cannot contain line separator", e);
  1287                     }
  1288                     findParamNames(receiveParams, e, headerLine, null, headers);
  1289                     headers.append("+ \"\\r\\n\" +\n");
  1290                 }
  1291                 if (headers.length() > 0) {
  1292                     headers.append("\"\"");
  1293                 }
  1294                 for (String p : receiveParams) {
  1295                     if (!skipJSONP && p.equals(onR.jsonp())) {
  1296                         skipJSONP = true;
  1297                         jsonpVarName = p;
  1298                         continue;
  1299                     }
  1300                     body.append(sep);
  1301                     body.append("String ").append(p);
  1302                     sep = ", ";
  1303                 }
  1304                 if (!skipJSONP) {
  1305                     error(
  1306                         "Name of jsonp attribute ('" + onR.jsonp() +
  1307                         "') is not used in url attribute '" + onR.url() + "'", e
  1308                     );
  1309                 }
  1310                 if (dataMirror != null) {
  1311                     body.append(sep).append(dataMirror.toString()).append(" data");
  1312                 }
  1313                 for (int i = 2; i < e.getParameters().size(); i++) {
  1314                     if (isWebSocket) {
  1315                         error("@OnReceive(method=\"WebSocket\") can only have two arguments", e);
  1316                         ok = false;
  1317                     }
  1318 
  1319                     VariableElement ve = e.getParameters().get(i);
  1320                     body.append(sep).append(ve.asType().toString()).append(" ").append(ve.getSimpleName());
  1321                     final String tp = ve.asType().toString();
  1322                     String btn = findBoxedType(tp);
  1323                     if (btn == null) {
  1324                         btn = tp;
  1325                     }
  1326                     args.add("(" + btn + ")params[" + (i - 2) + "]");
  1327                     params.add(ve.getSimpleName().toString());
  1328                     sep = ", ";
  1329                 }
  1330             }
  1331             body.append(") {\n");
  1332             boolean webSocket = onR.method().equals("WebSocket");
  1333             if (webSocket) {
  1334                 if (generateWSReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
  1335                     return false;
  1336                 }
  1337                 body.append("  }\n");
  1338                 body.append("  private Object ws_" + e.getSimpleName() + ";\n");
  1339             } else {
  1340                 if (generateJSONReceiveBody(index++, body, inType, onR, e, clazz, className, expectsList != 0, modelClass, n, args, params, urlBefore, jsonpVarName, urlAfter, dataMirror, headers)) {
  1341                     ok = false;
  1342                 }
  1343                 body.append("  }\n");
  1344             }
  1345         }
  1346         inType.append("    }\n");
  1347         inType.append("    throw new UnsupportedOperationException(\"index: \" + index + \" type: \" + type);\n");
  1348         inType.append("  }\n");
  1349         return ok;
  1350     }
  1351 
  1352     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) {
  1353         boolean error = false;
  1354         body.append(
  1355             "    case " + index + ": {\n" +
  1356             "      if (type == 2) { /* on error */\n" +
  1357             "        Exception ex = (Exception)data;\n"
  1358             );
  1359         if (onR.onError().isEmpty()) {
  1360             body.append(
  1361                 "        ex.printStackTrace();\n"
  1362                 );
  1363         } else {
  1364             error = !findOnError(e, ((TypeElement)clazz), onR.onError(), className);
  1365             body.append("        ").append(clazz.getSimpleName()).append(".").append(onR.onError()).append("(");
  1366             body.append("model, ex);\n");
  1367         }
  1368         body.append(
  1369             "        return;\n" +
  1370             "      } else if (type == 1) {\n" +
  1371             "        Object[] ev = (Object[])data;\n"
  1372             );
  1373         if (expectsList) {
  1374             body.append(
  1375                 "        " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
  1376                 );
  1377         } else {
  1378             body.append(
  1379                 "        " + modelClass + "[] arr = { null };\n"
  1380                 );
  1381         }
  1382         body.append(
  1383             "        TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
  1384         );
  1385         {
  1386             body.append("        ").append(clazz.getSimpleName()).append(".").append(n).append("(");
  1387             String sep = "";
  1388             for (String arg : args) {
  1389                 body.append(sep);
  1390                 body.append(arg);
  1391                 sep = ", ";
  1392             }
  1393             body.append(");\n");
  1394         }
  1395         body.append(
  1396             "        return;\n" +
  1397             "      }\n" +
  1398             "    }\n"
  1399             );
  1400         method.append("    proto.loadJSONWithHeaders(" + index + ",\n        ");
  1401         method.append(headers.length() == 0 ? "null" : headers).append(",\n        ");
  1402         method.append(urlBefore).append(", ");
  1403         if (jsonpVarName != null) {
  1404             method.append(urlAfter);
  1405         } else {
  1406             method.append("null");
  1407         }
  1408         if (!"GET".equals(onR.method()) || dataMirror != null) {
  1409             method.append(", \"").append(onR.method()).append('"');
  1410             if (dataMirror != null) {
  1411                 method.append(", data");
  1412             } else {
  1413                 method.append(", null");
  1414             }
  1415         } else {
  1416             method.append(", null, null");
  1417         }
  1418         for (String a : params) {
  1419             method.append(", ").append(a);
  1420         }
  1421         method.append(");\n");
  1422         return error;
  1423     }
  1424 
  1425     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) {
  1426         body.append(
  1427             "    case " + index + ": {\n" +
  1428             "      if (type == 0) { /* on open */\n" +
  1429             "        ").append(inPckName(clazz, true)).append(".").append(n).append("(");
  1430         {
  1431             String sep = "";
  1432             for (String arg : args) {
  1433                 body.append(sep);
  1434                 if (arg.startsWith("arr") || arg.startsWith("java.util.Array")) {
  1435                     body.append("null");
  1436                 } else {
  1437                     body.append(arg);
  1438                 }
  1439                 sep = ", ";
  1440             }
  1441         }
  1442         body.append(");\n");
  1443         body.append(
  1444             "        return;\n" +
  1445             "      } else if (type == 2) { /* on error */\n" +
  1446             "        Exception value = (Exception)data;\n"
  1447             );
  1448         if (onR.onError().isEmpty()) {
  1449             body.append(
  1450                 "        value.printStackTrace();\n"
  1451                 );
  1452         } else {
  1453             if (!findOnError(e, ((TypeElement)clazz), onR.onError(), className)) {
  1454                 return true;
  1455             }
  1456             body.append("        ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
  1457             body.append("model, value);\n");
  1458         }
  1459         body.append(
  1460             "        return;\n" +
  1461             "      } else if (type == 1) {\n" +
  1462             "        Object[] ev = (Object[])data;\n"
  1463         );
  1464         if (expectsList) {
  1465             body.append(
  1466                 "        " + modelClass + "[] arr = new " + modelClass + "[ev.length];\n"
  1467                 );
  1468         } else {
  1469             body.append(
  1470                 "        " + modelClass + "[] arr = { null };\n"
  1471                 );
  1472         }
  1473         body.append(
  1474             "        TYPE.copyJSON(model.proto.getContext(), ev, " + modelClass + ".class, arr);\n"
  1475         );
  1476         {
  1477             body.append("        ").append(inPckName(clazz, true)).append(".").append(n).append("(");
  1478             String sep = "";
  1479             for (String arg : args) {
  1480                 body.append(sep);
  1481                 body.append(arg);
  1482                 sep = ", ";
  1483             }
  1484             body.append(");\n");
  1485         }
  1486         body.append(
  1487             "        return;\n" +
  1488             "      }"
  1489         );
  1490         if (!onR.onError().isEmpty()) {
  1491             body.append(" else if (type == 3) { /* on close */\n");
  1492             body.append("        ").append(inPckName(clazz, true)).append(".").append(onR.onError()).append("(");
  1493             body.append("model, null);\n");
  1494             body.append(
  1495                 "        return;" +
  1496                 "      }"
  1497             );
  1498         }
  1499         body.append("\n");
  1500         body.append("    }\n");
  1501         method.append("    if (this.ws_").append(e.getSimpleName()).append(" == null) {\n");
  1502         method.append("      this.ws_").append(e.getSimpleName());
  1503         method.append("= proto.wsOpen(" + index + ", ");
  1504         method.append(urlBefore).append(", data);\n");
  1505         method.append("    } else {\n");
  1506         method.append("      proto.wsSend(this.ws_").append(e.getSimpleName()).append(", ").append(urlBefore).append(", data");
  1507         for (String a : params) {
  1508             method.append(", ").append(a);
  1509         }
  1510         method.append(");\n");
  1511         method.append("    }\n");
  1512         return false;
  1513     }
  1514 
  1515     private CharSequence wrapParams(
  1516         ExecutableElement ee, String id, String className, String classRef, String evName, String dataName
  1517     ) {
  1518         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1519         StringBuilder params = new StringBuilder();
  1520         boolean first = true;
  1521         for (VariableElement ve : ee.getParameters()) {
  1522             if (!first) {
  1523                 params.append(", ");
  1524             }
  1525             first = false;
  1526             String toCall = null;
  1527             String toFinish = null;
  1528             boolean addNull = true;
  1529             if (ve.asType() == stringType) {
  1530                 if (ve.getSimpleName().contentEquals("id")) {
  1531                     params.append('"').append(id).append('"');
  1532                     continue;
  1533                 }
  1534                 toCall = classRef + ".proto.toString(";
  1535             }
  1536             if (ve.asType().getKind() == TypeKind.DOUBLE) {
  1537                 toCall = classRef + ".proto.toNumber(";
  1538                 toFinish = ".doubleValue()";
  1539             }
  1540             if (ve.asType().getKind() == TypeKind.FLOAT) {
  1541                 toCall = classRef + ".proto.toNumber(";
  1542                 toFinish = ".floatValue()";
  1543             }
  1544             if (ve.asType().getKind() == TypeKind.INT) {
  1545                 toCall = classRef + ".proto.toNumber(";
  1546                 toFinish = ".intValue()";
  1547             }
  1548             if (ve.asType().getKind() == TypeKind.BYTE) {
  1549                 toCall = classRef + ".proto.toNumber(";
  1550                 toFinish = ".byteValue()";
  1551             }
  1552             if (ve.asType().getKind() == TypeKind.SHORT) {
  1553                 toCall = classRef + ".proto.toNumber(";
  1554                 toFinish = ".shortValue()";
  1555             }
  1556             if (ve.asType().getKind() == TypeKind.LONG) {
  1557                 toCall = classRef + ".proto.toNumber(";
  1558                 toFinish = ".longValue()";
  1559             }
  1560             if (ve.asType().getKind() == TypeKind.BOOLEAN) {
  1561                 toCall = "\"true\".equals(" + classRef + ".proto.toString(";
  1562                 toFinish = ")";
  1563             }
  1564             if (ve.asType().getKind() == TypeKind.CHAR) {
  1565                 toCall = "(char)" + classRef + ".proto.toNumber(";
  1566                 toFinish = ".intValue()";
  1567             }
  1568             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
  1569                 toCall = classRef + ".proto.toModel(" + ve.asType() + ".class, ";
  1570                 addNull = false;
  1571             }
  1572 
  1573             if (toCall != null) {
  1574                 params.append(toCall);
  1575                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
  1576                     params.append(dataName);
  1577                     if (addNull) {
  1578                         params.append(", null");
  1579                     }
  1580                 } else {
  1581                     if (evName == null) {
  1582                         final StringBuilder sb = new StringBuilder();
  1583                         sb.append("Unexpected string parameter name.");
  1584                         if (dataName != null) {
  1585                             sb.append(" Try \"").append(dataName).append("\"");
  1586                         }
  1587                         error(sb.toString(), ee);
  1588                     }
  1589                     params.append(evName);
  1590                     params.append(", \"");
  1591                     params.append(ve.getSimpleName().toString());
  1592                     params.append("\"");
  1593                 }
  1594                 params.append(")");
  1595                 if (toFinish != null) {
  1596                     params.append(toFinish);
  1597                 }
  1598                 continue;
  1599             }
  1600             String rn = fqn(ve.asType(), ee);
  1601             int last = rn.lastIndexOf('.');
  1602             if (last >= 0) {
  1603                 rn = rn.substring(last + 1);
  1604             }
  1605             if (rn.equals(className)) {
  1606                 params.append(classRef);
  1607                 continue;
  1608             }
  1609             StringBuilder err = new StringBuilder();
  1610             err.append("Argument ").
  1611                 append(ve.getSimpleName()).
  1612                 append(" is not valid. The annotated method can only accept ").
  1613                 append(className).
  1614                 append(" argument");
  1615             if (dataName != null) {
  1616                 err.append(" or argument named '").append(dataName).append("'");
  1617             }
  1618             err.append(".");
  1619             error(err.toString(), ee);
  1620         }
  1621         return params;
  1622     }
  1623 
  1624 
  1625     private CharSequence wrapPropName(
  1626         ExecutableElement ee, String className, String propName, String propValue
  1627     ) {
  1628         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1629         StringBuilder params = new StringBuilder();
  1630         boolean first = true;
  1631         for (VariableElement ve : ee.getParameters()) {
  1632             if (!first) {
  1633                 params.append(", ");
  1634             }
  1635             first = false;
  1636             if (ve.asType() == stringType) {
  1637                 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
  1638                     params.append('"').append(propValue).append('"');
  1639                 } else {
  1640                     error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
  1641                 }
  1642                 continue;
  1643             }
  1644             String rn = fqn(ve.asType(), ee);
  1645             int last = rn.lastIndexOf('.');
  1646             if (last >= 0) {
  1647                 rn = rn.substring(last + 1);
  1648             }
  1649             if (rn.equals(className)) {
  1650                 params.append("model");
  1651                 continue;
  1652             }
  1653             error(
  1654                 "@OnPrprtChange method can only accept String or " + className + " arguments",
  1655                 ee);
  1656         }
  1657         return params;
  1658     }
  1659 
  1660     private boolean isModel(TypeMirror tm) {
  1661         if (tm.getKind() == TypeKind.ERROR) {
  1662             return true;
  1663         }
  1664         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1665         if (e == null) {
  1666             return false;
  1667         }
  1668         for (Element ch : e.getEnclosedElements()) {
  1669             if (ch.getKind() == ElementKind.METHOD) {
  1670                 ExecutableElement ee = (ExecutableElement)ch;
  1671                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
  1672                     return true;
  1673                 }
  1674             }
  1675         }
  1676         return models.values().contains(e.getSimpleName().toString());
  1677     }
  1678 
  1679     private void writeToString(Prprt[] props, Writer w) throws IOException {
  1680         w.write("  public String toString() {\n");
  1681         w.write("    StringBuilder sb = new StringBuilder();\n");
  1682         w.write("    sb.append('{');\n");
  1683         String sep = "";
  1684         for (Prprt p : props) {
  1685             w.write(sep);
  1686             w.append("    sb.append('\"').append(\"" + p.name() + "\")");
  1687                 w.append(".append('\"').append(\":\");\n");
  1688             w.append("    sb.append(TYPE.toJSON(prop_");
  1689             w.append(p.name()).append("));\n");
  1690             sep =    "    sb.append(',');\n";
  1691         }
  1692         w.write("    sb.append('}');\n");
  1693         w.write("    return sb.toString();\n");
  1694         w.write("  }\n");
  1695     }
  1696     private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
  1697         w.write("  public " + className + " clone() {\n");
  1698         w.write("    return clone(proto.getContext());\n");
  1699         w.write("  }\n");
  1700         w.write("  private " + className + " clone(net.java.html.BrwsrCtx ctx) {\n");
  1701         w.write("    " + className + " ret = new " + className + "(ctx);\n");
  1702         for (Prprt p : props) {
  1703             String tn = typeName(p);
  1704             String[] gs = toGetSet(p.name(), tn, p.array());
  1705             if (!p.array()) {
  1706                 boolean isModel[] = { false };
  1707                 boolean isEnum[] = { false };
  1708                 boolean isPrimitive[] = { false };
  1709                 checkType(p, isModel, isEnum, isPrimitive);
  1710                 if (!isModel[0]) {
  1711                     w.write("    ret.prop_" + p.name() + " = " + gs[0] + "();\n");
  1712                     continue;
  1713                 }
  1714                 w.write("    ret.prop_" + p.name() + " =  " + gs[0] + "()  == null ? null : prop_" + p.name() + ".clone();\n");
  1715             } else {
  1716                 w.write("    proto.cloneList(ret." + gs[0] + "(), ctx, prop_" + p.name() + ");\n");
  1717             }
  1718         }
  1719 
  1720         w.write("    return ret;\n");
  1721         w.write("  }\n");
  1722     }
  1723 
  1724     private String inPckName(Element e, boolean preferInstance) {
  1725         if (preferInstance && e.getAnnotation(Model.class).instance()) {
  1726             return "model.instance";
  1727         }
  1728         StringBuilder sb = new StringBuilder();
  1729         while (e.getKind() != ElementKind.PACKAGE) {
  1730             if (sb.length() == 0) {
  1731                 sb.append(e.getSimpleName());
  1732             } else {
  1733                 sb.insert(0, '.');
  1734                 sb.insert(0, e.getSimpleName());
  1735             }
  1736             e = e.getEnclosingElement();
  1737         }
  1738         return sb.toString();
  1739     }
  1740 
  1741     private String fqn(TypeMirror pt, Element relative) {
  1742         if (pt.getKind() == TypeKind.ERROR) {
  1743             final Elements eu = processingEnv.getElementUtils();
  1744             PackageElement pckg = eu.getPackageOf(relative);
  1745             return pckg.getQualifiedName() + "." + pt.toString();
  1746         }
  1747         return pt.toString();
  1748     }
  1749 
  1750     private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
  1751         TypeMirror tm;
  1752         try {
  1753             String ret = p.typeName(processingEnv);
  1754             TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
  1755             if (e == null) {
  1756                 isModel[0] = true;
  1757                 isEnum[0] = false;
  1758                 isPrimitive[0] = false;
  1759                 return ret;
  1760             }
  1761             tm = e.asType();
  1762         } catch (MirroredTypeException ex) {
  1763             tm = ex.getTypeMirror();
  1764         }
  1765         tm = processingEnv.getTypeUtils().erasure(tm);
  1766         if (isPrimitive[0] = tm.getKind().isPrimitive()) {
  1767             isEnum[0] = false;
  1768             isModel[0] = false;
  1769             return tm.toString();
  1770         }
  1771         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1772         if (e.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
  1773             isModel[0] = true;
  1774             isEnum[0] = false;
  1775             return e.getSimpleName().toString();
  1776         }
  1777 
  1778         final Model m = e == null ? null : e.getAnnotation(Model.class);
  1779         String ret;
  1780         if (m != null) {
  1781             ret = findPkgName(e) + '.' + m.className();
  1782             isModel[0] = true;
  1783             models.put(e, m.className());
  1784         } else if (findModelForMthd(e)) {
  1785             ret = ((TypeElement)e).getQualifiedName().toString();
  1786             isModel[0] = true;
  1787         } else {
  1788             ret = tm.toString();
  1789         }
  1790         TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
  1791         enm = processingEnv.getTypeUtils().erasure(enm);
  1792         isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
  1793         return ret;
  1794     }
  1795 
  1796     private static boolean findModelForMthd(Element clazz) {
  1797         if (clazz == null) {
  1798             return false;
  1799         }
  1800         for (Element e : clazz.getEnclosedElements()) {
  1801             if (e.getKind() == ElementKind.METHOD) {
  1802                 ExecutableElement ee = (ExecutableElement)e;
  1803                 if (
  1804                     ee.getSimpleName().contentEquals("modelFor") &&
  1805                     ee.getParameters().isEmpty()
  1806                 ) {
  1807                     return true;
  1808                 }
  1809             }
  1810         }
  1811         return false;
  1812     }
  1813 
  1814     private void findParamNames(
  1815         Set<String> params, Element e, String url, String jsonParam, StringBuilder... both
  1816     ) {
  1817         int wasJSON = 0;
  1818 
  1819         for (int pos = 0; ;) {
  1820             int next = url.indexOf('{', pos);
  1821             if (next == -1) {
  1822                 both[wasJSON].append('"')
  1823                     .append(url.substring(pos).replace("\"", "\\\""))
  1824                     .append('"');
  1825                 return;
  1826             }
  1827             int close = url.indexOf('}', next);
  1828             if (close == -1) {
  1829                 error("Unbalanced '{' and '}' in " + url, e);
  1830                 return;
  1831             }
  1832             final String paramName = url.substring(next + 1, close);
  1833             params.add(paramName);
  1834             if (paramName.equals(jsonParam) && !jsonParam.isEmpty()) {
  1835                 both[wasJSON].append('"')
  1836                     .append(url.substring(pos, next).replace("\"", "\\\""))
  1837                     .append('"');
  1838                 wasJSON = 1;
  1839             } else {
  1840                 both[wasJSON].append('"')
  1841                     .append(url.substring(pos, next).replace("\"", "\\\""))
  1842                     .append("\" + ").append(paramName).append(" + ");
  1843             }
  1844             pos = close + 1;
  1845         }
  1846     }
  1847 
  1848     private static Prprt findPrprt(Prprt[] properties, String propName) {
  1849         for (Prprt p : properties) {
  1850             if (propName.equals(p.name())) {
  1851                 return p;
  1852             }
  1853         }
  1854         return null;
  1855     }
  1856 
  1857     private boolean isPrimitive(String type) {
  1858         return
  1859             "int".equals(type) ||
  1860             "double".equals(type) ||
  1861             "long".equals(type) ||
  1862             "short".equals(type) ||
  1863             "byte".equals(type) ||
  1864             "char".equals(type) ||
  1865             "boolean".equals(type) ||
  1866             "float".equals(type);
  1867     }
  1868 
  1869     private static Collection<String> findDerivedFrom(Map<String, Collection<String[]>> propsDeps, String derivedProp) {
  1870         Set<String> names = new HashSet<String>();
  1871         for (Map.Entry<String, Collection<String[]>> e : propsDeps.entrySet()) {
  1872             for (String[] pair : e.getValue()) {
  1873                 if (pair[0].equals(derivedProp)) {
  1874                     names.add(e.getKey());
  1875                     break;
  1876                 }
  1877             }
  1878         }
  1879         return names;
  1880     }
  1881 
  1882     private Prprt[] createProps(Element e, Property[] arr) {
  1883         Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
  1884         Prprt[] prev = verify.put(e, ret);
  1885         if (prev != null) {
  1886             error("Two sets of properties for ", e);
  1887         }
  1888         return ret;
  1889     }
  1890 
  1891     private static String strip(String s) {
  1892         int indx = s.indexOf("__");
  1893         if (indx >= 0) {
  1894             return s.substring(0, indx);
  1895         } else {
  1896             return s;
  1897         }
  1898     }
  1899 
  1900     private String findDataSpecified(ExecutableElement e, OnReceive onR) {
  1901         try {
  1902             return onR.data().getName();
  1903         } catch (MirroredTypeException ex) {
  1904             final TypeMirror tm = ex.getTypeMirror();
  1905             String name;
  1906             final Element te = processingEnv.getTypeUtils().asElement(tm);
  1907             if (te.getKind() == ElementKind.CLASS && tm.getKind() == TypeKind.ERROR) {
  1908                 name = te.getSimpleName().toString();
  1909             } else {
  1910                 name = tm.toString();
  1911             }
  1912             return "java.lang.Object".equals(name) ? null : name;
  1913         } catch (Exception ex) {
  1914             // fallback
  1915         }
  1916 
  1917         AnnotationMirror found = null;
  1918         for (AnnotationMirror am : e.getAnnotationMirrors()) {
  1919             if (am.getAnnotationType().toString().equals(OnReceive.class.getName())) {
  1920                 found = am;
  1921             }
  1922         }
  1923         if (found == null) {
  1924             return null;
  1925         }
  1926 
  1927         for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : found.getElementValues().entrySet()) {
  1928             ExecutableElement ee = entry.getKey();
  1929             AnnotationValue av = entry.getValue();
  1930             if (ee.getSimpleName().contentEquals("data")) {
  1931                 List<? extends Object> values = getAnnoValues(processingEnv, e, found);
  1932                 for (Object v : values) {
  1933                     String sv = v.toString();
  1934                     if (sv.startsWith("data = ") && sv.endsWith(".class")) {
  1935                         return sv.substring(7, sv.length() - 6);
  1936                     }
  1937                 }
  1938                 return "error";
  1939             }
  1940         }
  1941         return null;
  1942     }
  1943 
  1944     static List<? extends Object> getAnnoValues(ProcessingEnvironment pe, Element e, AnnotationMirror am) {
  1945         try {
  1946             Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
  1947             Method m = trees.getMethod("instance", ProcessingEnvironment.class);
  1948             Object instance = m.invoke(null, pe);
  1949             m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
  1950             Object path = m.invoke(instance, e, am);
  1951             m = path.getClass().getMethod("getLeaf");
  1952             Object leaf = m.invoke(path);
  1953             m = leaf.getClass().getMethod("getArguments");
  1954             return (List) m.invoke(leaf);
  1955         } catch (Exception ex) {
  1956             return Collections.emptyList();
  1957         }
  1958     }
  1959 
  1960     private static String findTargetId(Element e) {
  1961         for (AnnotationMirror m : e.getAnnotationMirrors()) {
  1962             if (m.getAnnotationType().toString().equals(Model.class.getName())) {
  1963                 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entrySet : m.getElementValues().entrySet()) {
  1964                     ExecutableElement key = entrySet.getKey();
  1965                     AnnotationValue value = entrySet.getValue();
  1966                     if ("targetId()".equals(key.toString())) {
  1967                         return value.toString();
  1968                     }
  1969                 }
  1970             }
  1971         }
  1972         return null;
  1973     }
  1974 
  1975     private static class Prprt {
  1976         private final Element e;
  1977         private final AnnotationMirror tm;
  1978         private final Property p;
  1979 
  1980         public Prprt(Element e, AnnotationMirror tm, Property p) {
  1981             this.e = e;
  1982             this.tm = tm;
  1983             this.p = p;
  1984         }
  1985 
  1986         String name() {
  1987             return p.name();
  1988         }
  1989 
  1990         boolean array() {
  1991             return p.array();
  1992         }
  1993 
  1994         String typeName(ProcessingEnvironment env) {
  1995             RuntimeException ex;
  1996             try {
  1997                 return p.type().getName();
  1998             } catch (IncompleteAnnotationException e) {
  1999                 ex = e;
  2000             } catch (AnnotationTypeMismatchException e) {
  2001                 ex = e;
  2002             }
  2003             for (Object v : getAnnoValues(env, e, tm)) {
  2004                 String s = v.toString().replace(" ", "");
  2005                 if (s.startsWith("type=") && s.endsWith(".class")) {
  2006                     return s.substring(5, s.length() - 6);
  2007                 }
  2008             }
  2009             throw ex;
  2010         }
  2011 
  2012 
  2013         static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
  2014             if (arr.length == 0) {
  2015                 return new Prprt[0];
  2016             }
  2017 
  2018             if (e.getKind() != ElementKind.CLASS) {
  2019                 throw new IllegalStateException("" + e.getKind());
  2020             }
  2021             TypeElement te = (TypeElement)e;
  2022             List<? extends AnnotationValue> val = null;
  2023             for (AnnotationMirror an : te.getAnnotationMirrors()) {
  2024                 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
  2025                     if (entry.getKey().getSimpleName().contentEquals("properties")) {
  2026                         val = (List)entry.getValue().getValue();
  2027                         break;
  2028                     }
  2029                 }
  2030             }
  2031             if (val == null || val.size() != arr.length) {
  2032                 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
  2033                 return new Prprt[0];
  2034             }
  2035             Prprt[] ret = new Prprt[arr.length];
  2036             BIG: for (int i = 0; i < ret.length; i++) {
  2037                 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
  2038                 ret[i] = new Prprt(e, am, arr[i]);
  2039 
  2040             }
  2041             return ret;
  2042         }
  2043     } // end of Prprt
  2044 
  2045     private static final class GetSet {
  2046         final String name;
  2047         final String getter;
  2048         final String setter;
  2049         final String type;
  2050         final boolean readOnly;
  2051         GetSet(String name, String getter, String setter, String type, boolean readOnly) {
  2052             this.name = name;
  2053             this.getter = getter;
  2054             this.setter = setter;
  2055             this.type = type;
  2056             this.readOnly = readOnly;
  2057         }
  2058     }
  2059 
  2060     @Override
  2061     public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
  2062         final Level l = Level.FINE;
  2063         LOG.log(l, " element: {0}", element);
  2064         LOG.log(l, " annotation: {0}", annotation);
  2065         LOG.log(l, " member: {0}", member);
  2066         LOG.log(l, " userText: {0}", userText);
  2067         LOG.log(l, "str: {0}", annotation.getAnnotationType().toString());
  2068         if (annotation.getAnnotationType().toString().equals(OnReceive.class.getName())) {
  2069             if (member.getSimpleName().contentEquals("method")) {
  2070                 return Arrays.asList(
  2071                     methodOf("GET"),
  2072                     methodOf("POST"),
  2073                     methodOf("PUT"),
  2074                     methodOf("DELETE"),
  2075                     methodOf("HEAD"),
  2076                     methodOf("WebSocket")
  2077                 );
  2078             }
  2079         }
  2080 
  2081         return super.getCompletions(element, annotation, member, userText);
  2082     }
  2083 
  2084     private static final Completion methodOf(String method) {
  2085         ResourceBundle rb = ResourceBundle.getBundle("org.netbeans.html.json.impl.Bundle");
  2086         return Completions.of('"' + method + '"', rb.getString("MSG_Completion_" + method));
  2087     }
  2088 
  2089     private boolean findOnError(ExecutableElement errElem, TypeElement te, String name, String className) {
  2090         String err = null;
  2091         METHODS:
  2092         for (Element e : te.getEnclosedElements()) {
  2093             if (e.getKind() != ElementKind.METHOD) {
  2094                 continue;
  2095             }
  2096             if (!e.getSimpleName().contentEquals(name)) {
  2097                 continue;
  2098             }
  2099             if (!e.getModifiers().contains(Modifier.STATIC)) {
  2100                 errElem = (ExecutableElement) e;
  2101                 err = "Would have to be static";
  2102                 continue;
  2103             }
  2104             ExecutableElement ee = (ExecutableElement) e;
  2105             TypeMirror excType = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
  2106             final List<? extends VariableElement> params = ee.getParameters();
  2107             boolean error = false;
  2108             if (params.size() != 2) {
  2109                 error = true;
  2110             } else {
  2111                 String firstType = params.get(0).asType().toString();
  2112                 int lastDot = firstType.lastIndexOf('.');
  2113                 if (lastDot != -1) {
  2114                     firstType = firstType.substring(lastDot + 1);
  2115                 }
  2116                 if (!firstType.equals(className)) {
  2117                     error = true;
  2118                 }
  2119                 if (!processingEnv.getTypeUtils().isAssignable(excType, params.get(1).asType())) {
  2120                     error = true;
  2121                 }
  2122             }
  2123             if (error) {
  2124                 errElem = (ExecutableElement) e;
  2125                 err = "Error method first argument needs to be " + className + " and second Exception";
  2126                 continue;
  2127             }
  2128             return true;
  2129         }
  2130         if (err == null) {
  2131             err = "Cannot find " + name + "(" + className + ", Exception) method in this class";
  2132         }
  2133         error(err, errElem);
  2134         return false;
  2135     }
  2136 
  2137     private ExecutableElement findWrite(ExecutableElement computedPropElem, TypeElement te, String name, String className) {
  2138         String err = null;
  2139         METHODS:
  2140         for (Element e : te.getEnclosedElements()) {
  2141             if (e.getKind() != ElementKind.METHOD) {
  2142                 continue;
  2143             }
  2144             if (!e.getSimpleName().contentEquals(name)) {
  2145                 continue;
  2146             }
  2147             if (e.equals(computedPropElem)) {
  2148                 continue;
  2149             }
  2150             if (!e.getModifiers().contains(Modifier.STATIC)) {
  2151                 computedPropElem = (ExecutableElement) e;
  2152                 err = "Would have to be static";
  2153                 continue;
  2154             }
  2155             ExecutableElement ee = (ExecutableElement) e;
  2156             if (ee.getReturnType().getKind() != TypeKind.VOID) {
  2157                 computedPropElem = (ExecutableElement) e;
  2158                 err = "Write method has to return void";
  2159                 continue;
  2160             }
  2161             TypeMirror retType = computedPropElem.getReturnType();
  2162             final List<? extends VariableElement> params = ee.getParameters();
  2163             boolean error = false;
  2164             if (params.size() != 2) {
  2165                 error = true;
  2166             } else {
  2167                 String firstType = params.get(0).asType().toString();
  2168                 int lastDot = firstType.lastIndexOf('.');
  2169                 if (lastDot != -1) {
  2170                     firstType = firstType.substring(lastDot + 1);
  2171                 }
  2172                 if (!firstType.equals(className)) {
  2173                     error = true;
  2174                 }
  2175                 if (!processingEnv.getTypeUtils().isAssignable(retType, params.get(1).asType())) {
  2176                     error = true;
  2177                 }
  2178             }
  2179             if (error) {
  2180                 computedPropElem = (ExecutableElement) e;
  2181                 err = "Write method first argument needs to be " + className + " and second " + retType + " or Object";
  2182                 continue;
  2183             }
  2184             return ee;
  2185         }
  2186         if (err == null) {
  2187             err = "Cannot find " + name + "(" + className + ", value) method in this class";
  2188         }
  2189         error(err, computedPropElem);
  2190         return null;
  2191     }
  2192 
  2193 }