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