launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 26 Aug 2013 08:56:37 +0200
changeset 1249 cdaeea7becf2
parent 1179 2fee889b9830
child 1423 237dbcd482dc
permissions -rw-r--r--
First updates to run with forthcoming version 0.5 - WebSockets in FX launcher and etc.
     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             Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
   150             try {
   151                 if (c == null) {
   152                     String data = arr[0];
   153 
   154                     if (data == null) {
   155                         log("Some error exiting");
   156                         closeWindow();
   157                         return;
   158                     }
   159 
   160                     if (data.isEmpty()) {
   161                         log("No data, exiting");
   162                         closeWindow();
   163                         return;
   164                     }
   165 
   166                     c = Case.parseData(data);
   167                     beginTest(c);
   168                     log("Got \"" + data + "\"");
   169                 } else {
   170                     log("Processing \"" + arr[0] + "\" for " + retries + " time");
   171                 }
   172                 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
   173                 finishTest(c, result);
   174                 
   175                 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
   176                 new Request(url, u);
   177             } catch (Exception ex) {
   178                 if (ex instanceof InterruptedException) {
   179                     log("Re-scheduling in 100ms");
   180                     schedule(new Run(this), 100);
   181                     return;
   182                 }
   183                 log(ex.getClass().getName() + ":" + ex.getMessage());
   184             }
   185         }
   186     }
   187     
   188     private static String encodeURL(String r) throws UnsupportedEncodingException {
   189         final String SPECIAL = "%$&+,/:;=?@";
   190         StringBuilder sb = new StringBuilder();
   191         byte[] utf8 = r.getBytes("UTF-8");
   192         for (int i = 0; i < utf8.length; i++) {
   193             int ch = utf8[i] & 0xff;
   194             if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
   195                 final String numbers = "0" + Integer.toHexString(ch);
   196                 sb.append("%").append(numbers.substring(numbers.length() - 2));
   197             } else {
   198                 if (ch == 32) {
   199                     sb.append("+");
   200                 } else {
   201                     sb.append((char)ch);
   202                 }
   203             }
   204         }
   205         return sb.toString();
   206     }
   207     
   208     static String invoke(String clazz, String method) throws 
   209     ClassNotFoundException, InvocationTargetException, IllegalAccessException, 
   210     InstantiationException, InterruptedException {
   211         final Object r = new Case(null).invokeMethod(clazz, method);
   212         return r == null ? "null" : r.toString().toString();
   213     }
   214 
   215     /** Helper method that inspects the classpath and loads given resource
   216      * (usually a class file). Used while running tests in Rhino.
   217      * 
   218      * @param name resource name to find
   219      * @return the array of bytes in the given resource
   220      * @throws IOException I/O in case something goes wrong
   221      */
   222     public static byte[] read(String name) throws IOException {
   223         URL u = null;
   224         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   225         while (en.hasMoreElements()) {
   226             u = en.nextElement();
   227         }
   228         if (u == null) {
   229             throw new IOException("Can't find " + name);
   230         }
   231         InputStream is = null;
   232         try {
   233             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         } finally {
   246             if (is != null) is.close();
   247         }
   248     }
   249    
   250     private static void turnAssetionStatusOn() {
   251     }
   252 
   253     @JavaScriptBody(args = { "r", "time" }, body = "return window.setTimeout(function() { r.run(); }, 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 (String) value("methodName", data);
   270         }
   271 
   272         public String getClassName() {
   273             return (String) value("className", data);
   274         }
   275         
   276         public int getRequestId() {
   277             Object v = value("request", data);
   278             if (v instanceof Number) {
   279                 return ((Number)v).intValue();
   280             }
   281             return Integer.parseInt(v.toString());
   282         }
   283 
   284         public String getHtmlFragment() {
   285             return (String) value("html", data);
   286         }
   287         
   288         void again(Object[] arr) {
   289             try {
   290                 textArea = arr[0];
   291                 statusArea = arr[1];
   292                 setAttr(textArea, "value", "");
   293                 runTest();
   294             } catch (Exception ex) {
   295                 log(ex.getClass().getName() + ":" + ex.getMessage());
   296             }
   297         }
   298 
   299         private Object runTest() throws IllegalAccessException, 
   300         IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException, 
   301         InvocationTargetException, InstantiationException, InterruptedException {
   302             if (this.getHtmlFragment() != null) {
   303                 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
   304             }
   305             log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
   306             Object result = invokeMethod(this.getClassName(), this.getMethodName());
   307             setAttr("bck2brwsr.fragment", "innerHTML", "");
   308             log("Result: " + result);
   309             result = encodeURL("" + result);
   310             log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
   311             return result;
   312         }
   313 
   314         private Object invokeMethod(String clazz, String method)
   315         throws ClassNotFoundException, InvocationTargetException,
   316         InterruptedException, IllegalAccessException, IllegalArgumentException,
   317         InstantiationException {
   318             Method found = null;
   319             Class<?> c = Class.forName(clazz);
   320             for (Method m : c.getMethods()) {
   321                 if (m.getName().equals(method)) {
   322                     found = m;
   323                 }
   324             }
   325             Object res;
   326             if (found != null) {
   327                 try {
   328                     if ((found.getModifiers() & Modifier.STATIC) != 0) {
   329                         res = found.invoke(null);
   330                     } else {
   331                         if (inst == null) {
   332                             inst = c.newInstance();
   333                         }
   334                         res = found.invoke(inst);
   335                     }
   336                 } catch (Throwable ex) {
   337                     if (ex instanceof InvocationTargetException) {
   338                         ex = ((InvocationTargetException) ex).getTargetException();
   339                     }
   340                     if (ex instanceof InterruptedException) {
   341                         throw (InterruptedException)ex;
   342                     }
   343                     res = ex.getClass().getName() + ":" + ex.getMessage();
   344                 }
   345             } else {
   346                 res = "Can't find method " + method + " in " + clazz;
   347             }
   348             return res;
   349         }
   350 
   351         @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
   352         private static native Object toJSON(String s);
   353         
   354         private static Object value(String p, Object d) {
   355             return ((JSObject)d).getMember(p);
   356         }
   357     }
   358     
   359     static {
   360         turnAssetionStatusOn();
   361     }
   362 }