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