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