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