launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 25 Dec 2012 14:07:02 +0100
changeset 381 70d15cf323ba
parent 366 ca2be963f3b9
child 412 777b9b841f15
permissions -rw-r--r--
Can execute the matrix multiplication test using VMTest
     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.net.URL;
    25 import java.net.URLDecoder;
    26 import java.net.URLEncoder;
    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     public static String welcome() {
    36         return "HellofromBck2Brwsr";
    37     }
    38     public static String multiply() {
    39         return String.valueOf(Integer.MAX_VALUE / 2 + Integer.MAX_VALUE);
    40     }
    41     
    42     @JavaScriptBody(args = {"id", "attr"}, body = 
    43         "return window.document.getElementById(id)[attr].toString();")
    44     private static native Object getAttr(String id, String attr);
    45 
    46     @JavaScriptBody(args = {"id", "attr", "value"}, body = 
    47         "window.document.getElementById(id)[attr] = value;")
    48     private static native void setAttr(String id, String attr, Object value);
    49     
    50     @JavaScriptBody(args = {}, body = "return; window.close();")
    51     private static native void closeWindow();
    52 
    53     private static void log(String newText) {
    54         String id = "result";
    55         String attr = "value";
    56         setAttr(id, attr, getAttr(id, attr) + "\n" + newText);
    57         setAttr(id, "scrollTop", getAttr(id, "scrollHeight"));
    58     }
    59     
    60     public static void execute() throws Exception {
    61         String clazz = (String) getAttr("clazz", "value");
    62         String method = (String) getAttr("method", "value");
    63         Object res = invokeMethod(clazz, method);
    64         setAttr("result", "value", res);
    65     }
    66     
    67     public static void harness(String url) {
    68         log("Connecting to " + url);
    69         try {
    70             URL u = new URL(url);
    71             for (;;) {
    72                 String data = (String) u.getContent(new Class[] { String.class });
    73                 log("\nGot \"" + data + "\"");
    74                 if (data.isEmpty()) {
    75                     log("No data, exiting");
    76                     closeWindow();
    77                     break;
    78                 }
    79                 
    80                 Case c = Case.parseData(data);
    81                 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
    82 
    83                 Object result = invokeMethod(c.getClassName(), c.getMethodName());
    84                 
    85                 log("Result: " + result);
    86                 
    87                 result = encodeURL("" + result);
    88                 
    89                 log("Sending back: " + url + "?request=" + c.getRequestId() + "&result=" + result);
    90                 u = new URL(url + "?request=" + c.getRequestId() + "&result=" + result);
    91             }
    92             
    93             
    94         } catch (Exception ex) {
    95             log(ex.getMessage());
    96         }
    97     }
    98     
    99     private static String encodeURL(String r) {
   100         StringBuilder sb = new StringBuilder();
   101         for (int i = 0; i < r.length(); i++) {
   102             int ch = r.charAt(i);
   103             if (ch < 32 || ch == '%' || ch == '+') {
   104                 sb.append("%").append(("0" + Integer.toHexString(ch)).substring(0, 2));
   105             } else {
   106                 if (ch == 32) {
   107                     sb.append("+");
   108                 } else {
   109                     sb.append((char)ch);
   110                 }
   111             }
   112         }
   113         return sb.toString();
   114     }
   115     
   116     static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
   117         final Object r = invokeMethod(clazz, method);
   118         return r == null ? "null" : r.toString().toString();
   119     }
   120 
   121     /** Helper method that inspects the classpath and loads given resource
   122      * (usually a class file). Used while running tests in Rhino.
   123      * 
   124      * @param name resource name to find
   125      * @return the array of bytes in the given resource
   126      * @throws IOException I/O in case something goes wrong
   127      */
   128     public static byte[] read(String name) throws IOException {
   129         URL u = null;
   130         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   131         while (en.hasMoreElements()) {
   132             u = en.nextElement();
   133         }
   134         if (u == null) {
   135             throw new IOException("Can't find " + name);
   136         }
   137         try (InputStream is = u.openStream()) {
   138             byte[] arr;
   139             arr = new byte[is.available()];
   140             int offset = 0;
   141             while (offset < arr.length) {
   142                 int len = is.read(arr, offset, arr.length - offset);
   143                 if (len == -1) {
   144                     throw new IOException("Can't read " + name);
   145                 }
   146                 offset += len;
   147             }
   148             return arr;
   149         }
   150     }
   151    
   152     private static Object invokeMethod(String clazz, String method) 
   153     throws ClassNotFoundException, InvocationTargetException, 
   154     SecurityException, IllegalAccessException, IllegalArgumentException {
   155         Method found = null;
   156         Class<?> c = Class.forName(clazz);
   157         for (Method m : c.getMethods()) {
   158             if (m.getName().equals(method)) {
   159                 found = m;
   160             }
   161         }
   162         Object res;
   163         if (found != null) {
   164             res = found.invoke(null);
   165         } else {
   166             res = "Can't find method " + method + " in " + clazz;
   167         }
   168         return res;
   169     }
   170     
   171     private static final class Case {
   172         private final Object data;
   173 
   174         private Case(Object data) {
   175             this.data = data;
   176         }
   177         
   178         public static Case parseData(String s) {
   179             return new Case(toJSON(s));
   180         }
   181         
   182         public String getMethodName() {
   183             return value("methodName", data);
   184         }
   185 
   186         public String getClassName() {
   187             return value("className", data);
   188         }
   189         
   190         public String getRequestId() {
   191             return value("request", data);
   192         }
   193         
   194         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   195         private static native Object toJSON(String s);
   196         
   197         @JavaScriptBody(args = {"p", "d"}, body = "return d[p].toString();")
   198         private static native String value(String p, Object d);
   199     }
   200 }