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