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