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