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