javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Jan 2013 13:05:02 +0100
branchmodel
changeset 490 e089ef6785c0
parent 489 4b59fa013d49
child 491 14268cd404a4
permissions -rw-r--r--
Annotation to generate getters and setters
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.OutputStreamWriter;
    23 import java.io.Writer;
    24 import java.util.ArrayList;
    25 import java.util.Collections;
    26 import java.util.List;
    27 import java.util.Locale;
    28 import java.util.Set;
    29 import javax.annotation.processing.AbstractProcessor;
    30 import javax.annotation.processing.Completion;
    31 import javax.annotation.processing.Completions;
    32 import javax.annotation.processing.Processor;
    33 import javax.annotation.processing.RoundEnvironment;
    34 import javax.annotation.processing.SupportedAnnotationTypes;
    35 import javax.lang.model.element.AnnotationMirror;
    36 import javax.lang.model.element.Element;
    37 import javax.lang.model.element.ExecutableElement;
    38 import javax.lang.model.element.Modifier;
    39 import javax.lang.model.element.PackageElement;
    40 import javax.lang.model.element.TypeElement;
    41 import javax.lang.model.type.MirroredTypeException;
    42 import javax.lang.model.type.TypeMirror;
    43 import javax.tools.Diagnostic;
    44 import javax.tools.FileObject;
    45 import javax.tools.StandardLocation;
    46 import org.apidesign.bck2brwsr.htmlpage.api.On;
    47 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    48 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    49 import org.openide.util.lookup.ServiceProvider;
    50 
    51 /** Annotation processor to process an XHTML page and generate appropriate 
    52  * "id" file.
    53  *
    54  * @author Jaroslav Tulach <jtulach@netbeans.org>
    55  */
    56 @ServiceProvider(service=Processor.class)
    57 @SupportedAnnotationTypes({
    58     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    59     "org.apidesign.bck2brwsr.htmlpage.api.On"
    60 })
    61 public final class PageProcessor extends AbstractProcessor {
    62     @Override
    63     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    64         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    65             Page p = e.getAnnotation(Page.class);
    66             PackageElement pe = (PackageElement)e.getEnclosingElement();
    67             String pkg = pe.getQualifiedName().toString();
    68             
    69             ProcessPage pp;
    70             try {
    71                 InputStream is = openStream(pkg, p.xhtml());
    72                 pp = ProcessPage.readPage(is);
    73                 is.close();
    74             } catch (IOException iOException) {
    75                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    76                 return false;
    77             }
    78             Writer w;
    79             String className = p.className();
    80             if (className.isEmpty()) {
    81                 int indx = p.xhtml().indexOf('.');
    82                 className = p.xhtml().substring(0, indx);
    83             }
    84             try {
    85                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    86                 w = new OutputStreamWriter(java.openOutputStream());
    87                 try {
    88                     w.append("package " + pkg + ";\n");
    89                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
    90                     w.append("class ").append(className).append(" {\n");
    91                     for (String id : pp.ids()) {
    92                         String tag = pp.tagNameForId(id);
    93                         String type = type(tag);
    94                         w.append("  ").append("public static final ").
    95                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
    96                             append(type).append("(\"").append(id).append("\");\n");
    97                     }
    98                     w.append("  static {\n");
    99                     if (!initializeOnClick((TypeElement) e, w, pp)) {
   100                         return false;
   101                     }
   102                     w.append("  }\n");
   103                     generateProperties(w, p.properties());
   104                     w.append("}\n");
   105                 } finally {
   106                     w.close();
   107                 }
   108             } catch (IOException ex) {
   109                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   110                 return false;
   111             }
   112         }
   113         return true;
   114     }
   115 
   116     private InputStream openStream(String pkg, String name) throws IOException {
   117         try {
   118             FileObject fo = processingEnv.getFiler().getResource(
   119                 StandardLocation.SOURCE_PATH, pkg, name);
   120             return fo.openInputStream();
   121         } catch (IOException ex) {
   122             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   123         }
   124     }
   125 
   126     private static String type(String tag) {
   127         if (tag.equals("title")) {
   128             return "Title";
   129         }
   130         if (tag.equals("button")) {
   131             return "Button";
   132         }
   133         if (tag.equals("input")) {
   134             return "Input";
   135         }
   136         return "Element";
   137     }
   138 
   139     private static String cnstnt(String id) {
   140         return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
   141     }
   142 
   143     private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
   144         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   145         { //for (Element clazz : pe.getEnclosedElements()) {
   146           //  if (clazz.getKind() != ElementKind.CLASS) {
   147             //    continue;
   148            // }
   149             for (Element method : type.getEnclosedElements()) {
   150                 On oc = method.getAnnotation(On.class);
   151                 if (oc != null) {
   152                     for (String id : oc.id()) {
   153                         if (pp.tagNameForId(id) == null) {
   154                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   155                             return false;
   156                         }
   157                         ExecutableElement ee = (ExecutableElement)method;
   158                         boolean hasParam;
   159                         if (ee.getParameters().isEmpty()) {
   160                             hasParam = false;
   161                         } else {
   162                             if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
   163                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
   164                                 return false;
   165                             }
   166                             hasParam = true;
   167                         }
   168                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   169                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   170                             return false;
   171                         }
   172                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   173                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   174                             return false;
   175                         }
   176                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   177                             append(").perform(new Runnable() { public void run() {\n");
   178                         w.append("    ").append(type.getSimpleName().toString()).
   179                             append('.').append(ee.getSimpleName()).append("(");
   180                         if (hasParam) {
   181                             w.append("\"").append(id).append("\"");
   182                         }
   183                         w.append(");\n");
   184                         w.append("  }});\n");
   185                     }           
   186                 }
   187             }
   188         }
   189         return true;
   190     }
   191 
   192     @Override
   193     public Iterable<? extends Completion> getCompletions(
   194         Element element, AnnotationMirror annotation, 
   195         ExecutableElement member, String userText
   196     ) {
   197         if (!userText.startsWith("\"")) {
   198             return Collections.emptyList();
   199         }
   200         
   201         Element cls = findClass(element);
   202         Page p = cls.getAnnotation(Page.class);
   203         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   204         String pkg = pe.getQualifiedName().toString();
   205         ProcessPage pp;
   206         try {
   207             InputStream is = openStream(pkg, p.xhtml());
   208             pp = ProcessPage.readPage(is);
   209             is.close();
   210         } catch (IOException iOException) {
   211             return Collections.emptyList();
   212         }
   213         
   214         List<Completion> cc = new ArrayList<Completion>();
   215         userText = userText.substring(1);
   216         for (String id : pp.ids()) {
   217             if (id.startsWith(userText)) {
   218                 cc.add(Completions.of("\"" + id + "\"", id));
   219             }
   220         }
   221         return cc;
   222     }
   223     
   224     private static Element findClass(Element e) {
   225         if (e == null) {
   226             return null;
   227         }
   228         Page p = e.getAnnotation(Page.class);
   229         if (p != null) {
   230             return e;
   231         }
   232         return e.getEnclosingElement();
   233     }
   234 
   235     private static void generateProperties(Writer w, Property[] properties) throws IOException {
   236         for (Property p : properties) {
   237             String[] gs = toGetSet(p);
   238 
   239             final String tn = typeName(p);
   240             w.write("private static " + tn + " prop_" + p.name() + ";\n");
   241             w.write("public static " + tn + " " + gs[0] + "() {\n");
   242             w.write("  return prop_" + p.name() + ";\n");
   243             w.write("}\n");
   244             w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
   245             w.write("  prop_" + p.name() + " = v;\n");
   246             w.write("}\n");
   247         }
   248     }
   249 
   250     private static String[] toGetSet(Property p) {
   251         String n = Character.toUpperCase(p.name().charAt(0)) + p.name().substring(1);
   252 //        if (p.type() == boolean.class) {
   253 //            return new String[] { "is" + n, "set" + n };
   254 //        } else {
   255         return new String[]{"get" + n, "set" + n};
   256 //        }
   257     }
   258 
   259     private static String typeName(Property p) {
   260         try {
   261             return p.type().getName();
   262         } catch (MirroredTypeException ex) {
   263             if (ex.getTypeMirror().getKind().isPrimitive()) {
   264                 return ex.getTypeMirror().toString();
   265             }
   266             throw ex;
   267         }
   268     }
   269 }