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