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