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