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