rt/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/impl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 18 Apr 2013 09:06:18 +0200
branchfx
changeset 1007 66ccab5a3530
parent 1006 691c5cd3fb93
child 1011 9cc253aa9405
permissions -rw-r--r--
Can execute tests in FX web view.
     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.launcher.impl;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.UnsupportedEncodingException;
    23 import java.lang.reflect.InvocationTargetException;
    24 import java.lang.reflect.Method;
    25 import java.lang.reflect.Modifier;
    26 import java.net.URL;
    27 import java.util.Enumeration;
    28 import javafx.scene.web.WebEngine;
    29 import netscape.javascript.JSObject;
    30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    31 
    32 /**
    33  *
    34  * @author Jaroslav Tulach <jtulach@netbeans.org>
    35  */
    36 public final class Console {
    37     public Console() {
    38     }
    39     private static final JSObject CObject;
    40     
    41     @JavaScriptBody(args = {"elem", "attr"}, body = 
    42         "return elem[attr].toString();")
    43     private static Object getAttr(Object elem, String attr) {
    44         return CObject.call("getAttr", elem, attr);
    45     }
    46 
    47     @JavaScriptBody(args = {"id", "attr", "value"}, body = 
    48         "window.document.getElementById(id)[attr] = value;")
    49     private static void setAttr(String id, String attr, Object value) {
    50         CObject.call("setAttrId", id, attr, value);
    51     }
    52     @JavaScriptBody(args = {"elem", "attr", "value"}, body = 
    53         "elem[attr] = value;")
    54     private static void setAttr(Object id, String attr, Object value) {
    55         CObject.call("setAttr", id, attr, value);
    56     }
    57     
    58     @JavaScriptBody(args = {}, body = "return; window.close();")
    59     private static void closeWindow() {}
    60 
    61     private static Object textArea;
    62     private static Object statusArea;
    63     
    64     private static void log(String newText) {
    65         if (textArea == null) {
    66             return;
    67         }
    68         String attr = "value";
    69         setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
    70         setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
    71     }
    72     
    73     private static void beginTest(Case c) {
    74         Object[] arr = new Object[2];
    75         beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
    76         textArea = arr[0];
    77         statusArea = arr[1];
    78     }
    79     
    80     private static void finishTest(Case c, Object res) {
    81         if ("null".equals(res)) {
    82             setAttr(statusArea, "innerHTML", "Success");
    83         } else {
    84             setAttr(statusArea, "innerHTML", "Result " + res);
    85         }
    86         statusArea = null;
    87         textArea = null;
    88     }
    89 
    90     private static final String BEGIN_TEST =  
    91         "var ul = window.document.getElementById('bck2brwsr.result');\n"
    92         + "var li = window.document.createElement('li');\n"
    93         + "var span = window.document.createElement('span');"
    94         + "span.innerHTML = test + ' - ';\n"
    95         + "var details = window.document.createElement('a');\n"
    96         + "details.innerHTML = 'Details';\n"
    97         + "details.href = '#';\n"
    98         + "var p = window.document.createElement('p');\n"
    99         + "var status = window.document.createElement('a');\n"
   100         + "status.innerHTML = 'running';"
   101         + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
   102         + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
   103         + "var pre = window.document.createElement('textarea');\n"
   104         + "pre.cols = 100;"
   105         + "pre.rows = 10;"
   106         + "li.appendChild(span);\n"
   107         + "li.appendChild(status);\n"
   108         + "var span = window.document.createElement('span');"
   109         + "span.innerHTML = ' ';\n"
   110         + "li.appendChild(span);\n"
   111         + "li.appendChild(details);\n"
   112         + "p.appendChild(pre);\n"
   113         + "ul.appendChild(li);\n"
   114         + "arr[0] = pre;\n"
   115         + "arr[1] = status;\n";
   116         
   117     @JavaScriptBody(args = { "test", "c", "arr" }, body = BEGIN_TEST)
   118     private static void beginTest(String test, Case c, Object[] arr) {
   119         CObject.call("beginTest", test, c, arr);
   120     }
   121     
   122     private static final String LOAD_TEXT = 
   123           "var request = new XMLHttpRequest();\n"
   124         + "request.open('GET', url, true);\n"
   125         + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
   126         + "request.onreadystatechange = function() {\n"
   127         + "  if (this.readyState!==4) return;\n"
   128         + " try {"
   129         + "  arr[0] = this.responseText;\n"
   130         + "  callback.run();\n"
   131         + " } catch (e) { alert(e); }"
   132         + "};"
   133         + "request.send();";
   134     @JavaScriptBody(args = { "url", "callback", "arr" }, body = LOAD_TEXT)
   135     private static void loadText(String url, Runnable callback, String[] arr) throws IOException {
   136         CObject.call("loadText", url, new Run(callback), arr);
   137     }
   138     
   139     public void harness(String url) throws IOException {
   140         log("Connecting to " + url);
   141         Request r = new Request(url);
   142     }
   143     
   144     private static class Request implements Runnable {
   145         private final String[] arr = { null };
   146         private final String url;
   147         private Case c;
   148         private int retries;
   149 
   150         private Request(String url) throws IOException {
   151             this.url = url;
   152             loadText(url, this, arr);
   153         }
   154         private Request(String url, String u) throws IOException {
   155             this.url = url;
   156             loadText(u, this, arr);
   157         }
   158         
   159         @Override
   160         public void run() {
   161             try {
   162                 if (c == null) {
   163                     String data = arr[0];
   164 
   165                     if (data == null) {
   166                         log("Some error exiting");
   167                         closeWindow();
   168                         return;
   169                     }
   170 
   171                     if (data.isEmpty()) {
   172                         log("No data, exiting");
   173                         closeWindow();
   174                         return;
   175                     }
   176 
   177                     c = Case.parseData(data);
   178                     beginTest(c);
   179                     log("Got \"" + data + "\"");
   180                 } else {
   181                     log("Processing \"" + arr[0] + "\" for " + retries + " time");
   182                 }
   183                 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
   184                 finishTest(c, result);
   185                 
   186                 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
   187                 new Request(url, u);
   188             } catch (Exception ex) {
   189                 if (ex instanceof InterruptedException) {
   190                     log("Re-scheduling in 100ms");
   191                     schedule(this, 100);
   192                     return;
   193                 }
   194                 log(ex.getClass().getName() + ":" + ex.getMessage());
   195             }
   196         }
   197     }
   198     
   199     private static String encodeURL(String r) throws UnsupportedEncodingException {
   200         final String SPECIAL = "%$&+,/:;=?@";
   201         StringBuilder sb = new StringBuilder();
   202         byte[] utf8 = r.getBytes("UTF-8");
   203         for (int i = 0; i < utf8.length; i++) {
   204             int ch = utf8[i] & 0xff;
   205             if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
   206                 final String numbers = "0" + Integer.toHexString(ch);
   207                 sb.append("%").append(numbers.substring(numbers.length() - 2));
   208             } else {
   209                 if (ch == 32) {
   210                     sb.append("+");
   211                 } else {
   212                     sb.append((char)ch);
   213                 }
   214             }
   215         }
   216         return sb.toString();
   217     }
   218     
   219     static String invoke(String clazz, String method) throws 
   220     ClassNotFoundException, InvocationTargetException, IllegalAccessException, 
   221     InstantiationException, InterruptedException {
   222         final Object r = new Case(null).invokeMethod(clazz, method);
   223         return r == null ? "null" : r.toString().toString();
   224     }
   225 
   226     /** Helper method that inspects the classpath and loads given resource
   227      * (usually a class file). Used while running tests in Rhino.
   228      * 
   229      * @param name resource name to find
   230      * @return the array of bytes in the given resource
   231      * @throws IOException I/O in case something goes wrong
   232      */
   233     public static byte[] read(String name) throws IOException {
   234         URL u = null;
   235         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   236         while (en.hasMoreElements()) {
   237             u = en.nextElement();
   238         }
   239         if (u == null) {
   240             throw new IOException("Can't find " + name);
   241         }
   242         try (InputStream is = u.openStream()) {
   243             byte[] arr;
   244             arr = new byte[is.available()];
   245             int offset = 0;
   246             while (offset < arr.length) {
   247                 int len = is.read(arr, offset, arr.length - offset);
   248                 if (len == -1) {
   249                     throw new IOException("Can't read " + name);
   250                 }
   251                 offset += len;
   252             }
   253             return arr;
   254         }
   255     }
   256    
   257     @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
   258     private static void turnAssetionStatusOn() {
   259     }
   260 
   261     @JavaScriptBody(args = {"r", "time"}, body =
   262         "return window.setTimeout(function() { r.run__V(); }, time);")
   263     private static Object schedule(Runnable r, int time) {
   264         return CObject.call("schedule", new Run(r), time);
   265     }
   266     
   267     private static final class Case {
   268         private final Object data;
   269         private Object inst;
   270 
   271         private Case(Object data) {
   272             this.data = data;
   273         }
   274         
   275         public static Case parseData(String s) {
   276             return new Case(toJSON(s));
   277         }
   278         
   279         public String getMethodName() {
   280             return (String) value("methodName", data);
   281         }
   282 
   283         public String getClassName() {
   284             return (String) value("className", data);
   285         }
   286         
   287         public int getRequestId() {
   288             return (int) value("request", data);
   289         }
   290 
   291         public String getHtmlFragment() {
   292             return (String) value("html", data);
   293         }
   294         
   295         void again(Object[] arr) {
   296             try {
   297                 textArea = arr[0];
   298                 statusArea = arr[1];
   299                 setAttr(textArea, "value", "");
   300                 runTest();
   301             } catch (Exception ex) {
   302                 log(ex.getClass().getName() + ":" + ex.getMessage());
   303             }
   304         }
   305 
   306         private Object runTest() throws IllegalAccessException, 
   307         IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException, 
   308         InvocationTargetException, InstantiationException, InterruptedException {
   309             if (this.getHtmlFragment() != null) {
   310                 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
   311             }
   312             log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
   313             Object result = invokeMethod(this.getClassName(), this.getMethodName());
   314             setAttr("bck2brwsr.fragment", "innerHTML", "");
   315             log("Result: " + result);
   316             result = encodeURL("" + result);
   317             log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
   318             return result;
   319         }
   320 
   321         private Object invokeMethod(String clazz, String method)
   322         throws ClassNotFoundException, InvocationTargetException,
   323         InterruptedException, IllegalAccessException, IllegalArgumentException,
   324         InstantiationException {
   325             Method found = null;
   326             Class<?> c = Class.forName(clazz);
   327             for (Method m : c.getMethods()) {
   328                 if (m.getName().equals(method)) {
   329                     found = m;
   330                 }
   331             }
   332             Object res;
   333             if (found != null) {
   334                 try {
   335                     if ((found.getModifiers() & Modifier.STATIC) != 0) {
   336                         res = found.invoke(null);
   337                     } else {
   338                         if (inst == null) {
   339                             inst = c.newInstance();
   340                         }
   341                         res = found.invoke(inst);
   342                     }
   343                 } catch (Throwable ex) {
   344                     if (ex instanceof InvocationTargetException) {
   345                         ex = ((InvocationTargetException) ex).getTargetException();
   346                     }
   347                     if (ex instanceof InterruptedException) {
   348                         throw (InterruptedException)ex;
   349                     }
   350                     res = ex.getClass().getName() + ":" + ex.getMessage();
   351                 }
   352             } else {
   353                 res = "Can't find method " + method + " in " + clazz;
   354             }
   355             return res;
   356         }
   357         
   358         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   359         private static Object toJSON(String s) {
   360             return CObject.call("toJSON", s);
   361         }
   362         
   363         @JavaScriptBody(args = {"p", "d"}, body = 
   364               "var v = d[p];\n"
   365             + "if (typeof v === 'undefined') return null;\n"
   366             + "return v.toString();"
   367         )
   368         private static Object value(String p, Object d) {
   369             return ((JSObject)d).getMember(p);
   370         }
   371     }
   372     
   373     private static String safe(String txt) {
   374         return "try {" + txt + "} catch (err) { alert(err); }";
   375     }
   376     
   377     static {
   378         turnAssetionStatusOn();
   379 
   380         WebEngine web = (WebEngine) System.getProperties().get("webEngine");
   381         CObject = (JSObject) web.executeScript("(function() {"
   382             + "var CObject = {};"
   383 
   384             + "CObject.getAttr = function(elem, attr) { return elem[attr].toString(); };"
   385 
   386             + "CObject.setAttrId = function(id, attr, value) { window.document.getElementById(id)[attr] = value; };"
   387             + "CObject.setAttr = function(elem, attr, value) { elem[attr] = value; };"
   388 
   389             + "CObject.beginTest = function(test, c, arr) {" + safe(BEGIN_TEST) + "};"
   390 
   391             + "CObject.loadText = function(url, callback, arr) {" + safe(LOAD_TEXT) + "};"
   392             
   393             + "CObject.schedule = function(r, time) { return window.setTimeout(function() { r.run(); }, time); };"
   394             
   395             + "CObject.toJSON = function(s) { return eval('(' + s + ')'); };"
   396 
   397             + "return CObject;"
   398         + "})(this)");
   399     }
   400     
   401 }