javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 16 Jan 2013 12:27:53 +0100
branchdew
changeset 467 c50c541368f8
parent 463 3641fd0663d3
parent 435 fb4ed6cc0d4b
child 543 1adce93fea0f
permissions -rw-r--r--
Merge with recent advances in default branch
     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.ElementKind;
    38 import javax.lang.model.element.ExecutableElement;
    39 import javax.lang.model.element.Modifier;
    40 import javax.lang.model.element.PackageElement;
    41 import javax.lang.model.element.TypeElement;
    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.openide.util.lookup.ServiceProvider;
    49 
    50 /** Annotation processor to process an XHTML page and generate appropriate 
    51  * "id" file.
    52  *
    53  * @author Jaroslav Tulach <jtulach@netbeans.org>
    54  */
    55 @ServiceProvider(service=Processor.class)
    56 @SupportedAnnotationTypes({
    57     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    58     "org.apidesign.bck2brwsr.htmlpage.api.On"
    59 })
    60 public final class PageProcessor extends AbstractProcessor {
    61     @Override
    62     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    63         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    64             Page p = e.getAnnotation(Page.class);
    65             if (p == null) {
    66                 continue;
    67             }
    68             PackageElement pe = (PackageElement)e.getEnclosingElement();
    69             String pkg = pe.getQualifiedName().toString();
    70             
    71             ProcessPage pp;
    72             try {
    73                 InputStream is = openStream(pkg, p.xhtml());
    74                 pp = ProcessPage.readPage(is);
    75                 is.close();
    76             } catch (IOException iOException) {
    77                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    78                 return false;
    79             }
    80             Writer w;
    81             String className = p.className();
    82             if (className.isEmpty()) {
    83                 int indx = p.xhtml().indexOf('.');
    84                 className = p.xhtml().substring(0, indx);
    85             }
    86             try {
    87                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    88                 w = new OutputStreamWriter(java.openOutputStream());
    89                 try {
    90                     w.append("package " + pkg + ";\n");
    91                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
    92                     w.append("class ").append(className).append(" {\n");
    93                     for (String id : pp.ids()) {
    94                         String tag = pp.tagNameForId(id);
    95                         String type = type(tag);
    96                         w.append("  ").append("public static final ").
    97                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
    98                             append(type).append("(\"").append(id).append("\");\n");
    99                     }
   100                     w.append("  static {\n");
   101                     if (!initializeOnClick(pe, w, pp)) {
   102                         return false;
   103                     }
   104                     w.append("  }\n");
   105                     w.append("}\n");
   106                 } finally {
   107                     w.close();
   108                 }
   109             } catch (IOException ex) {
   110                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   111                 return false;
   112             }
   113         }
   114         return true;
   115     }
   116 
   117     private InputStream openStream(String pkg, String name) throws IOException {
   118         try {
   119             FileObject fo = processingEnv.getFiler().getResource(
   120                 StandardLocation.SOURCE_PATH, pkg, name);
   121             return fo.openInputStream();
   122         } catch (IOException ex) {
   123             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   124         }
   125     }
   126 
   127     private static String type(String tag) {
   128         if (tag.equals("title")) {
   129             return "Title";
   130         }
   131         if (tag.equals("button")) {
   132             return "Button";
   133         }
   134         if (tag.equals("input")) {
   135             return "Input";
   136         }
   137         return "Element";
   138     }
   139 
   140     private static String cnstnt(String id) {
   141         return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
   142     }
   143 
   144     private boolean initializeOnClick(PackageElement pe, Writer w, ProcessPage pp) throws IOException {
   145         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   146         for (Element clazz : pe.getEnclosedElements()) {
   147             if (clazz.getKind() != ElementKind.CLASS) {
   148                 continue;
   149             }
   150             TypeElement type = (TypeElement)clazz;
   151             for (Element method : clazz.getEnclosedElements()) {
   152                 On oc = method.getAnnotation(On.class);
   153                 if (oc != null) {
   154                     for (String id : oc.id()) {
   155                         if (pp.tagNameForId(id) == null) {
   156                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   157                             return false;
   158                         }
   159                         ExecutableElement ee = (ExecutableElement)method;
   160                         boolean hasParam;
   161                         if (ee.getParameters().isEmpty()) {
   162                             hasParam = false;
   163                         } else {
   164                             if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
   165                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
   166                                 return false;
   167                             }
   168                             hasParam = true;
   169                         }
   170                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   171                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   172                             return false;
   173                         }
   174                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   175                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   176                             return false;
   177                         }
   178                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   179                             append(").perform(new Runnable() { public void run() {\n");
   180                         w.append("    ").append(type.getSimpleName().toString()).
   181                             append('.').append(ee.getSimpleName()).append("(");
   182                         if (hasParam) {
   183                             w.append("\"").append(id).append("\"");
   184                         }
   185                         w.append(");\n");
   186                         w.append("  }});\n");
   187                     }           
   188                 }
   189             }
   190         }
   191         return true;
   192     }
   193 
   194     @Override
   195     public Iterable<? extends Completion> getCompletions(
   196         Element element, AnnotationMirror annotation, 
   197         ExecutableElement member, String userText
   198     ) {
   199         if (!userText.startsWith("\"")) {
   200             return Collections.emptyList();
   201         }
   202         
   203         Element cls = findClass(element);
   204         Page p = cls.getAnnotation(Page.class);
   205         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   206         String pkg = pe.getQualifiedName().toString();
   207         ProcessPage pp;
   208         try {
   209             InputStream is = openStream(pkg, p.xhtml());
   210             pp = ProcessPage.readPage(is);
   211             is.close();
   212         } catch (IOException iOException) {
   213             return Collections.emptyList();
   214         }
   215         
   216         List<Completion> cc = new ArrayList<Completion>();
   217         userText = userText.substring(1);
   218         for (String id : pp.ids()) {
   219             if (id.startsWith(userText)) {
   220                 cc.add(Completions.of("\"" + id + "\"", id));
   221             }
   222         }
   223         return cc;
   224     }
   225     
   226     private static Element findClass(Element e) {
   227         if (e == null) {
   228             return null;
   229         }
   230         Page p = e.getAnnotation(Page.class);
   231         if (p != null) {
   232             return e;
   233         }
   234         return e.getEnclosingElement();
   235     }
   236 }