launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 20 Dec 2012 21:54:33 +0100
branchlauncher
changeset 360 86f3ea771e24
parent 356 e078953818d2
child 366 ca2be963f3b9
permissions -rw-r--r--
Moving the read method closer to the definition of the script
     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.util.Enumeration;
    26 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    27 
    28 /**
    29  *
    30  * @author Jaroslav Tulach <jtulach@netbeans.org>
    31  */
    32 public class Console {
    33     public static String welcome() {
    34         return "HellofromBck2Brwsr";
    35     }
    36     public static String multiply() {
    37         return String.valueOf(Integer.MAX_VALUE / 2 + Integer.MAX_VALUE);
    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     private static void log(String newText) {
    49         String id = "result";
    50         String attr = "value";
    51         setAttr(id, attr, getAttr(id, attr) + "\n" + newText);
    52         setAttr(id, "scrollTop", getAttr(id, "scrollHeight"));
    53     }
    54     
    55     public static void execute() throws Exception {
    56         String clazz = (String) getAttr("clazz", "value");
    57         String method = (String) getAttr("method", "value");
    58         Object res = invokeMethod(clazz, method);
    59         setAttr("result", "value", res);
    60     }
    61     
    62     public static void harness(String url) {
    63         log("Connecting to " + url);
    64         try {
    65             URL u = new URL(url);
    66             for (;;) {
    67                 String data = (String) u.getContent(new Class[] { String.class });
    68                 log("\nGot \"" + data + "\"");
    69                 if (data.isEmpty()) {
    70                     log("No data, exiting");
    71                     break;
    72                 }
    73                 
    74                 Case c = Case.parseData(data);
    75                 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
    76 
    77                 Object result = invokeMethod(c.getClassName(), c.getMethodName());
    78                 
    79                 log("Result: " + result);
    80                 log("Sending back: " + url + "?request=" + c.getRequestId() + "&result=" + result);
    81                 u = new URL(url + "?request=" + c.getRequestId() + "&result=" + result);
    82             }
    83             
    84             
    85         } catch (Exception ex) {
    86             log(ex.getMessage());
    87         }
    88     }
    89     
    90     static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
    91         final Object r = invokeMethod(clazz, method);
    92         return r == null ? "null" : r.toString().toString();
    93     }
    94 
    95     /** Helper method that inspects the classpath and loads given resource
    96      * (usually a class file). Used while running tests in Rhino.
    97      * 
    98      * @param name resource name to find
    99      * @return the array of bytes in the given resource
   100      * @throws IOException I/O in case something goes wrong
   101      */
   102     public static byte[] read(String name) throws IOException {
   103         URL u = null;
   104         Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   105         while (en.hasMoreElements()) {
   106             u = en.nextElement();
   107         }
   108         if (u == null) {
   109             throw new IOException("Can't find " + name);
   110         }
   111         try (InputStream is = u.openStream()) {
   112             byte[] arr;
   113             arr = new byte[is.available()];
   114             int offset = 0;
   115             while (offset < arr.length) {
   116                 int len = is.read(arr, offset, arr.length - offset);
   117                 if (len == -1) {
   118                     throw new IOException("Can't read " + name);
   119                 }
   120                 offset += len;
   121             }
   122             return arr;
   123         }
   124     }
   125    
   126     private static Object invokeMethod(String clazz, String method) 
   127     throws ClassNotFoundException, InvocationTargetException, 
   128     SecurityException, IllegalAccessException, IllegalArgumentException {
   129         Method found = null;
   130         Class<?> c = Class.forName(clazz);
   131         for (Method m : c.getMethods()) {
   132             if (m.getName().equals(method)) {
   133                 found = m;
   134             }
   135         }
   136         Object res;
   137         if (found != null) {
   138             res = found.invoke(null);
   139         } else {
   140             res = "Can't find method " + method + " in " + clazz;
   141         }
   142         return res;
   143     }
   144     
   145     private static final class Case {
   146         private final Object data;
   147 
   148         private Case(Object data) {
   149             this.data = data;
   150         }
   151         
   152         public static Case parseData(String s) {
   153             return new Case(toJSON(s));
   154         }
   155         
   156         public String getMethodName() {
   157             return value("methodName", data);
   158         }
   159 
   160         public String getClassName() {
   161             return value("className", data);
   162         }
   163         
   164         public String getRequestId() {
   165             return value("request", data);
   166         }
   167         
   168         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   169         private static native Object toJSON(String s);
   170         
   171         @JavaScriptBody(args = {"p", "d"}, body = "return d[p].toString();")
   172         private static native String value(String p, Object d);
   173     }
   174 }