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