javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Jan 2013 14:29:10 +0100
branchmodel
changeset 491 14268cd404a4
parent 490 e089ef6785c0
child 492 854286e49061
permissions -rw-r--r--
The model can contain derived properties
     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.Collection;
    26 import java.util.Collections;
    27 import java.util.List;
    28 import java.util.Locale;
    29 import java.util.Set;
    30 import javax.annotation.processing.AbstractProcessor;
    31 import javax.annotation.processing.Completion;
    32 import javax.annotation.processing.Completions;
    33 import javax.annotation.processing.Processor;
    34 import javax.annotation.processing.RoundEnvironment;
    35 import javax.annotation.processing.SupportedAnnotationTypes;
    36 import javax.lang.model.element.AnnotationMirror;
    37 import javax.lang.model.element.Element;
    38 import javax.lang.model.element.ElementKind;
    39 import javax.lang.model.element.ExecutableElement;
    40 import javax.lang.model.element.Modifier;
    41 import javax.lang.model.element.PackageElement;
    42 import javax.lang.model.element.TypeElement;
    43 import javax.lang.model.element.VariableElement;
    44 import javax.lang.model.type.MirroredTypeException;
    45 import javax.lang.model.type.TypeMirror;
    46 import javax.tools.Diagnostic;
    47 import javax.tools.FileObject;
    48 import javax.tools.StandardLocation;
    49 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    50 import org.apidesign.bck2brwsr.htmlpage.api.On;
    51 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    52 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    53 import org.openide.util.lookup.ServiceProvider;
    54 
    55 /** Annotation processor to process an XHTML page and generate appropriate 
    56  * "id" file.
    57  *
    58  * @author Jaroslav Tulach <jtulach@netbeans.org>
    59  */
    60 @ServiceProvider(service=Processor.class)
    61 @SupportedAnnotationTypes({
    62     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    63     "org.apidesign.bck2brwsr.htmlpage.api.On"
    64 })
    65 public final class PageProcessor extends AbstractProcessor {
    66     @Override
    67     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    68         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    69             Page p = e.getAnnotation(Page.class);
    70             PackageElement pe = (PackageElement)e.getEnclosingElement();
    71             String pkg = pe.getQualifiedName().toString();
    72             
    73             ProcessPage pp;
    74             try {
    75                 InputStream is = openStream(pkg, p.xhtml());
    76                 pp = ProcessPage.readPage(is);
    77                 is.close();
    78             } catch (IOException iOException) {
    79                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    80                 return false;
    81             }
    82             Writer w;
    83             String className = p.className();
    84             if (className.isEmpty()) {
    85                 int indx = p.xhtml().indexOf('.');
    86                 className = p.xhtml().substring(0, indx);
    87             }
    88             try {
    89                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    90                 w = new OutputStreamWriter(java.openOutputStream());
    91                 try {
    92                     w.append("package " + pkg + ";\n");
    93                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
    94                     w.append("class ").append(className).append(" {\n");
    95                     for (String id : pp.ids()) {
    96                         String tag = pp.tagNameForId(id);
    97                         String type = type(tag);
    98                         w.append("  ").append("public static final ").
    99                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   100                             append(type).append("(\"").append(id).append("\");\n");
   101                     }
   102                     w.append("  static {\n");
   103                     if (!initializeOnClick((TypeElement) e, w, pp)) {
   104                         return false;
   105                     }
   106                     w.append("  }\n");
   107                     generateProperties(w, p.properties());
   108                     generateComputedProperties(w, e.getEnclosedElements());
   109                     w.append("}\n");
   110                 } finally {
   111                     w.close();
   112                 }
   113             } catch (IOException ex) {
   114                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   115                 return false;
   116             }
   117         }
   118         return true;
   119     }
   120 
   121     private InputStream openStream(String pkg, String name) throws IOException {
   122         try {
   123             FileObject fo = processingEnv.getFiler().getResource(
   124                 StandardLocation.SOURCE_PATH, pkg, name);
   125             return fo.openInputStream();
   126         } catch (IOException ex) {
   127             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   128         }
   129     }
   130 
   131     private static String type(String tag) {
   132         if (tag.equals("title")) {
   133             return "Title";
   134         }
   135         if (tag.equals("button")) {
   136             return "Button";
   137         }
   138         if (tag.equals("input")) {
   139             return "Input";
   140         }
   141         return "Element";
   142     }
   143 
   144     private static String cnstnt(String id) {
   145         return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
   146     }
   147 
   148     private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
   149         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   150         { //for (Element clazz : pe.getEnclosedElements()) {
   151           //  if (clazz.getKind() != ElementKind.CLASS) {
   152             //    continue;
   153            // }
   154             for (Element method : type.getEnclosedElements()) {
   155                 On oc = method.getAnnotation(On.class);
   156                 if (oc != null) {
   157                     for (String id : oc.id()) {
   158                         if (pp.tagNameForId(id) == null) {
   159                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   160                             return false;
   161                         }
   162                         ExecutableElement ee = (ExecutableElement)method;
   163                         boolean hasParam;
   164                         if (ee.getParameters().isEmpty()) {
   165                             hasParam = false;
   166                         } else {
   167                             if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
   168                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
   169                                 return false;
   170                             }
   171                             hasParam = true;
   172                         }
   173                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   174                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   175                             return false;
   176                         }
   177                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   178                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   179                             return false;
   180                         }
   181                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   182                             append(").perform(new Runnable() { public void run() {\n");
   183                         w.append("    ").append(type.getSimpleName().toString()).
   184                             append('.').append(ee.getSimpleName()).append("(");
   185                         if (hasParam) {
   186                             w.append("\"").append(id).append("\"");
   187                         }
   188                         w.append(");\n");
   189                         w.append("  }});\n");
   190                     }           
   191                 }
   192             }
   193         }
   194         return true;
   195     }
   196 
   197     @Override
   198     public Iterable<? extends Completion> getCompletions(
   199         Element element, AnnotationMirror annotation, 
   200         ExecutableElement member, String userText
   201     ) {
   202         if (!userText.startsWith("\"")) {
   203             return Collections.emptyList();
   204         }
   205         
   206         Element cls = findClass(element);
   207         Page p = cls.getAnnotation(Page.class);
   208         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   209         String pkg = pe.getQualifiedName().toString();
   210         ProcessPage pp;
   211         try {
   212             InputStream is = openStream(pkg, p.xhtml());
   213             pp = ProcessPage.readPage(is);
   214             is.close();
   215         } catch (IOException iOException) {
   216             return Collections.emptyList();
   217         }
   218         
   219         List<Completion> cc = new ArrayList<Completion>();
   220         userText = userText.substring(1);
   221         for (String id : pp.ids()) {
   222             if (id.startsWith(userText)) {
   223                 cc.add(Completions.of("\"" + id + "\"", id));
   224             }
   225         }
   226         return cc;
   227     }
   228     
   229     private static Element findClass(Element e) {
   230         if (e == null) {
   231             return null;
   232         }
   233         Page p = e.getAnnotation(Page.class);
   234         if (p != null) {
   235             return e;
   236         }
   237         return e.getEnclosingElement();
   238     }
   239 
   240     private static void generateProperties(Writer w, Property[] properties) throws IOException {
   241         for (Property p : properties) {
   242             String[] gs = toGetSet(p.name(), null);
   243 
   244             final String tn = typeName(p);
   245             w.write("private static " + tn + " prop_" + p.name() + ";\n");
   246             w.write("public static " + tn + " " + gs[0] + "() {\n");
   247             w.write("  return prop_" + p.name() + ";\n");
   248             w.write("}\n");
   249             w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
   250             w.write("  prop_" + p.name() + " = v;\n");
   251             w.write("}\n");
   252         }
   253     }
   254 
   255     private void generateComputedProperties(Writer w, Collection<? extends Element> arr) throws IOException {
   256         for (Element e : arr) {
   257             if (e.getKind() != ElementKind.METHOD) {
   258                 continue;
   259             }
   260             if (e.getAnnotation(ComputedProperty.class) == null) {
   261                 continue;
   262             }
   263             ExecutableElement ee = (ExecutableElement)e;
   264             String[] gs = toGetSet(ee.getSimpleName().toString(), null);
   265 
   266             final String tn = ee.getReturnType().toString();
   267             w.write("public static " + tn + " " + gs[0] + "() {\n");
   268             w.write("  return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   269             String sep = "";
   270             for (VariableElement pe : ee.getParameters()) {
   271                 String[] call = toGetSet(pe.getSimpleName().toString(), null);
   272                 w.write(sep);
   273                 w.write(call[0] + "()");
   274                 sep = ", ";
   275             }
   276             w.write(");\n");
   277             w.write("}\n");
   278         }
   279     }
   280 
   281     private static String[] toGetSet(String name, Object type) {
   282         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   283 //        if (p.type() == boolean.class) {
   284 //            return new String[] { "is" + n, "set" + n };
   285 //        } else {
   286         return new String[]{"get" + n, "set" + n};
   287 //        }
   288     }
   289 
   290     private static String typeName(Property p) {
   291         try {
   292             return p.type().getName();
   293         } catch (MirroredTypeException ex) {
   294             if (ex.getTypeMirror().getKind().isPrimitive()) {
   295                 return ex.getTypeMirror().toString();
   296             }
   297             throw ex;
   298         }
   299     }
   300 }