# HG changeset patch # User Jaroslav Tulach # Date 1365589397 -7200 # Node ID 5c7cdd2b3f8f9f3be7349520409349531d5d9a6c # Parent c75bd6823179051b0ff9ebc4c9f974fd0c20ec58# Parent df60ba2aeb87ee4cebee4ab76fe595db80d48e21 Merge of improved model which allows us to refer to @Model classes diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java Wed Apr 10 12:23:17 2013 +0200 @@ -89,10 +89,12 @@ @JavaScriptBody(args = { "name", "arr", "run" }, body = "if (window[name]) return false;\n " + "window[name] = function(data) {\n " + + " delete window[name];\n" + + " var el = window.document.getElementById(name);\n" + + " el.parentNode.removeChild(el);\n" + " arr[0] = data;\n" + " run.run__V();\n" - + " delete window[name];\n" - + "};" + + "};\n" + "return true;\n" ) private static boolean defineIfUnused(String name, Object[] arr, Runnable run) { diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java Wed Apr 10 12:23:17 2013 +0200 @@ -22,6 +22,8 @@ import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; +import java.lang.annotation.AnnotationTypeMismatchException; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -35,11 +37,12 @@ import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Completion; import javax.annotation.processing.Completions; -import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; @@ -78,10 +81,12 @@ "org.apidesign.bck2brwsr.htmlpage.api.OnFunction", "org.apidesign.bck2brwsr.htmlpage.api.OnReceive", "org.apidesign.bck2brwsr.htmlpage.api.OnPropertyChange", + "org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty", "org.apidesign.bck2brwsr.htmlpage.api.On" }) public final class PageProcessor extends AbstractProcessor { private final Map models = new WeakHashMap<>(); + private final Map verify = new WeakHashMap<>(); @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { boolean ok = true; @@ -97,6 +102,42 @@ } if (roundEnv.processingOver()) { models.clear(); + for (Map.Entry entry : verify.entrySet()) { + TypeElement te = (TypeElement)entry.getKey(); + String fqn = processingEnv.getElementUtils().getBinaryName(te).toString(); + Element finalElem = processingEnv.getElementUtils().getTypeElement(fqn); + if (finalElem == null) { + continue; + } + Prprt[] props; + Model m = finalElem.getAnnotation(Model.class); + if (m != null) { + props = Prprt.wrap(processingEnv, finalElem, m.properties()); + } else { + Page p = finalElem.getAnnotation(Page.class); + props = Prprt.wrap(processingEnv, finalElem, p.properties()); + } + for (Prprt p : props) { + boolean[] isModel = { false }; + boolean[] isEnum = { false }; + boolean[] isPrimitive = { false }; + String t = checkType(p, isModel, isEnum, isPrimitive); + if (isEnum[0]) { + continue; + } + if (isPrimitive[0]) { + continue; + } + if (isModel[0]) { + continue; + } + if ("java.lang.String".equals(t)) { + continue; + } + error("The type " + t + " should be defined by @Model annotation", entry.getKey()); + } + } + verify.clear(); } return ok; } @@ -111,8 +152,8 @@ } } - private Messager err() { - return processingEnv.getMessager(); + private void error(String msg, Element e) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e); } private boolean processModel(Element e) { @@ -131,13 +172,15 @@ List functions = new ArrayList<>(); Map> propsDeps = new HashMap<>(); Map> functionDeps = new HashMap<>(); - if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) { + Prprt[] props = createProps(e, m.properties()); + + if (!generateComputedProperties(body, props, e.getEnclosedElements(), propsGetSet, propsDeps)) { ok = false; } - if (!generateOnChange(e, propsDeps, m.properties(), className, functionDeps)) { + if (!generateOnChange(e, propsDeps, props, className, functionDeps)) { ok = false; } - if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps, functionDeps)) { + if (!generateProperties(e, body, props, propsGetSet, propsDeps, functionDeps)) { ok = false; } if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) { @@ -168,7 +211,7 @@ w.append(" ").append(className).append("(Object json) {\n"); int values = 0; for (int i = 0; i < propsGetSet.size(); i += 4) { - Property p = findProperty(m.properties(), propsGetSet.get(i)); + Prprt p = findPrprt(props, propsGetSet.get(i)); if (p == null) { continue; } @@ -177,7 +220,7 @@ w.append(" Object[] ret = new Object[" + values + "];\n"); w.append(" org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n"); for (int i = 0; i < propsGetSet.size(); i += 4) { - Property p = findProperty(m.properties(), propsGetSet.get(i)); + Prprt p = findPrprt(props, propsGetSet.get(i)); if (p == null) { continue; } @@ -186,24 +229,24 @@ w.append(" }, ret);\n"); for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) { final String pn = propsGetSet.get(i); - Property p = findProperty(m.properties(), pn); + Prprt p = findPrprt(props, pn); if (p == null) { continue; } boolean[] isModel = { false }; boolean[] isEnum = { false }; - String type = checkType(m.properties()[prop++], isModel, isEnum); - if (isEnum[0]) { -// w.append(type).append(".valueOf((String)"); -// close = true; - w.append(" this.prop_").append(pn); - w.append(" = null;\n"); - } else if (p.array()) { + boolean isPrimitive[] = { false }; + String type = checkType(props[prop++], isModel, isEnum, isPrimitive); + if (p.array()) { w.append("if (ret[" + cnt + "] instanceof Object[]) {\n"); w.append(" for (Object e : ((Object[])ret[" + cnt + "])) {\n"); if (isModel[0]) { w.append(" this.prop_").append(pn).append(".add(new "); w.append(type).append("(e));\n"); + } else if (isEnum[0]) { + w.append(" this.prop_").append(pn); + w.append(".add("); + w.append(type).append(".valueOf((String)e));\n"); } else { if (isPrimitive(type)) { w.append(" this.prop_").append(pn).append(".add(((Number)e)."); @@ -216,7 +259,11 @@ w.append(" }\n"); w.append("}\n"); } else { - if (isPrimitive(type)) { + if (isEnum[0]) { + w.append(" this.prop_").append(pn); + w.append(" = "); + w.append(type).append(".valueOf((String)ret[" + cnt + "]);\n"); + } else if (isPrimitive(type)) { w.append(" this.prop_").append(pn); w.append(" = ((Number)").append("ret[" + cnt + "])."); w.append(type).append("Value();\n"); @@ -230,14 +277,14 @@ } w.append(" intKnckt();\n"); w.append(" };\n"); - writeToString(m.properties(), w); - writeClone(className, m.properties(), w); + writeToString(props, w); + writeClone(className, props, w); w.append("}\n"); } finally { w.close(); } } catch (IOException ex) { - err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e); + error("Can't create " + className + ".java", e); return false; } return ok; @@ -256,7 +303,7 @@ pp = ProcessPage.readPage(is); is.close(); } catch (IOException iOException) { - err().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e); + error("Can't read " + p.xhtml() + " as " + iOException.getMessage(), e); ok = false; pp = null; } @@ -272,13 +319,15 @@ List functions = new ArrayList<>(); Map> propsDeps = new HashMap<>(); Map> functionDeps = new HashMap<>(); - if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) { + + Prprt[] props = createProps(e, p.properties()); + if (!generateComputedProperties(body, props, e.getEnclosedElements(), propsGetSet, propsDeps)) { ok = false; } - if (!generateOnChange(e, propsDeps, p.properties(), className, functionDeps)) { + if (!generateOnChange(e, propsDeps, props, className, functionDeps)) { ok = false; } - if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps, functionDeps)) { + if (!generateProperties(e, body, props, propsGetSet, propsDeps, functionDeps)) { ok = false; } if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) { @@ -327,7 +376,7 @@ w.close(); } } catch (IOException ex) { - err().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e); + error("Can't create " + className + ".java", e); return false; } return ok; @@ -373,24 +422,24 @@ if (oc != null) { for (String id : oc.id()) { if (pp == null) { - err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page."); + error("id = " + id + " not found in HTML page.", method); ok = false; continue; } if (pp.tagNameForId(id) == null) { - err().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method); + error("id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method); ok = false; continue; } ExecutableElement ee = (ExecutableElement)method; CharSequence params = wrapParams(ee, id, className, "ev", null); if (!ee.getModifiers().contains(Modifier.STATIC)) { - err().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee); + error("@On method has to be static", ee); ok = false; continue; } if (ee.getModifiers().contains(Modifier.PRIVATE)) { - err().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee); + error("@On method can't be private", ee); ok = false; continue; } @@ -470,13 +519,13 @@ private boolean generateProperties( Element where, - Writer w, Property[] properties, + Writer w, Prprt[] properties, Collection props, Map> deps, Map> functionDeps ) throws IOException { boolean ok = true; - for (Property p : properties) { + for (Prprt p : properties) { final String tn; tn = typeName(where, p); String[] gs = toGetSet(p.name(), tn, p.array()); @@ -546,7 +595,7 @@ } private boolean generateComputedProperties( - Writer w, Property[] fixedProps, + Writer w, Prprt[] fixedProps, Collection arr, Collection props, Map> deps ) throws IOException { @@ -648,27 +697,18 @@ }; } - private String typeName(Element where, Property p) { + private String typeName(Element where, Prprt p) { String ret; boolean[] isModel = { false }; boolean[] isEnum = { false }; - ret = checkType(p, isModel, isEnum); + boolean isPrimitive[] = { false }; + ret = checkType(p, isModel, isEnum, isPrimitive); if (p.array()) { String bt = findBoxedType(ret); if (bt != null) { return bt; } } - if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) { - String bt = findBoxedType(ret); - if (bt == null) { - err().printMessage( - Diagnostic.Kind.ERROR, - "Only primitive types supported in the mapping. Not " + ret, - where - ); - } - } return ret; } @@ -700,20 +740,20 @@ return null; } - private boolean verifyPropName(Element e, String propName, Property[] existingProps) { + private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) { StringBuilder sb = new StringBuilder(); String sep = ""; - for (Property property : existingProps) { - if (property.name().equals(propName)) { + for (Prprt Prprt : existingProps) { + if (Prprt.name().equals(propName)) { return true; } sb.append(sep); sb.append('"'); - sb.append(property.name()); + sb.append(Prprt.name()); sb.append('"'); sep = ", "; } - err().printMessage(Diagnostic.Kind.ERROR, + error( propName + " is not one of known properties: " + sb , e ); @@ -743,21 +783,15 @@ continue; } if (!e.getModifiers().contains(Modifier.STATIC)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e - ); + error("@OnFunction method needs to be static", e); return false; } if (e.getModifiers().contains(Modifier.PRIVATE)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e - ); + error("@OnFunction method cannot be private", e); return false; } if (e.getReturnType().getKind() != TypeKind.VOID) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnFunction method should return void", e - ); + error("@OnFunction method should return void", e); return false; } String n = e.getSimpleName().toString(); @@ -774,7 +808,7 @@ } private boolean generateOnChange(Element clazz, Map> propDeps, - Property[] properties, String className, + Prprt[] properties, String className, Map> functionDeps ) { for (Element m : clazz.getEnclosedElements()) { @@ -787,24 +821,21 @@ continue; } for (String pn : onPC.value()) { - if (findProperty(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) { - err().printMessage(Diagnostic.Kind.ERROR, "No property named '" + pn + "' in the model"); + if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) { + error("No Prprt named '" + pn + "' in the model", clazz); return false; } } if (!e.getModifiers().contains(Modifier.STATIC)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnPropertyChange method needs to be static", e); + error("@OnPrprtChange method needs to be static", e); return false; } if (e.getModifiers().contains(Modifier.PRIVATE)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnPropertyChange method cannot be private", e); + error("@OnPrprtChange method cannot be private", e); return false; } if (e.getReturnType().getKind() != TypeKind.VOID) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnPropertyChange method should return void", e); + error("@OnPrprtChange method should return void", e); return false; } String n = e.getSimpleName().toString(); @@ -849,21 +880,15 @@ continue; } if (!e.getModifiers().contains(Modifier.STATIC)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnReceive method needs to be static", e - ); + error("@OnReceive method needs to be static", e); return false; } if (e.getModifiers().contains(Modifier.PRIVATE)) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnReceive method cannot be private", e - ); + error("@OnReceive method cannot be private", e); return false; } if (e.getReturnType().getKind() != TypeKind.VOID) { - err().printMessage( - Diagnostic.Kind.ERROR, "@OnReceive method should return void", e - ); + error("@OnReceive method should return void", e); return false; } String modelClass = null; @@ -882,7 +907,7 @@ } if (modelType != null) { if (modelClass != null) { - err().printMessage(Diagnostic.Kind.ERROR, "There can be only one model class among arguments", e); + error("There can be only one model class among arguments", e); } else { modelClass = modelType.toString(); if (expectsList) { @@ -895,7 +920,7 @@ } } if (modelClass == null) { - err().printMessage(Diagnostic.Kind.ERROR, "The method needs to have one @Model class as parameter", e); + error("The method needs to have one @Model class as parameter", e); } String n = e.getSimpleName().toString(); body.append("public void ").append(n).append("("); @@ -915,9 +940,9 @@ sep = ", "; } if (!skipJSONP) { - err().printMessage(Diagnostic.Kind.ERROR, + error( "Name of jsonp attribute ('" + onR.jsonp() + - "') is not used in url attribute '" + onR.url() + "'" + "') is not used in url attribute '" + onR.url() + "'", e ); } } @@ -1013,7 +1038,7 @@ if (dataName != null) { sb.append(" Try \"").append(dataName).append("\""); } - err().printMessage(Diagnostic.Kind.ERROR, sb.toString(), ee); + error(sb.toString(), ee); } params.append(evName); params.append(", \""); @@ -1032,7 +1057,7 @@ params.append(className).append(".this"); continue; } - err().printMessage(Diagnostic.Kind.ERROR, + error( "@On method can only accept String named 'id' or " + className + " arguments", ee ); @@ -1056,7 +1081,7 @@ if (propName != null && ve.getSimpleName().contentEquals(propName)) { params.append('"').append(propValue).append('"'); } else { - err().printMessage(Diagnostic.Kind.ERROR, "Unexpected string parameter name. Try \"" + propName + "\"."); + error("Unexpected string parameter name. Try \"" + propName + "\".", ee); } continue; } @@ -1069,8 +1094,8 @@ params.append(className).append(".this"); continue; } - err().printMessage(Diagnostic.Kind.ERROR, - "@OnPropertyChange method can only accept String or " + className + " arguments", + error( + "@OnPrprtChange method can only accept String or " + className + " arguments", ee); } return params; @@ -1107,12 +1132,12 @@ w.write("\n }"); } - private void writeToString(Property[] props, Writer w) throws IOException { + private void writeToString(Prprt[] props, Writer w) throws IOException { w.write(" public String toString() {\n"); w.write(" StringBuilder sb = new StringBuilder();\n"); w.write(" sb.append('{');\n"); String sep = ""; - for (Property p : props) { + for (Prprt p : props) { w.write(sep); w.append(" sb.append(\"" + p.name() + ": \");\n"); w.append(" sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_"); @@ -1123,14 +1148,15 @@ w.write(" return sb.toString();\n"); w.write(" }\n"); } - private void writeClone(String className, Property[] props, Writer w) throws IOException { + private void writeClone(String className, Prprt[] props, Writer w) throws IOException { w.write(" public " + className + " clone() {\n"); w.write(" " + className + " ret = new " + className + "();\n"); - for (Property p : props) { + for (Prprt p : props) { if (!p.array()) { boolean isModel[] = { false }; boolean isEnum[] = { false }; - checkType(p, isModel, isEnum); + boolean isPrimitive[] = { false }; + checkType(p, isModel, isEnum, isPrimitive); if (!isModel[0]) { w.write(" ret.prop_" + p.name() + " = prop_" + p.name() + ";\n"); continue; @@ -1168,26 +1194,59 @@ return pt.toString(); } - private String checkType(Property p, boolean[] isModel, boolean[] isEnum) { + private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) { + TypeMirror tm; + try { + String ret = p.typeName(processingEnv); + TypeElement e = processingEnv.getElementUtils().getTypeElement(ret); + if (e == null) { + isModel[0] = true; + isEnum[0] = false; + isPrimitive[0] = false; + return ret; + } + tm = e.asType(); + } catch (MirroredTypeException ex) { + tm = ex.getTypeMirror(); + } + tm = processingEnv.getTypeUtils().erasure(tm); + isPrimitive[0] = tm.getKind().isPrimitive(); + final Element e = processingEnv.getTypeUtils().asElement(tm); + final Model m = e == null ? null : e.getAnnotation(Model.class); + String ret; - try { - ret = p.type().getName(); - } catch (MirroredTypeException ex) { - TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror()); - final Element e = processingEnv.getTypeUtils().asElement(tm); - final Model m = e == null ? null : e.getAnnotation(Model.class); - if (m != null) { - ret = findPkgName(e) + '.' + m.className(); - isModel[0] = true; - models.put(e, m.className()); - } else { - ret = tm.toString(); + if (m != null) { + ret = findPkgName(e) + '.' + m.className(); + isModel[0] = true; + models.put(e, m.className()); + } else if (findModelForMthd(e)) { + ret = ((TypeElement)e).getQualifiedName().toString(); + isModel[0] = true; + } else { + ret = tm.toString(); + } + TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType(); + enm = processingEnv.getTypeUtils().erasure(enm); + isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm); + return ret; + } + + private static boolean findModelForMthd(Element clazz) { + if (clazz == null) { + return false; + } + for (Element e : clazz.getEnclosedElements()) { + if (e.getKind() == ElementKind.METHOD) { + ExecutableElement ee = (ExecutableElement)e; + if ( + ee.getSimpleName().contentEquals("modelFor") && + ee.getParameters().isEmpty() + ) { + return true; + } } - TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType(); - enm = processingEnv.getTypeUtils().erasure(enm); - isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm); } - return ret; + return false; } private Iterable findParamNames(Element e, String url, StringBuilder assembleURL) { @@ -1203,7 +1262,7 @@ } int close = url.indexOf('}', next); if (close == -1) { - err().printMessage(Diagnostic.Kind.ERROR, "Unbalanced '{' and '}' in " + url, e); + error("Unbalanced '{' and '}' in " + url, e); return params; } final String paramName = url.substring(next + 1, close); @@ -1215,8 +1274,8 @@ } } - private static Property findProperty(Property[] properties, String propName) { - for (Property p : properties) { + private static Prprt findPrprt(Prprt[] properties, String propName) { + for (Prprt p : properties) { if (propName.equals(p.name())) { return p; } @@ -1243,4 +1302,96 @@ } return names; } + + private Prprt[] createProps(Element e, Property[] arr) { + Prprt[] ret = Prprt.wrap(processingEnv, e, arr); + Prprt[] prev = verify.put(e, ret); + if (prev != null) { + error("Two sets of properties for ", e); + } + return ret; + } + + private static class Prprt { + private final Element e; + private final AnnotationMirror tm; + private final Property p; + + public Prprt(Element e, AnnotationMirror tm, Property p) { + this.e = e; + this.tm = tm; + this.p = p; + } + + String name() { + return p.name(); + } + + boolean array() { + return p.array(); + } + + String typeName(ProcessingEnvironment env) { + try { + return p.type().getName(); + } catch (AnnotationTypeMismatchException ex) { + for (Object v : getAnnoValues(env)) { + String s = v.toString().replace(" ", ""); + if (s.startsWith("type=") && s.endsWith(".class")) { + return s.substring(5, s.length() - 6); + } + } + throw ex; + } + } + + + static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) { + if (arr.length == 0) { + return new Prprt[0]; + } + + if (e.getKind() != ElementKind.CLASS) { + throw new IllegalStateException("" + e.getKind()); + } + TypeElement te = (TypeElement)e; + List val = null; + for (AnnotationMirror an : te.getAnnotationMirrors()) { + for (Map.Entry entry : an.getElementValues().entrySet()) { + if (entry.getKey().getSimpleName().contentEquals("properties")) { + val = (List)entry.getValue().getValue(); + break; + } + } + } + if (val == null || val.size() != arr.length) { + pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e); + return new Prprt[0]; + } + Prprt[] ret = new Prprt[arr.length]; + BIG: for (int i = 0; i < ret.length; i++) { + AnnotationMirror am = (AnnotationMirror)val.get(i).getValue(); + ret[i] = new Prprt(e, am, arr[i]); + + } + return ret; + } + + private List getAnnoValues(ProcessingEnvironment pe) { + try { + Class trees = Class.forName("com.sun.tools.javac.api.JavacTrees"); + Method m = trees.getMethod("instance", ProcessingEnvironment.class); + Object instance = m.invoke(null, pe); + m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class); + Object path = m.invoke(instance, e, tm); + m = path.getClass().getMethod("getLeaf"); + Object leaf = m.invoke(path); + m = leaf.getClass().getMethod("getArguments"); + return (List)m.invoke(leaf); + } catch (Exception ex) { + return Collections.emptyList(); + } + } + } + } diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Model.java --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Model.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Model.java Wed Apr 10 12:23:17 2013 +0200 @@ -27,8 +27,9 @@ * annotated by {@link ComputedProperty} which define derived * properties in the model class. *

- * The {@link #className() generated class} will have methods - * to convert the object toJSON and fromJSON. + * The {@link #className() generated class}'s toString + * converts the state of the object into + * JSON format. * * @author Jaroslav Tulach */ diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/OnReceive.java --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/OnReceive.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/OnReceive.java Wed Apr 10 12:23:17 2013 +0200 @@ -22,12 +22,51 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** Static methods in classes annotated by {@link Model} or {@link Page} - * can be marked by this annotation establish a JSON communication point. +/** Static methods in classes annotated by {@link Page} + * can be marked by this annotation to establish a + * JSON + * communication point. * The associated model page then gets new method to invoke a network - * connection + * connection. Example follows: + * + *

+ * {@link Page @Page}(className="MyModel", xhtml="page.html", properties={
+ *   {@link Property @Property}(name = "people", type=Person.class, array=true)
+ * })
+ * class MyModelImpl {
+ *   {@link Model @Model}(className="Person", properties={
+ *     {@link Property @Property}(name = "firstName", type=String.class),
+ *     {@link Property @Property}(name = "lastName", type=String.class)
+ *   })
+ *   static class PersonImpl {
+ *     {@link ComputedProperty @ComputedProperty}
+ *     static String fullName(String firstName, String lastName) {
+ *       return firstName + " " + lastName;
+ *     }
+ *   }
+ * 
+ *   {@link OnReceive @OnReceive}(url = "{protocol}://your.server.com/person/{name}")
+ *   static void getANewPerson(MyModel m, Person p) {
+ *     {@link Element#alert Element.alert}("Adding " + p.getFullName() + '!');
+ *     m.getPeople().add(p);
+ *   }
+ * 
+ *   // the above will generate method getANewPerson in class MyModel.
+ *   // with protocol and name arguments
+ *   // which asynchronously contacts the server and in case of success calls
+ *   // your {@link OnReceive @OnReceive} with parsed in data
+ * 
+ *   {@link On @On}(event={@link OnEvent#CLICK OnEvent.CLICK}, id="rqst")
+ *   static void requestSmith(MyModel m) {
+ *     m.getANewPerson("http", "Smith");
+ *   }
+ * }
+ * 
+ * When the server returns { "firstName" : "John", "lastName" : "Smith" } + * the browser will show alert message Adding John Smith!. * * @author Jaroslav Tulach + * @since 0.6 */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypesTest.java --- a/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypesTest.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypesTest.java Wed Apr 10 12:23:17 2013 +0200 @@ -43,7 +43,7 @@ assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName(); assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName(); -// assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex(); + assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex(); } @Factory public static Object[] create() { diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/JSONTest.java --- a/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/JSONTest.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/JSONTest.java Wed Apr 10 12:23:17 2013 +0200 @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.Iterator; -import java.util.List; +import org.apidesign.bck2brwsr.core.JavaScriptBody; import org.apidesign.bck2brwsr.htmlpage.api.OnReceive; import org.apidesign.bck2brwsr.htmlpage.api.Page; import org.apidesign.bck2brwsr.htmlpage.api.Property; @@ -39,10 +39,12 @@ */ @Page(xhtml = "Empty.html", className = "JSONik", properties = { @Property(name = "fetched", type = PersonImpl.class), - @Property(name = "fetchedCount", type = int.class) + @Property(name = "fetchedCount", type = int.class), + @Property(name = "fetchedSex", type = Sex.class, array = true) }) public class JSONTest { private JSONik js; + private Integer orig; @Test public void personToString() throws JSONException { Person p = new Person(); @@ -169,7 +171,7 @@ } assert "Sitar".equals(p.getFirstName()) : "Expecting Sitar: " + p.getFirstName(); - // assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); } @OnReceive(url="/{url}?callme={me}", jsonp = "me") @@ -184,7 +186,11 @@ parameters = { "callme" } )) @BrwsrTest public void loadAndParseJSONP() throws InterruptedException { + if (js == null) { + orig = scriptElements(); + assert orig > 0 : "There should be some scripts on the page"; + js = new JSONik(); js.applyBindings(); @@ -197,8 +203,15 @@ } assert "Mitar".equals(p.getFirstName()) : "Unexpected: " + p.getFirstName(); - // assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + + int now = scriptElements(); + + assert orig == now : "The set of elements is unchanged. Delta: " + (now - orig); } + + @JavaScriptBody(args = { }, body = "return window.document.getElementsByTagName('script').length;") + private static native int scriptElements(); @Http(@Http.Resource( content = "{'firstName': 'Sitar', 'sex': 'MALE'}", @@ -220,7 +233,7 @@ assert p != null : "We should get our person back: " + p; assert "Sitar".equals(p.getFirstName()) : "Expecting Sitar: " + p.getFirstName(); -// assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); } @Http(@Http.Resource( @@ -243,7 +256,7 @@ assert p != null : "We should get our person back: " + p; assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName(); -// assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex(); } @Http(@Http.Resource( @@ -269,7 +282,7 @@ assert p != null : "We should get our person back: " + p; assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName(); -// assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex(); } @Http(@Http.Resource( @@ -292,6 +305,38 @@ assert js.getFetchedCount() == 6 : "1 + 2 + 3 is " + js.getFetchedCount(); } + @OnReceive(url="/{url}") + static void fetchPeopleSex(People p, JSONik model) { + model.setFetchedCount(1); + model.getFetchedSex().addAll(p.getSex()); + } + + + @Http(@Http.Resource( + content = "{'sex':['FEMALE', 'MALE', 'MALE']}", + path="/people.json", + mimeType = "application/json" + )) + @BrwsrTest public void loadAndParseArrayOfEnums() throws InterruptedException { + if (js == null) { + js = new JSONik(); + js.applyBindings(); + + js.fetchPeopleSex("people.json"); + } + + if (0 == js.getFetchedCount()) { + throw new InterruptedException(); + } + + assert js.getFetchedCount() == 1 : "Loaded"; + + assert js.getFetchedSex().size() == 3 : "Three values " + js.getFetchedSex(); + assert js.getFetchedSex().get(0) == Sex.FEMALE : "Female first " + js.getFetchedSex(); + assert js.getFetchedSex().get(1) == Sex.MALE : "male 2nd " + js.getFetchedSex(); + assert js.getFetchedSex().get(2) == Sex.MALE : "male 3rd " + js.getFetchedSex(); + } + @Http(@Http.Resource( content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'}," + "{'firstName': 'Peter', 'sex': 'MALE'}" @@ -315,7 +360,7 @@ assert js.getFetchedCount() == 2 : "We got two values: " + js.getFetchedCount(); assert p != null : "We should get our person back: " + p; assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName(); -// assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex(); + assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex(); } @Factory public static Object[] create() { diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PageTest.java --- a/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PageTest.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PageTest.java Wed Apr 10 12:23:17 2013 +0200 @@ -19,6 +19,8 @@ import java.io.IOException; import java.util.Locale; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; import static org.testng.Assert.*; import org.testng.annotations.Test; @@ -39,11 +41,12 @@ + "}\n"; Compile c = Compile.create(html, code); - assertEquals(c.getErrors().size(), 1, "One error: " + c.getErrors()); - - String msg = c.getErrors().get(0).getMessage(Locale.ENGLISH); - if (!msg.contains("Runnable")) { - fail("Should contain warning about Runnable: " + msg); + assertFalse(c.getErrors().isEmpty(), "One error: " + c.getErrors()); + for (Diagnostic e : c.getErrors()) { + String msg = e.getMessage(Locale.ENGLISH); + if (!msg.contains("Runnable")) { + fail("Should contain warning about Runnable: " + msg); + } } } diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PersonImpl.java --- a/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PersonImpl.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/PersonImpl.java Wed Apr 10 12:23:17 2013 +0200 @@ -52,9 +52,11 @@ } @Model(className = "People", properties = { - @Property(array = true, name = "info", type = PersonImpl.class), + @Property(array = true, name = "info", type = Person.class), @Property(array = true, name = "nicknames", type = String.class), - @Property(array = true, name = "age", type = int.class),}) + @Property(array = true, name = "age", type = int.class), + @Property(array = true, name = "sex", type = Sex.class) + }) public class PeopleImpl { } } diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/demo-twitter/pom.xml --- a/javaquery/demo-twitter/pom.xml Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/demo-twitter/pom.xml Wed Apr 10 12:23:17 2013 +0200 @@ -44,7 +44,7 @@ UTF-8 - FULL + MINIMAL diff -r c75bd6823179 -r 5c7cdd2b3f8f javaquery/demo-twitter/src/main/java/org/apidesign/bck2brwsr/demo/twitter/TwitterClient.java --- a/javaquery/demo-twitter/src/main/java/org/apidesign/bck2brwsr/demo/twitter/TwitterClient.java Mon Apr 08 19:33:08 2013 +0200 +++ b/javaquery/demo-twitter/src/main/java/org/apidesign/bck2brwsr/demo/twitter/TwitterClient.java Wed Apr 10 12:23:17 2013 +0200 @@ -29,11 +29,11 @@ * @author Jaroslav Tulach */ @Page(xhtml="index.html", className="TwitterModel", properties={ - @Property(name="savedLists", type=TwitterClient.Twttrs.class, array = true), + @Property(name="savedLists", type=Tweeters.class, array = true), @Property(name="activeTweetersName", type=String.class), @Property(name="activeTweeters", type=String.class, array = true), @Property(name="userNameToAdd", type=String.class), - @Property(name="currentTweets", type=TwitterClient.Twt.class, array = true) + @Property(name="currentTweets", type=Tweet.class, array = true) }) public class TwitterClient { @Model(className = "Tweeters", properties = { diff -r c75bd6823179 -r 5c7cdd2b3f8f rt/emul/mini/src/main/java/java/lang/Enum.java --- a/rt/emul/mini/src/main/java/java/lang/Enum.java Mon Apr 08 19:33:08 2013 +0200 +++ b/rt/emul/mini/src/main/java/java/lang/Enum.java Wed Apr 10 12:23:17 2013 +0200 @@ -27,6 +27,7 @@ import java.io.Serializable; import java.io.IOException; +import org.apidesign.bck2brwsr.core.JavaScriptBody; /** * This is the common base class of all Java language enumeration types. @@ -225,15 +226,17 @@ */ public static > T valueOf(Class enumType, String name) { - throw new UnsupportedOperationException(); -// T result = enumType.enumConstantDirectory().get(name); -// if (result != null) -// return result; -// if (name == null) -// throw new NullPointerException("Name is null"); -// throw new IllegalArgumentException( -// "No enum constant " + enumType.getCanonicalName() + "." + name); + for (Object o : values(enumType)) { + T t = enumType.cast(o); + if (name.equals(((Enum)t).name)) { + return t; + } + } + throw new IllegalArgumentException(); } + + @JavaScriptBody(args = { "enumType" }, body = "return enumType.cnstr.$VALUES;") + private static native Object[] values(Class enumType); /** * enum classes cannot have finalize methods. diff -r c75bd6823179 -r 5c7cdd2b3f8f rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java --- a/rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Mon Apr 08 19:33:08 2013 +0200 +++ b/rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Wed Apr 10 12:23:17 2013 +0200 @@ -1940,7 +1940,7 @@ final String type = jc.getClassName(indx); if (!type.startsWith("[")) { emit(out, - "if (@1 !== null && !@1.$instOf_@2) throw {};", + "if (@1 !== null && !@1.$instOf_@2) throw vm.java_lang_ClassCastException(true);", smapper.getA(0), type.replace('/', '_')); } else { emit(out, "vm.java_lang_Class(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('@2').cast__Ljava_lang_Object_2Ljava_lang_Object_2(@1);", diff -r c75bd6823179 -r 5c7cdd2b3f8f rt/vm/src/test/java/org/apidesign/vm4brwsr/ClassTest.java --- a/rt/vm/src/test/java/org/apidesign/vm4brwsr/ClassTest.java Mon Apr 08 19:33:08 2013 +0200 +++ b/rt/vm/src/test/java/org/apidesign/vm4brwsr/ClassTest.java Wed Apr 10 12:23:17 2013 +0200 @@ -207,5 +207,12 @@ true ); } + + @Test public void valueOfEnum() throws Exception { + assertExec("can get value of enum", Classes.class, + "valueEnum__Ljava_lang_String_2Ljava_lang_String_2", + "TWO", "TWO" + ); + } } diff -r c75bd6823179 -r 5c7cdd2b3f8f rt/vm/src/test/java/org/apidesign/vm4brwsr/Classes.java --- a/rt/vm/src/test/java/org/apidesign/vm4brwsr/Classes.java Mon Apr 08 19:33:08 2013 +0200 +++ b/rt/vm/src/test/java/org/apidesign/vm4brwsr/Classes.java Wed Apr 10 12:23:17 2013 +0200 @@ -230,4 +230,7 @@ return Application.class.isAssignableFrom(MyApplication.class); } + public static String valueEnum(String v) { + return ClassesMarker.E.valueOf(v).toString(); + } } diff -r c75bd6823179 -r 5c7cdd2b3f8f rt/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/ReflectionTest.java --- a/rt/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/ReflectionTest.java Mon Apr 08 19:33:08 2013 +0200 +++ b/rt/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/ReflectionTest.java Wed Apr 10 12:23:17 2013 +0200 @@ -103,6 +103,15 @@ StaticUse.class.getMethod("instanceMethod").invoke(null); return "should not happen"; } + + @Compare public String classCastException() { + try { + Integer i = (Integer)StaticUseSub.getNonNull(); + return "" + i.intValue(); + } catch (ClassCastException ex) { + return ex.getClass().getName(); + } + } @Compare public String methodThatThrowsException() throws Exception { StaticUse.class.getMethod("instanceMethod").invoke(new StaticUse());