rt/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/impl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 707 launcher/src/main/java/org/apidesign/bck2brwsr/launcher/impl/Console.java@a9187d4aaa6b
child 800 3661b82478e0
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
     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.onreadystatechange = function() {\n"
    69         + "  if (this.readyState!==4) return;\n"
    70         + "  arr[0] = this.responseText;\n"
    71         + "  callback.run__V();\n"
    72         + "};"
    73         + "request.send();"
    74     )
    75     private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
    76     
    77     public static void harness(String url) throws IOException {
    78         log("Connecting to " + url);
    79         Request r = new Request(url);
    80     }
    81     
    82     private static class Request implements Runnable {
    83         private final String[] arr = { null };
    84         private final String url;
    85 
    86         private Request(String url) throws IOException {
    87             this.url = url;
    88             loadText(url, this, arr);
    89         }
    90         
    91         @Override
    92         public void run() {
    93             try {
    94                 String data = arr[0];
    95                 log("\nGot \"" + data + "\"");
    96                 
    97                 if (data == null) {
    98                     log("Some error exiting");
    99                     closeWindow();
   100                     return;
   101                 }
   102                 
   103                 if (data.isEmpty()) {
   104                     log("No data, exiting");
   105                     closeWindow();
   106                     return;
   107                 }
   108                 
   109                 Case c = Case.parseData(data);
   110                 if (c.getHtmlFragment() != null) {
   111                     setAttr("bck2brwsr.fragment", "innerHTML", c.getHtmlFragment());
   112                 }
   113                 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
   114 
   115                 Object result = invokeMethod(c.getClassName(), c.getMethodName());
   116                 
   117                 setAttr("bck2brwsr.fragment", "innerHTML", "");
   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.getClass().getName() + ":" + 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 (Throwable 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         public String getHtmlFragment() {
   242             return value("html", data);
   243         }
   244         
   245         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   246         private static native Object toJSON(String s);
   247         
   248         @JavaScriptBody(args = {"p", "d"}, body = 
   249               "var v = d[p];\n"
   250             + "if (typeof v === 'undefined') return null;\n"
   251             + "return v.toString();"
   252         )
   253         private static native String value(String p, Object d);
   254     }
   255 }