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