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