launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 20 Dec 2012 11:03:34 +0100
branchlauncher
changeset 356 e078953818d2
parent 349 3fe5a86bd123
child 357 dc375a56fd15
permissions -rw-r--r--
Using the Console for invoking VMTests in Rhino. All tests are passing now.
     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.awt.Desktop;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import java.io.InterruptedIOException;
    24 import java.io.OutputStream;
    25 import java.io.Writer;
    26 import java.net.URI;
    27 import java.net.URISyntaxException;
    28 import java.net.URL;
    29 import java.util.ArrayList;
    30 import java.util.Enumeration;
    31 import java.util.LinkedHashSet;
    32 import java.util.List;
    33 import java.util.Set;
    34 import java.util.concurrent.CountDownLatch;
    35 import java.util.concurrent.TimeUnit;
    36 import java.util.logging.Level;
    37 import java.util.logging.Logger;
    38 import javax.script.Invocable;
    39 import javax.script.ScriptEngine;
    40 import javax.script.ScriptEngineManager;
    41 import javax.script.ScriptException;
    42 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
    43 import org.apidesign.vm4brwsr.Bck2Brwsr;
    44 import org.glassfish.grizzly.PortRange;
    45 import org.glassfish.grizzly.http.server.HttpHandler;
    46 import org.glassfish.grizzly.http.server.HttpServer;
    47 import org.glassfish.grizzly.http.server.NetworkListener;
    48 import org.glassfish.grizzly.http.server.Request;
    49 import org.glassfish.grizzly.http.server.Response;
    50 import org.glassfish.grizzly.http.server.ServerConfiguration;
    51 
    52 /**
    53  * Lightweight server to launch Bck2Brwsr applications in real browser.
    54  */
    55 public class Bck2BrwsrLauncher {
    56     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    57     private List<MethodInvocation> methods = new ArrayList<>();
    58     private long timeOut;
    59     private String sen;
    60     
    61     
    62     public MethodInvocation addMethod(Class<?> clazz, String method) {
    63         loaders.add(clazz.getClassLoader());
    64         MethodInvocation c = new MethodInvocation(clazz.getName(), method);
    65         methods.add(c);
    66         return c;
    67     }
    68     
    69     public void setTimeout(long ms) {
    70         timeOut = ms;
    71     }
    72     
    73     public void setScriptEngineName(String sen) {
    74         this.sen = sen;
    75     }
    76     
    77     public static void main( String[] args ) throws Exception {
    78         Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
    79         
    80         final MethodInvocation[] cases = { 
    81             l.addMethod(Console.class, "welcome"),
    82             l.addMethod(Console.class, "multiply"),
    83         };
    84         
    85         l.execute();
    86         
    87         for (MethodInvocation c : cases) {
    88             System.err.println(c.className + "." + c.methodName + " = " + c.result);
    89         }
    90     }
    91 
    92 
    93     public void execute() throws IOException {
    94         try {
    95             if (sen != null) {
    96                 executeRhino();
    97             } else {
    98                 executeInBrowser();
    99             }
   100         } catch (InterruptedException ex) {
   101             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   102             iio.initCause(ex);
   103             throw iio;
   104         } catch (Exception ex) {
   105             if (ex instanceof IOException) {
   106                 throw (IOException)ex;
   107             }
   108             if (ex instanceof RuntimeException) {
   109                 throw (RuntimeException)ex;
   110             }
   111             throw new IOException(ex);
   112         }
   113     }
   114     
   115     private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
   116         StringBuilder sb = new StringBuilder();
   117         Bck2Brwsr.generate(sb, new Res());
   118 
   119         ScriptEngineManager sem = new ScriptEngineManager();
   120         ScriptEngine mach = sem.getEngineByExtension(sen);
   121 
   122         sb.append(
   123               "\nvar vm = bck2brwsr(org.apidesign.bck2brwsr.vmtest.VMTest.read);"
   124             + "\nfunction initVM() { return vm; };"
   125             + "\n");
   126 
   127         Object res = mach.eval(sb.toString());
   128         if (!(mach instanceof Invocable)) {
   129             throw new IOException("It is invocable object: " + res);
   130         }
   131         Invocable code = (Invocable) mach;
   132         
   133         Object vm = code.invokeFunction("initVM");
   134         Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
   135 
   136         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   137         for (MethodInvocation mi : cases) {
   138             mi.result = code.invokeMethod(console, 
   139                 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2", 
   140                 mi.className, mi.methodName
   141             ).toString();
   142         }
   143     }
   144     
   145     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   146         final CountDownLatch wait = new CountDownLatch(1);
   147         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   148         
   149         HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
   150         
   151         Res resources = new Res();
   152         
   153         final ServerConfiguration conf = server.getServerConfiguration();
   154         conf.addHttpHandler(new Page("console.xhtml", 
   155             "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
   156         ), "/console");
   157         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   158         conf.addHttpHandler(new VMInit(), "/vm.js");
   159         conf.addHttpHandler(new Classes(resources), "/classes/");
   160         conf.addHttpHandler(new HttpHandler() {
   161             int cnt;
   162             @Override
   163             public void service(Request request, Response response) throws Exception {
   164                 String id = request.getParameter("request");
   165                 String value = request.getParameter("result");
   166                 if (id != null && value != null) {
   167                     value = value.replace("%20", " ");
   168                     cases[Integer.parseInt(id)].result = value;
   169                 }
   170                 
   171                 if (cnt >= cases.length) {
   172                     response.getWriter().write("");
   173                     wait.countDown();
   174                     cnt = 0;
   175                     return;
   176                 }
   177                 
   178                 response.getWriter().write("{"
   179                     + "className: '" + cases[cnt].className + "', "
   180                     + "methodName: '" + cases[cnt].methodName + "', "
   181                     + "request: " + cnt
   182                     + "}");
   183                 cnt++;
   184             }
   185         }, "/data");
   186         conf.addHttpHandler(new Page("harness.xhtml"), "/");
   187         
   188         server.start();
   189         NetworkListener listener = server.getListeners().iterator().next();
   190         int port = listener.getPort();
   191         
   192         URI uri = new URI("http://localhost:" + port + "/execute");
   193         try {
   194             Desktop.getDesktop().browse(uri);
   195         } catch (UnsupportedOperationException ex) {
   196             String[] cmd = { 
   197                 "xdg-open", uri.toString()
   198             };
   199             Runtime.getRuntime().exec(cmd).waitFor();
   200         }
   201         
   202         wait.await(timeOut, TimeUnit.MILLISECONDS);
   203         server.stop();
   204     }
   205     
   206     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   207         for (;;) {
   208             int ch = is.read();
   209             if (ch == -1) {
   210                 break;
   211             }
   212             if (ch == '$') {
   213                 int cnt = is.read() - '0';
   214                 if (cnt == 'U' - '0') {
   215                     os.write(baseURL.getBytes());
   216                 }
   217                 if (cnt < params.length) {
   218                     os.write(params[cnt].getBytes());
   219                 }
   220             } else {
   221                 os.write(ch);
   222             }
   223         }
   224     }
   225 
   226     private class Res implements Bck2Brwsr.Resources {
   227         @Override
   228         public InputStream get(String resource) throws IOException {
   229             for (ClassLoader l : loaders) {
   230                 URL u = null;
   231                 Enumeration<URL> en = l.getResources(resource);
   232                 while (en.hasMoreElements()) {
   233                     u = en.nextElement();
   234                 }
   235                 if (u != null) {
   236                     return u.openStream();
   237                 }
   238             }
   239             throw new IOException("Can't find " + resource);
   240         }
   241     }
   242 
   243     private static class Page extends HttpHandler {
   244         private final String resource;
   245         private final String[] args;
   246         
   247         public Page(String resource, String... args) {
   248             this.resource = resource;
   249             this.args = args;
   250         }
   251 
   252         @Override
   253         public void service(Request request, Response response) throws Exception {
   254             response.setContentType("text/html");
   255             OutputStream os = response.getOutputStream();
   256             InputStream is = Bck2BrwsrLauncher.class.getResourceAsStream(resource);
   257             copyStream(is, os, request.getRequestURL().toString(), args);
   258         }
   259     }
   260 
   261     private static class VM extends HttpHandler {
   262         private final Res loader;
   263 
   264         public VM(Res loader) {
   265             this.loader = loader;
   266         }
   267 
   268         @Override
   269         public void service(Request request, Response response) throws Exception {
   270             response.setCharacterEncoding("UTF-8");
   271             response.setContentType("text/javascript");
   272             Bck2Brwsr.generate(response.getWriter(), loader);
   273         }
   274     }
   275     private static class VMInit extends HttpHandler {
   276         public VMInit() {
   277         }
   278 
   279         @Override
   280         public void service(Request request, Response response) throws Exception {
   281             response.setCharacterEncoding("UTF-8");
   282             response.setContentType("text/javascript");
   283             response.getWriter().append(
   284                 "function ldCls(res) {\n"
   285                 + "  var request = new XMLHttpRequest();\n"
   286                 + "  request.open('GET', 'classes/' + res, false);\n"
   287                 + "  request.send();\n"
   288                 + "  var arr = eval('(' + request.responseText + ')');\n"
   289                 + "  return arr;\n"
   290                 + "}\n"
   291                 + "var vm = new bck2brwsr(ldCls);\n");
   292         }
   293     }
   294 
   295     private static class Classes extends HttpHandler {
   296         private final Res loader;
   297 
   298         public Classes(Res loader) {
   299             this.loader = loader;
   300         }
   301 
   302         @Override
   303         public void service(Request request, Response response) throws Exception {
   304             String res = request.getHttpHandlerPath();
   305             if (res.startsWith("/")) {
   306                 res = res.substring(1);
   307             }
   308             try (InputStream is = loader.get(res)) {
   309                 response.setContentType("text/javascript");
   310                 Writer w = response.getWriter();
   311                 w.append("[");
   312                 for (int i = 0;; i++) {
   313                     int b = is.read();
   314                     if (b == -1) {
   315                         break;
   316                     }
   317                     if (i > 0) {
   318                         w.append(", ");
   319                     }
   320                     if (i % 20 == 0) {
   321                         w.write("\n");
   322                     }
   323                     if (b > 127) {
   324                         b = b - 256;
   325                     }
   326                     w.append(Integer.toString(b));
   327                 }
   328                 w.append("\n]");
   329             } catch (IOException ex) {
   330                 response.setError();
   331                 response.setDetailMessage(ex.getMessage());
   332             }
   333         }
   334     }
   335     
   336     public static final class MethodInvocation {
   337         final String className;
   338         final String methodName;
   339         String result;
   340 
   341         MethodInvocation(String className, String methodName) {
   342             this.className = className;
   343             this.methodName = methodName;
   344         }
   345 
   346         @Override
   347         public String toString() {
   348             return result;
   349         }
   350     }
   351 }