launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 22 Jan 2013 19:16:38 +0100
changeset 526 a0d8b5ab79a2
parent 519 aeb076729a8a
child 527 de22f66d685f
permissions -rw-r--r--
@BrwsrTest can reference @HtmlFragment and manipulate it
     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 = "bck2brwsr.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("bck2brwsr.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                 if (c.getHtmlFragment() != null) {
   115                     setAttr("bck2brwsr.fragment", "innerHTML", c.getHtmlFragment());
   116                 }
   117                 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
   118 
   119                 Object result = invokeMethod(c.getClassName(), c.getMethodName());
   120                 
   121                 setAttr("bck2brwsr.fragment", "innerHTML", "");
   122                 log("Result: " + result);
   123                 
   124                 result = encodeURL("" + result);
   125                 
   126                 log("Sending back: " + url + "?request=" + c.getRequestId() + "&result=" + result);
   127                 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
   128                 
   129                 loadText(u, this, arr);
   130                 
   131             } catch (Exception ex) {
   132                 log(ex.getMessage());
   133             }
   134         }
   135     }
   136     
   137     private static String encodeURL(String r) {
   138         StringBuilder sb = new StringBuilder();
   139         for (int i = 0; i < r.length(); i++) {
   140             int ch = r.charAt(i);
   141             if (ch < 32 || ch == '%' || ch == '+') {
   142                 sb.append("%").append(("0" + Integer.toHexString(ch)).substring(0, 2));
   143             } else {
   144                 if (ch == 32) {
   145                     sb.append("+");
   146                 } else {
   147                     sb.append((char)ch);
   148                 }
   149             }
   150         }
   151         return sb.toString();
   152     }
   153     
   154     static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
   155         final Object r = invokeMethod(clazz, method);
   156         return r == null ? "null" : r.toString().toString();
   157     }
   158 
   159     /** Helper method that inspects the classpath and loads given resource
   160      * (usually a class file). Used while running tests in Rhino.
   161      * 
   162      * @param name resource name to find
   163      * @return the array of bytes in the given resource
   164      * @throws IOException I/O in case something goes wrong
   165      */
   166     public static byte[] read(String name) throws IOException {
   167         URL u = null;
   168         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   169         while (en.hasMoreElements()) {
   170             u = en.nextElement();
   171         }
   172         if (u == null) {
   173             throw new IOException("Can't find " + name);
   174         }
   175         try (InputStream is = u.openStream()) {
   176             byte[] arr;
   177             arr = new byte[is.available()];
   178             int offset = 0;
   179             while (offset < arr.length) {
   180                 int len = is.read(arr, offset, arr.length - offset);
   181                 if (len == -1) {
   182                     throw new IOException("Can't read " + name);
   183                 }
   184                 offset += len;
   185             }
   186             return arr;
   187         }
   188     }
   189    
   190     private static Object invokeMethod(String clazz, String method) 
   191     throws ClassNotFoundException, InvocationTargetException, 
   192     SecurityException, IllegalAccessException, IllegalArgumentException,
   193     InstantiationException {
   194         Method found = null;
   195         Class<?> c = Class.forName(clazz);
   196         for (Method m : c.getMethods()) {
   197             if (m.getName().equals(method)) {
   198                 found = m;
   199             }
   200         }
   201         Object res;
   202         if (found != null) {
   203             try {
   204                 if ((found.getModifiers() & Modifier.STATIC) != 0) {
   205                     res = found.invoke(null);
   206                 } else {
   207                     res = found.invoke(c.newInstance());
   208                 }
   209             } catch (Exception | Error ex) {
   210                 res = ex.getClass().getName() + ":" + ex.getMessage();
   211             }
   212         } else {
   213             res = "Can't find method " + method + " in " + clazz;
   214         }
   215         return res;
   216     }
   217 
   218     @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
   219     private static void turnAssetionStatusOn() {
   220     }
   221     
   222     private static final class Case {
   223         private final Object data;
   224 
   225         private Case(Object data) {
   226             this.data = data;
   227         }
   228         
   229         public static Case parseData(String s) {
   230             return new Case(toJSON(s));
   231         }
   232         
   233         public String getMethodName() {
   234             return value("methodName", data);
   235         }
   236 
   237         public String getClassName() {
   238             return value("className", data);
   239         }
   240         
   241         public String getRequestId() {
   242             return value("request", data);
   243         }
   244 
   245         public String getHtmlFragment() {
   246             return value("html", data);
   247         }
   248         
   249         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   250         private static native Object toJSON(String s);
   251         
   252         @JavaScriptBody(args = {"p", "d"}, body = 
   253               "var v = d[p];\n"
   254             + "if (typeof v === 'undefined') return null;\n"
   255             + "return v.toString();"
   256         )
   257         private static native String value(String p, Object d);
   258     }
   259 }