rt/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/impl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 01 Mar 2013 14:10:57 +0100
changeset 800 3661b82478e0
parent 772 d382dacfd73f
child 802 b975b19621c6
permissions -rw-r--r--
Allow execution in browser rather than Rhino. This should speed up our tests. Had to workaround Grizlly/Chrome misunderstanding about UTF-8
     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.lang.reflect.InvocationTargetException;
    23 import java.lang.reflect.Method;
    24 import java.lang.reflect.Modifier;
    25 import java.net.URL;
    26 import java.util.Enumeration;
    27 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    28 
    29 /**
    30  *
    31  * @author Jaroslav Tulach <jtulach@netbeans.org>
    32  */
    33 public class Console {
    34     private Console() {
    35     }
    36     static {
    37         turnAssetionStatusOn();
    38     }
    39     
    40     @JavaScriptBody(args = {"id", "attr"}, body = 
    41         "return window.document.getElementById(id)[attr].toString();")
    42     private static native Object getAttr(String id, String attr);
    43 
    44     @JavaScriptBody(args = {"id", "attr", "value"}, body = 
    45         "window.document.getElementById(id)[attr] = value;")
    46     private static native void setAttr(String id, String attr, Object value);
    47     
    48     @JavaScriptBody(args = {}, body = "return; window.close();")
    49     private static native void closeWindow();
    50 
    51     private static void log(String newText) {
    52         String id = "bck2brwsr.result";
    53         String attr = "value";
    54         setAttr(id, attr, getAttr(id, attr) + "\n" + newText);
    55         setAttr(id, "scrollTop", getAttr(id, "scrollHeight"));
    56     }
    57     
    58     public static void execute() throws Exception {
    59         String clazz = (String) getAttr("clazz", "value");
    60         String method = (String) getAttr("method", "value");
    61         Object res = invokeMethod(clazz, method);
    62         setAttr("bck2brwsr.result", "value", res);
    63     }
    64 
    65     @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
    66         + "var request = new XMLHttpRequest();\n"
    67         + "request.open('GET', url, true);\n"
    68         + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
    69         + "request.onreadystatechange = function() {\n"
    70         + "  if (this.readyState!==4) return;\n"
    71         + "  arr[0] = this.responseText;\n"
    72         + "  callback.run__V();\n"
    73         + "};"
    74         + "request.send();"
    75     )
    76     private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
    77     
    78     public static void harness(String url) throws IOException {
    79         log("Connecting to " + url);
    80         Request r = new Request(url);
    81     }
    82     
    83     private static class Request implements Runnable {
    84         private final String[] arr = { null };
    85         private final String url;
    86 
    87         private Request(String url) throws IOException {
    88             this.url = url;
    89             loadText(url, this, arr);
    90         }
    91         
    92         @Override
    93         public void run() {
    94             try {
    95                 String data = arr[0];
    96                 log("\nGot \"" + data + "\"");
    97                 
    98                 if (data == null) {
    99                     log("Some error exiting");
   100                     closeWindow();
   101                     return;
   102                 }
   103                 
   104                 if (data.isEmpty()) {
   105                     log("No data, exiting");
   106                     closeWindow();
   107                     return;
   108                 }
   109                 
   110                 Case c = Case.parseData(data);
   111                 if (c.getHtmlFragment() != null) {
   112                     setAttr("bck2brwsr.fragment", "innerHTML", c.getHtmlFragment());
   113                 }
   114                 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
   115 
   116                 Object result = invokeMethod(c.getClassName(), c.getMethodName());
   117                 
   118                 setAttr("bck2brwsr.fragment", "innerHTML", "");
   119                 log("Result: " + result);
   120                 
   121                 result = encodeURL("" + result);
   122                 
   123                 log("Sending back: " + url + "?request=" + c.getRequestId() + "&result=" + result);
   124                 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
   125                 
   126                 loadText(u, this, arr);
   127                 
   128             } catch (Exception ex) {
   129                 log(ex.getClass().getName() + ":" + ex.getMessage());
   130             }
   131         }
   132     }
   133     
   134     private static String encodeURL(String r) {
   135         StringBuilder sb = new StringBuilder();
   136         for (int i = 0; i < r.length(); i++) {
   137             int ch = r.charAt(i);
   138             if (ch < 32 || ch == '%' || ch == '+') {
   139                 sb.append("%").append(("0" + Integer.toHexString(ch)).substring(0, 2));
   140             } else {
   141                 if (ch == 32) {
   142                     sb.append("+");
   143                 } else {
   144                     sb.append((char)ch);
   145                 }
   146             }
   147         }
   148         return sb.toString();
   149     }
   150     
   151     static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
   152         final Object r = invokeMethod(clazz, method);
   153         return r == null ? "null" : r.toString().toString();
   154     }
   155 
   156     /** Helper method that inspects the classpath and loads given resource
   157      * (usually a class file). Used while running tests in Rhino.
   158      * 
   159      * @param name resource name to find
   160      * @return the array of bytes in the given resource
   161      * @throws IOException I/O in case something goes wrong
   162      */
   163     public static byte[] read(String name) throws IOException {
   164         URL u = null;
   165         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   166         while (en.hasMoreElements()) {
   167             u = en.nextElement();
   168         }
   169         if (u == null) {
   170             throw new IOException("Can't find " + name);
   171         }
   172         try (InputStream is = u.openStream()) {
   173             byte[] arr;
   174             arr = new byte[is.available()];
   175             int offset = 0;
   176             while (offset < arr.length) {
   177                 int len = is.read(arr, offset, arr.length - offset);
   178                 if (len == -1) {
   179                     throw new IOException("Can't read " + name);
   180                 }
   181                 offset += len;
   182             }
   183             return arr;
   184         }
   185     }
   186    
   187     private static Object invokeMethod(String clazz, String method) 
   188     throws ClassNotFoundException, InvocationTargetException, 
   189     SecurityException, IllegalAccessException, IllegalArgumentException,
   190     InstantiationException {
   191         Method found = null;
   192         Class<?> c = Class.forName(clazz);
   193         for (Method m : c.getMethods()) {
   194             if (m.getName().equals(method)) {
   195                 found = m;
   196             }
   197         }
   198         Object res;
   199         if (found != null) {
   200             try {
   201                 if ((found.getModifiers() & Modifier.STATIC) != 0) {
   202                     res = found.invoke(null);
   203                 } else {
   204                     res = found.invoke(c.newInstance());
   205                 }
   206             } catch (Throwable ex) {
   207                 res = ex.getClass().getName() + ":" + ex.getMessage();
   208             }
   209         } else {
   210             res = "Can't find method " + method + " in " + clazz;
   211         }
   212         return res;
   213     }
   214 
   215     @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
   216     private static void turnAssetionStatusOn() {
   217     }
   218     
   219     private static final class Case {
   220         private final Object data;
   221 
   222         private Case(Object data) {
   223             this.data = data;
   224         }
   225         
   226         public static Case parseData(String s) {
   227             return new Case(toJSON(s));
   228         }
   229         
   230         public String getMethodName() {
   231             return value("methodName", data);
   232         }
   233 
   234         public String getClassName() {
   235             return value("className", data);
   236         }
   237         
   238         public String getRequestId() {
   239             return value("request", data);
   240         }
   241 
   242         public String getHtmlFragment() {
   243             return value("html", data);
   244         }
   245         
   246         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   247         private static native Object toJSON(String s);
   248         
   249         @JavaScriptBody(args = {"p", "d"}, body = 
   250               "var v = d[p];\n"
   251             + "if (typeof v === 'undefined') return null;\n"
   252             + "return v.toString();"
   253         )
   254         private static native String value(String p, Object d);
   255     }
   256 }