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