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