Basic support for knockout.js. It can read and write model properties.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
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.
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.
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.
18 package org.apidesign.bck2brwsr.htmlpage;
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;
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;
55 /** Annotation processor to process an XHTML page and generate appropriate
58 * @author Jaroslav Tulach <jtulach@netbeans.org>
60 @ServiceProvider(service=Processor.class)
61 @SupportedAnnotationTypes({
62 "org.apidesign.bck2brwsr.htmlpage.api.Page",
63 "org.apidesign.bck2brwsr.htmlpage.api.On"
65 public final class PageProcessor extends AbstractProcessor {
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();
75 InputStream is = openStream(pkg, p.xhtml());
76 pp = ProcessPage.readPage(is);
78 } catch (IOException iOException) {
79 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
83 String className = p.className();
84 if (className.isEmpty()) {
85 int indx = p.xhtml().indexOf('.');
86 className = p.xhtml().substring(0, indx);
89 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
90 w = new OutputStreamWriter(java.openOutputStream());
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 w.append(" private ").append(className).append("() {}\n");
96 for (String id : pp.ids()) {
97 String tag = pp.tagNameForId(id);
98 String type = type(tag);
99 w.append(" ").append("public static final ").
100 append(type).append(' ').append(cnstnt(id)).append(" = new ").
101 append(type).append("(\"").append(id).append("\");\n");
103 w.append(" static {\n");
104 if (!initializeOnClick((TypeElement) e, w, pp)) {
108 List<String> propsGetSet = new ArrayList<String>();
109 generateProperties(w, p.properties(), propsGetSet);
110 generateComputedProperties(w, e.getEnclosedElements(), propsGetSet);
111 if (!propsGetSet.isEmpty()) {
112 w.write("public static void applyBindings() {\n");
113 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
114 w.write(className + ".class, new " + className + "(), ");
115 w.write("new String[] {\n");
117 for (String n : propsGetSet) {
122 w.write(" \"" + n + "\"");
126 w.write("\n });\n}\n");
127 //w.write("static { applyBindings(); }\n");
133 } catch (IOException ex) {
134 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
141 private InputStream openStream(String pkg, String name) throws IOException {
143 FileObject fo = processingEnv.getFiler().getResource(
144 StandardLocation.SOURCE_PATH, pkg, name);
145 return fo.openInputStream();
146 } catch (IOException ex) {
147 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
151 private static String type(String tag) {
152 if (tag.equals("title")) {
155 if (tag.equals("button")) {
158 if (tag.equals("input")) {
164 private static String cnstnt(String id) {
165 return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
168 private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
169 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
170 { //for (Element clazz : pe.getEnclosedElements()) {
171 // if (clazz.getKind() != ElementKind.CLASS) {
174 for (Element method : type.getEnclosedElements()) {
175 On oc = method.getAnnotation(On.class);
177 for (String id : oc.id()) {
178 if (pp.tagNameForId(id) == null) {
179 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
182 ExecutableElement ee = (ExecutableElement)method;
184 if (ee.getParameters().isEmpty()) {
187 if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
188 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
193 if (!ee.getModifiers().contains(Modifier.STATIC)) {
194 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
197 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
198 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
201 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
202 append(").perform(new Runnable() { public void run() {\n");
203 w.append(" ").append(type.getSimpleName().toString()).
204 append('.').append(ee.getSimpleName()).append("(");
206 w.append("\"").append(id).append("\"");
218 public Iterable<? extends Completion> getCompletions(
219 Element element, AnnotationMirror annotation,
220 ExecutableElement member, String userText
222 if (!userText.startsWith("\"")) {
223 return Collections.emptyList();
226 Element cls = findClass(element);
227 Page p = cls.getAnnotation(Page.class);
228 PackageElement pe = (PackageElement) cls.getEnclosingElement();
229 String pkg = pe.getQualifiedName().toString();
232 InputStream is = openStream(pkg, p.xhtml());
233 pp = ProcessPage.readPage(is);
235 } catch (IOException iOException) {
236 return Collections.emptyList();
239 List<Completion> cc = new ArrayList<Completion>();
240 userText = userText.substring(1);
241 for (String id : pp.ids()) {
242 if (id.startsWith(userText)) {
243 cc.add(Completions.of("\"" + id + "\"", id));
249 private static Element findClass(Element e) {
253 Page p = e.getAnnotation(Page.class);
257 return e.getEnclosingElement();
260 private static void generateProperties(
261 Writer w, Property[] properties, Collection<String> props
262 ) throws IOException {
263 for (Property p : properties) {
264 final String tn = typeName(p);
265 String[] gs = toGetSet(p.name(), tn);
267 w.write("private static " + tn + " prop_" + p.name() + ";\n");
268 w.write("public static " + tn + " " + gs[0] + "() {\n");
269 w.write(" return prop_" + p.name() + ";\n");
271 w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
272 w.write(" prop_" + p.name() + " = v;\n");
281 private void generateComputedProperties(
282 Writer w, Collection<? extends Element> arr, Collection<String> props
283 ) throws IOException {
284 for (Element e : arr) {
285 if (e.getKind() != ElementKind.METHOD) {
288 if (e.getAnnotation(ComputedProperty.class) == null) {
291 ExecutableElement ee = (ExecutableElement)e;
292 final String tn = ee.getReturnType().toString();
293 String[] gs = toGetSet(ee.getSimpleName().toString(), tn);
295 w.write("public static " + tn + " " + gs[0] + "() {\n");
296 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
298 for (VariableElement pe : ee.getParameters()) {
299 String[] call = toGetSet(pe.getSimpleName().toString(), pe.asType().toString());
301 w.write(call[0] + "()");
307 props.add(e.getSimpleName().toString());
313 private static String[] toGetSet(String name, String type) {
314 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
315 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
316 if ("int".equals(type)) {
319 if ("double".equals(type)) {
323 if ("boolean".equals(type)) {
330 pref + n + "__" + bck2brwsrType,
331 "set" + n + "__V" + bck2brwsrType
335 private static String typeName(Property p) {
337 return p.type().getName();
338 } catch (MirroredTypeException ex) {
339 if (ex.getTypeMirror().getKind().isPrimitive()) {
340 return ex.getTypeMirror().toString();