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