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