launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 19 Apr 2016 05:31:17 +0200
changeset 1929 dd63b6731507
parent 1927 cff680298793
permissions -rw-r--r--
Get ready for missing output list element
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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 net.java.html.js.JavaScriptBody;
    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     @JavaScriptBody(args = { "elem", "attr" }, body = "return elem[attr].toString();")
    40     private static native Object getAttr(Object elem, String attr);
    41 
    42     @JavaScriptBody(args = { "id", "attr", "value" }, body = "\n"
    43         + "var e = window.document.getElementById(id);\n"
    44         + "if (e) e[attr] = value;\n"
    45     )
    46     private static native void setAttr(String id, String attr, Object value);
    47 
    48     @JavaScriptBody(args = { "elem", "attr", "value" }, body = "elem[attr] = value;")
    49     private static native void setAttr(Object elem, String attr, Object value);
    50 
    51     @JavaScriptBody(args = {}, body = "return new Date().getTime()")
    52     private static native double getTime();
    53     
    54     private static void closeWindow() {}
    55 
    56     private static Object textArea;
    57     private static Object statusArea;
    58     
    59     private static void log(String newText) {
    60         if (textArea == null) {
    61             return;
    62         }
    63         String attr = "value";
    64         setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
    65         setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
    66     }
    67     
    68     private static void beginTest(Case c) {
    69         Object[] arr = beginTest(c.getClassName() + "." + c.getMethodName(), c, new Object[2]);
    70         textArea = arr[0];
    71         statusArea = arr[1];
    72     }
    73     
    74     private static void finishTest(Case c, Object res) {
    75         if ("null".equals(res)) {
    76             setAttr(statusArea, "innerHTML", "Success");
    77         } else {
    78             setAttr(statusArea, "innerHTML", "Result " + res);
    79         }
    80         statusArea = null;
    81         textArea = null;
    82     }
    83 
    84     @JavaScriptBody(args = { "test", "c", "arr" }, body = 
    85         "var ul = window.document.getElementById('bck2brwsr.result');\n"
    86         + "var li = window.document.createElement('li');\n"
    87         + "var span = window.document.createElement('span');"
    88         + "span.innerHTML = test + ' - ';\n"
    89         + "var details = window.document.createElement('a');\n"
    90         + "details.innerHTML = 'Details';\n"
    91         + "details.href = '#';\n"
    92         + "var p = window.document.createElement('p');\n"
    93         + "var status = window.document.createElement('a');\n"
    94         + "status.innerHTML = 'running';"
    95         + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
    96         + "status.onclick = function() { c.again(arr); }\n"
    97         + "var pre = window.document.createElement('textarea');\n"
    98         + "pre.cols = 100;"
    99         + "pre.rows = 10;"
   100         + "li.appendChild(span);\n"
   101         + "li.appendChild(status);\n"
   102         + "var span = window.document.createElement('span');"
   103         + "span.innerHTML = ' ';\n"
   104         + "li.appendChild(span);\n"
   105         + "li.appendChild(details);\n"
   106         + "p.appendChild(pre);\n"
   107         + "if (ul) ul.appendChild(li);\n"
   108         + "arr[0] = pre;\n"
   109         + "arr[1] = status;\n"
   110         + "return arr;"
   111     )
   112     private static native Object[] beginTest(String test, Case c, Object[] arr);
   113     
   114     @JavaScriptBody(args = { "url", "callback" }, javacall = true, body =
   115           "var request = new XMLHttpRequest();\n"
   116         + "request.open('GET', url, true);\n"
   117         + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
   118         + "request.onreadystatechange = function() {\n"
   119         + "  if (this.readyState!==4) return;\n"
   120         + " try {\n"
   121         + "  callback.@org.apidesign.bck2brwsr.launcher.fximpl.OnMessage::onMessage(Ljava/lang/String;)(this.responseText);\n"
   122         + " } catch (e) { alert(e); }\n"
   123         + "};\n"
   124         + "request.send();\n"
   125     )
   126     private static native void loadText(String url, OnMessage callback) throws IOException;
   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, OnMessage {
   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);
   146         }
   147         private Request(String url, String u) throws IOException {
   148             this.url = url;
   149             loadText(u, this);
   150         }
   151 
   152         @Override
   153         public void onMessage(String msg) {
   154             arr[0] = msg;
   155             run();
   156         }
   157         
   158         @Override
   159         public void run() {
   160             Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
   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++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
   184                 String reply = "?request=" + c.getRequestId() + "&time=" + c.time + "&result=" + result;
   185                 log("Sending back: ..." + reply);
   186                 finishTest(c, result);
   187                 
   188                 String u = url + reply;
   189                 new Request(url, u);
   190             } catch (Exception ex) {
   191                 if (ex instanceof InterruptedException) {
   192                     log("Re-scheduling in 100ms");
   193                     schedule(this, 100);
   194                     return;
   195                 }
   196                 log(ex.getClass().getName() + ":" + ex.getMessage());
   197             }
   198         }
   199     }
   200     
   201     private static String encodeURL(String r) throws UnsupportedEncodingException {
   202         final String SPECIAL = "%$&+,/:;=?@";
   203         StringBuilder sb = new StringBuilder();
   204         byte[] utf8 = r.getBytes("UTF-8");
   205         for (int i = 0; i < utf8.length; i++) {
   206             int ch = utf8[i] & 0xff;
   207             if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
   208                 final String numbers = "0" + Integer.toHexString(ch);
   209                 sb.append("%").append(numbers.substring(numbers.length() - 2));
   210             } else {
   211                 if (ch == 32) {
   212                     sb.append("+");
   213                 } else {
   214                     sb.append((char)ch);
   215                 }
   216             }
   217         }
   218         return sb.toString();
   219     }
   220     
   221     static String invoke(String clazz, String method) throws 
   222     ClassNotFoundException, InvocationTargetException, IllegalAccessException, 
   223     InstantiationException, InterruptedException {
   224         final Object r = new Case(null).invokeMethod(clazz, method);
   225         return r == null ? "null" : r.toString().toString();
   226     }
   227 
   228     /** Helper method that inspects the classpath and loads given resource
   229      * (usually a class file). Used while running tests in Rhino.
   230      * 
   231      * @param name resource name to find
   232      * @return the array of bytes in the given resource
   233      * @throws IOException I/O in case something goes wrong
   234      */
   235     public static byte[] read(String name) throws IOException {
   236         URL u = null;
   237         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   238         while (en.hasMoreElements()) {
   239             u = en.nextElement();
   240         }
   241         if (u == null) {
   242             throw new IOException("Can't find " + name);
   243         }
   244         InputStream is = null;
   245         try {
   246             is = u.openStream();
   247             byte[] arr;
   248             arr = new byte[is.available()];
   249             int offset = 0;
   250             while (offset < arr.length) {
   251                 int len = is.read(arr, offset, arr.length - offset);
   252                 if (len == -1) {
   253                     throw new IOException("Can't read " + name);
   254                 }
   255                 offset += len;
   256             }
   257             return arr;
   258         } finally {
   259             if (is != null) is.close();
   260         }
   261     }
   262    
   263     private static void turnAssetionStatusOn() {
   264     }
   265 
   266     @JavaScriptBody(args = { "r", "time" }, javacall = true, body = 
   267         "return window.setTimeout(function() { "
   268         + "r.@java.lang.Runnable::run()(); "
   269         + "}, time);"
   270     )
   271     private static native Object schedule(Runnable r, int time);
   272     
   273     private static final class Case {
   274         private final Object data;
   275         private double time;
   276         private Object inst;
   277 
   278         private Case(Object data) {
   279             this.data = data;
   280         }
   281         
   282         public static Case parseData(String s) {
   283             return new Case(toJSON(s));
   284         }
   285         
   286         public String getMethodName() {
   287             return (String) value("methodName", data);
   288         }
   289 
   290         public String getClassName() {
   291             return (String) value("className", data);
   292         }
   293         
   294         public int getRequestId() {
   295             Object v = value("request", data);
   296             if (v instanceof Number) {
   297                 return ((Number)v).intValue();
   298             }
   299             return Integer.parseInt(v.toString());
   300         }
   301 
   302         public String getHtmlFragment() {
   303             return (String) value("html", data);
   304         }
   305         
   306         void again(Object[] arr) {
   307             try {
   308                 textArea = arr[0];
   309                 statusArea = arr[1];
   310                 setAttr(textArea, "value", "");
   311                 runTest();
   312             } catch (Exception ex) {
   313                 log(ex.getClass().getName() + ":" + ex.getMessage());
   314             }
   315         }
   316 
   317         private Object runTest() throws IllegalAccessException, 
   318         IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException, 
   319         InvocationTargetException, InstantiationException, InterruptedException {
   320             if (this.getHtmlFragment() != null) {
   321                 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
   322             }
   323             log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
   324             Object result = invokeMethod(this.getClassName(), this.getMethodName());
   325             setAttr("bck2brwsr.fragment", "innerHTML", "");
   326             log("Result: " + result);
   327             log("Time: " + time + " ms");
   328             result = encodeURL("" + result);
   329             return result;
   330         }
   331 
   332         private Object invokeMethod(String clazz, String method)
   333         throws ClassNotFoundException, InvocationTargetException,
   334         InterruptedException, IllegalAccessException, IllegalArgumentException,
   335         InstantiationException {
   336             Method found = null;
   337             Class<?> c = Class.forName(clazz);
   338             for (Method m : c.getMethods()) {
   339                 if (m.getName().equals(method)) {
   340                     found = m;
   341                 }
   342             }
   343             Object res;
   344             if (found != null) {
   345                 try {
   346                     if ((found.getModifiers() & Modifier.STATIC) != 0) {
   347                         res = found.invoke(null);
   348                     } else {
   349                         if (inst == null) {
   350                             inst = c.newInstance();
   351                         }
   352                         double now = getTime();
   353                         res = found.invoke(inst);
   354                         double took = Math.round(getTime() - now);
   355                         time += took;
   356                         log("Execution took " + took + " ms");
   357                     }
   358                 } catch (Throwable ex) {
   359                     if (ex instanceof InvocationTargetException) {
   360                         ex = ((InvocationTargetException) ex).getTargetException();
   361                     }
   362                     if (ex instanceof InterruptedException) {
   363                         throw (InterruptedException)ex;
   364                     }
   365                     res = ex.getClass().getName() + ":" + ex.getMessage();
   366                 }
   367             } else {
   368                 res = "Can't find method " + method + " in " + clazz;
   369             }
   370             return res;
   371         }
   372 
   373         @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
   374         private static native Object toJSON(String s);
   375         
   376         private static Object value(String p, Object d) {
   377             return ((JSObject)d).getMember(p);
   378         }
   379     }
   380     
   381     static {
   382         turnAssetionStatusOn();
   383     }
   384 }