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