launcher/http/src/main/java/org/apidesign/bck2brwsr/launcher/impl/Console.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 26 Apr 2015 10:58:52 +0300
changeset 1827 f07753959dcf
parent 1787 ea12a3bb4b33
child 1860 4ce38f21f4cd
permissions -rw-r--r--
Automatically close the browser windows unless such action gets canceled.
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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 @org.apidesign.bck2brwsr.core.Exported 
    35 public class Console {
    36     private Console() {
    37     }
    38     static {
    39         turnAssetionStatusOn();
    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     @JavaScriptBody(args = {"elem", "attr"}, body = 
    46         "return elem[attr].toString();")
    47     private static native Object getAttr(Object elem, String attr);
    48 
    49     @JavaScriptBody(args = {"id", "attr", "value"}, body = 
    50         "window.document.getElementById(id)[attr] = value;")
    51     private static native void setAttr(String id, String attr, Object value);
    52     @JavaScriptBody(args = {"elem", "attr", "value"}, body = 
    53         "elem[attr] = value;")
    54     private static native void setAttr(Object id, String attr, Object value);
    55     
    56     @net.java.html.js.JavaScriptBody(args = {  }, body = 
    57         "var a = document.createElement('a');"
    58       + "a.innerHTML = 'Cancel: closing in 10s...';\n"
    59       + "a.href = '#';\n"
    60       + "var closing = window.setTimeout(function() { window.close(); }, 10000);\n"
    61       + "a.onclick = function() { clearTimeout(closing); document.body.removeChild(a); };\n"
    62       + "document.body.appendChild(a);\n" +
    63         "return;\n"
    64     )
    65     static native void closeWindow();
    66 
    67     private static Object textArea;
    68     private static Object statusArea;
    69     
    70     private static void log(String newText) {
    71         if (textArea == null) {
    72             return;
    73         }
    74         String attr = "value";
    75         setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
    76         setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
    77     }
    78     
    79     private static void beginTest(Case c) {
    80         Object[] arr = new Object[2];
    81         beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
    82         textArea = arr[0];
    83         statusArea = arr[1];
    84     }
    85     
    86     private static void finishTest(Case c, Object res) {
    87         if ("null".equals(res)) {
    88             setAttr(statusArea, "innerHTML", "Success");
    89         } else {
    90             setAttr(statusArea, "innerHTML", "Result " + res);
    91         }
    92         statusArea = null;
    93         textArea = null;
    94     }
    95 
    96     @JavaScriptBody(args = { "test", "c", "arr" }, body = 
    97           "var ul = window.document.getElementById('bck2brwsr.result');\n"
    98         + "var li = window.document.createElement('li');\n"
    99         + "var span = window.document.createElement('span');"
   100         + "span.innerHTML = test + ' - ';\n"
   101         + "var details = window.document.createElement('a');\n"
   102         + "details.innerHTML = 'Details';\n"
   103         + "details.href = '#';\n"
   104         + "var p = window.document.createElement('p');\n"
   105         + "var status = window.document.createElement('a');\n"
   106         + "status.innerHTML = 'running';"
   107         + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
   108         + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
   109         + "var pre = window.document.createElement('textarea');\n"
   110         + "pre.cols = 100;"
   111         + "pre.rows = 10;"
   112         + "li.appendChild(span);\n"
   113         + "li.appendChild(status);\n"
   114         + "var span = window.document.createElement('span');"
   115         + "span.innerHTML = ' ';\n"
   116         + "li.appendChild(span);\n"
   117         + "li.appendChild(details);\n"
   118         + "p.appendChild(pre);\n"
   119         + "ul.appendChild(li);\n"
   120         + "arr[0] = pre;\n"
   121         + "arr[1] = status;\n"
   122     )
   123     private static native void beginTest(String test, Case c, Object[] arr);
   124     
   125     @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
   126         + "var request = new XMLHttpRequest();\n"
   127         + "request.open('GET', url, true);\n"
   128         + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
   129         + "request.onreadystatechange = function() {\n"
   130         + "  if (this.readyState!==4) return;\n"
   131         + "  arr[0] = this.responseText;\n"
   132         + "  callback.run__V();\n"
   133         + "};"
   134         + "request.send();"
   135     )
   136     private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
   137     
   138     public static void harness(String url) throws IOException {
   139         log("Connecting to " + url);
   140         Request r = new Request(url);
   141     }
   142     
   143     private static class Request implements Runnable {
   144         private final String[] arr = { null };
   145         private final String url;
   146         private Case c;
   147         private int retries;
   148 
   149         private Request(String url) throws IOException {
   150             this.url = url;
   151             loadText(url, this, arr);
   152         }
   153         private Request(String url, String u) throws IOException {
   154             this.url = url;
   155             loadText(u, this, arr);
   156         }
   157         
   158         @Override
   159         public void run() {
   160             try {
   161                 if (c == null) {
   162                     String data = arr[0];
   163 
   164                     if (data == null) {
   165                         log("Some error exiting");
   166                         closeWindow();
   167                         return;
   168                     }
   169 
   170                     if (data.isEmpty()) {
   171                         log("No data, exiting");
   172                         closeWindow();
   173                         return;
   174                     }
   175 
   176                     c = Case.parseData(data);
   177                     beginTest(c);
   178                     log("Got \"" + data + "\"");
   179                 } else {
   180                     log("Processing \"" + arr[0] + "\" for " + retries + " time");
   181                 }
   182                 Object result = retries++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
   183                 finishTest(c, result);
   184                 
   185                 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
   186                 new Request(url, u);
   187             } catch (Exception ex) {
   188                 if (ex instanceof InterruptedException) {
   189                     log("Re-scheduling in 100ms");
   190                     schedule(this, 100);
   191                     return;
   192                 }
   193                 log(ex.getClass().getName() + ":" + ex.getMessage());
   194             }
   195         }
   196     }
   197     
   198     private static String encodeURL(String r) throws UnsupportedEncodingException {
   199         final String SPECIAL = "%$&+,/:;=?@";
   200         StringBuilder sb = new StringBuilder();
   201         byte[] utf8 = r.getBytes("UTF-8");
   202         for (int i = 0; i < utf8.length; i++) {
   203             int ch = utf8[i] & 0xff;
   204             if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
   205                 final String numbers = "0" + Integer.toHexString(ch);
   206                 sb.append("%").append(numbers.substring(numbers.length() - 2));
   207             } else {
   208                 if (ch == 32) {
   209                     sb.append("+");
   210                 } else {
   211                     sb.append((char)ch);
   212                 }
   213             }
   214         }
   215         return sb.toString();
   216     }
   217     
   218     static String invoke(String clazz, String method) throws 
   219     ClassNotFoundException, InvocationTargetException, IllegalAccessException, 
   220     InstantiationException, InterruptedException {
   221         final Object r = new Case(null).invokeMethod(clazz, method);
   222         return r == null ? "null" : r.toString().toString();
   223     }
   224 
   225     /** Helper method that inspects the classpath and loads given resource
   226      * (usually a class file). Used while running tests in Rhino.
   227      * 
   228      * @param name resource name to find
   229      * @return the array of bytes in the given resource
   230      * @throws IOException I/O in case something goes wrong
   231      */
   232     public static byte[] read(String name, int skip) throws IOException {
   233         URL u = null;
   234         if (!name.endsWith(".class")) {
   235             u = getResource(name, skip);
   236         } else {
   237             Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
   238             while (en.hasMoreElements()) {
   239                 u = en.nextElement();
   240             }
   241         }
   242         if (u == null) {
   243             if (name.endsWith(".class")) {
   244                 throw new IOException("Can't find " + name);
   245             } else {
   246                 return null;
   247             }
   248         }
   249         try (InputStream is = u.openStream()) {
   250             byte[] arr;
   251             arr = new byte[is.available()];
   252             int offset = 0;
   253             while (offset < arr.length) {
   254                 int len = is.read(arr, offset, arr.length - offset);
   255                 if (len == -1) {
   256                     throw new IOException("Can't read " + name);
   257                 }
   258                 offset += len;
   259             }
   260             return arr;
   261         }
   262     }
   263    
   264     private static URL getResource(String resource, int skip) throws IOException {
   265         URL u = null;
   266         Enumeration<URL> en = Console.class.getClassLoader().getResources(resource);
   267         while (en.hasMoreElements()) {
   268             final URL now = en.nextElement();
   269             if (--skip < 0) {
   270                 u = now;
   271                 break;
   272             }
   273         }
   274         return u;
   275     }
   276     
   277     @JavaScriptBody(args = {}, body = "vm['java_lang_Class'](false)['desiredAssertionStatus'] = true;")
   278     private static void turnAssetionStatusOn() {
   279     }
   280 
   281     @JavaScriptBody(args = {"r", "time"}, body =
   282         "return window.setTimeout(function() { r.run__V(); }, time);")
   283     private static native Object schedule(Runnable r, int time);
   284     
   285     private static final class Case {
   286         private final Object data;
   287         private Object inst;
   288 
   289         private Case(Object data) {
   290             this.data = data;
   291         }
   292         
   293         public static Case parseData(String s) {
   294             return new Case(toJSON(s));
   295         }
   296         
   297         public String getMethodName() {
   298             return value("methodName", data);
   299         }
   300 
   301         public String getClassName() {
   302             return value("className", data);
   303         }
   304         
   305         public String getRequestId() {
   306             return value("request", data);
   307         }
   308 
   309         public String getHtmlFragment() {
   310             return value("html", data);
   311         }
   312         
   313         void again(Object[] arr) {
   314             try {
   315                 textArea = arr[0];
   316                 statusArea = arr[1];
   317                 setAttr(textArea, "value", "");
   318                 runTest();
   319             } catch (Exception ex) {
   320                 log(ex.getClass().getName() + ":" + ex.getMessage());
   321             }
   322         }
   323 
   324         private Object runTest() throws IllegalAccessException, 
   325         IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException, 
   326         InvocationTargetException, InstantiationException, InterruptedException {
   327             if (this.getHtmlFragment() != null) {
   328                 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
   329             }
   330             log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
   331             Object result = invokeMethod(this.getClassName(), this.getMethodName());
   332             setAttr("bck2brwsr.fragment", "innerHTML", "");
   333             log("Result: " + result);
   334             result = encodeURL("" + result);
   335             log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
   336             return result;
   337         }
   338 
   339         private Object invokeMethod(String clazz, String method)
   340         throws ClassNotFoundException, InvocationTargetException,
   341         InterruptedException, IllegalAccessException, IllegalArgumentException,
   342         InstantiationException {
   343             Method found = null;
   344             Class<?> c = Class.forName(clazz);
   345             for (Method m : c.getMethods()) {
   346                 if (m.getName().equals(method)) {
   347                     found = m;
   348                 }
   349             }
   350             Object res;
   351             if (found != null) {
   352                 try {
   353                     if ((found.getModifiers() & Modifier.STATIC) != 0) {
   354                         res = found.invoke(null);
   355                     } else {
   356                         if (inst == null) {
   357                             inst = c.newInstance();
   358                         }
   359                         res = found.invoke(inst);
   360                     }
   361                 } catch (Throwable ex) {
   362                     if (ex instanceof InvocationTargetException) {
   363                         ex = ((InvocationTargetException) ex).getTargetException();
   364                     }
   365                     if (ex instanceof InterruptedException) {
   366                         throw (InterruptedException)ex;
   367                     }
   368                     res = ex.getClass().getName() + ":" + ex.getMessage();
   369                 }
   370             } else {
   371                 res = "Can't find method " + method + " in " + clazz;
   372             }
   373             return res;
   374         }
   375         
   376         @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
   377         private static native Object toJSON(String s);
   378         
   379         @JavaScriptBody(args = {"p", "d"}, body = 
   380               "var v = d[p];\n"
   381             + "if (typeof v === 'undefined') return null;\n"
   382             + "return v.toString();"
   383         )
   384         private static native String value(String p, Object d);
   385     }
   386 }