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