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