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