launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 22 Dec 2012 21:35:14 +0100
branchlauncher
changeset 366 ca2be963f3b9
parent 365 4c8388f797b2
child 367 02641a16e272
permissions -rw-r--r--
Closing the window when data are processed.
     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.File;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.io.InterruptedIOException;
    25 import java.io.OutputStream;
    26 import java.io.Writer;
    27 import java.net.URI;
    28 import java.net.URISyntaxException;
    29 import java.net.URL;
    30 import java.nio.file.Files;
    31 import java.util.ArrayList;
    32 import java.util.Arrays;
    33 import java.util.Enumeration;
    34 import java.util.LinkedHashSet;
    35 import java.util.List;
    36 import java.util.Set;
    37 import java.util.concurrent.CountDownLatch;
    38 import java.util.concurrent.TimeUnit;
    39 import java.util.logging.Level;
    40 import java.util.logging.Logger;
    41 import javax.script.Invocable;
    42 import javax.script.ScriptEngine;
    43 import javax.script.ScriptEngineManager;
    44 import javax.script.ScriptException;
    45 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
    46 import org.apidesign.vm4brwsr.Bck2Brwsr;
    47 import org.glassfish.grizzly.PortRange;
    48 import org.glassfish.grizzly.http.server.HttpHandler;
    49 import org.glassfish.grizzly.http.server.HttpServer;
    50 import org.glassfish.grizzly.http.server.NetworkListener;
    51 import org.glassfish.grizzly.http.server.Request;
    52 import org.glassfish.grizzly.http.server.Response;
    53 import org.glassfish.grizzly.http.server.ServerConfiguration;
    54 
    55 /**
    56  * Lightweight server to launch Bck2Brwsr applications and tests.
    57  * Supports execution in native browser as well as Java's internal 
    58  * execution engine.
    59  */
    60 public class Bck2BrwsrLauncher {
    61     private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
    62     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    63     private List<MethodInvocation> methods = new ArrayList<>();
    64     private long timeOut;
    65     private String sen;
    66     private String showURL;
    67     private final Res resources = new Res();
    68     
    69     
    70     public MethodInvocation addMethod(Class<?> clazz, String method) {
    71         loaders.add(clazz.getClassLoader());
    72         MethodInvocation c = new MethodInvocation(clazz.getName(), method);
    73         methods.add(c);
    74         return c;
    75     }
    76     
    77     public void setTimeout(long ms) {
    78         timeOut = ms;
    79     }
    80     
    81     public void setScriptEngineName(String sen) {
    82         this.sen = sen;
    83     }
    84 
    85     public void setStartPage(String startpage) {
    86         if (!startpage.startsWith("/")) {
    87             startpage = "/" + startpage;
    88         }
    89         this.showURL = startpage;
    90     }
    91 
    92     public void addClassLoader(ClassLoader url) {
    93         this.loaders.add(url);
    94     }
    95     
    96     public static void main( String[] args ) throws Exception {
    97         Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
    98         l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
    99         l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
   100         l.execute();
   101         System.in.read();
   102     }
   103 
   104 
   105     public void execute() throws IOException {
   106         try {
   107             if (sen != null) {
   108                 executeRhino();
   109             } else if (showURL != null) {
   110                 HttpServer server = initServer();
   111                 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
   112                 launchServerAndBrwsr(server, showURL);
   113             } else {
   114                 executeInBrowser();
   115             }
   116         } catch (InterruptedException ex) {
   117             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   118             iio.initCause(ex);
   119             throw iio;
   120         } catch (Exception ex) {
   121             if (ex instanceof IOException) {
   122                 throw (IOException)ex;
   123             }
   124             if (ex instanceof RuntimeException) {
   125                 throw (RuntimeException)ex;
   126             }
   127             throw new IOException(ex);
   128         }
   129     }
   130     
   131     private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
   132         StringBuilder sb = new StringBuilder();
   133         Bck2Brwsr.generate(sb, new Res());
   134 
   135         ScriptEngineManager sem = new ScriptEngineManager();
   136         ScriptEngine mach = sem.getEngineByExtension(sen);
   137 
   138         sb.append(
   139               "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
   140             + "\nfunction initVM() { return vm; };"
   141             + "\n");
   142 
   143         Object res = mach.eval(sb.toString());
   144         if (!(mach instanceof Invocable)) {
   145             throw new IOException("It is invocable object: " + res);
   146         }
   147         Invocable code = (Invocable) mach;
   148         
   149         Object vm = code.invokeFunction("initVM");
   150         Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
   151 
   152         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   153         for (MethodInvocation mi : cases) {
   154             mi.result = code.invokeMethod(console, 
   155                 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2", 
   156                 mi.className, mi.methodName
   157             ).toString();
   158         }
   159     }
   160     
   161     private HttpServer initServer() {
   162         HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
   163 
   164         final ServerConfiguration conf = server.getServerConfiguration();
   165         conf.addHttpHandler(new Page(resources, 
   166             "org/apidesign/bck2brwsr/launcher/console.xhtml",
   167             "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
   168         ), "/console");
   169         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   170         conf.addHttpHandler(new VMInit(), "/vm.js");
   171         conf.addHttpHandler(new Classes(resources), "/classes/");
   172         return server;
   173     }
   174     
   175     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   176         final CountDownLatch wait = new CountDownLatch(1);
   177         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   178         
   179         HttpServer server = initServer();
   180         ServerConfiguration conf = server.getServerConfiguration();
   181         conf.addHttpHandler(new Page(resources, 
   182             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   183         ), "/execute");
   184         final int[] currentTest = { -1 };
   185         conf.addHttpHandler(new HttpHandler() {
   186             int cnt;
   187             @Override
   188             public void service(Request request, Response response) throws Exception {
   189                 String id = request.getParameter("request");
   190                 String value = request.getParameter("result");
   191                 
   192                 if (id != null && value != null) {
   193                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   194                     value = value.replace("%20", " ");
   195                     cases[Integer.parseInt(id)].result = value;
   196                 }
   197                 currentTest[0] = cnt;
   198                 
   199                 if (cnt >= cases.length) {
   200                     response.getWriter().write("");
   201                     wait.countDown();
   202                     cnt = 0;
   203                     return;
   204                 }
   205                 
   206                 final String cn = cases[cnt].className;
   207                 final String mn = cases[cnt].methodName;
   208                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   209                 response.getWriter().write("{"
   210                     + "className: '" + cn + "', "
   211                     + "methodName: '" + mn + "', "
   212                     + "request: " + cnt
   213                     + "}");
   214                 cnt++;
   215             }
   216         }, "/data");
   217 
   218         Object[] brwsr = launchServerAndBrwsr(server, "/execute");
   219         
   220         for (;;) {
   221             int prev = currentTest[0];
   222             if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   223                 break;
   224             }
   225             if (prev == currentTest[0]) {
   226                 LOG.log(
   227                     Level.WARNING, 
   228                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   229                     currentTest[0]
   230                 );
   231                 break;
   232             }
   233             LOG.log(Level.INFO, 
   234                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   235                 new Object[]{prev, currentTest[0]}
   236             );
   237         }
   238         stopServerAndBrwsr(server, brwsr);
   239     }
   240     
   241     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   242         for (;;) {
   243             int ch = is.read();
   244             if (ch == -1) {
   245                 break;
   246             }
   247             if (ch == '$') {
   248                 int cnt = is.read() - '0';
   249                 if (cnt == 'U' - '0') {
   250                     os.write(baseURL.getBytes());
   251                 }
   252                 if (cnt < params.length) {
   253                     os.write(params[cnt].getBytes());
   254                 }
   255             } else {
   256                 os.write(ch);
   257             }
   258         }
   259     }
   260 
   261     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   262         server.start();
   263         NetworkListener listener = server.getListeners().iterator().next();
   264         int port = listener.getPort();
   265         
   266         URI uri = new URI("http://localhost:" + port + page);
   267         LOG.log(Level.INFO, "Showing {0}", uri);
   268         try {
   269             Desktop.getDesktop().browse(uri);
   270             return null;
   271         } catch (UnsupportedOperationException ex) {
   272             File dir = File.createTempFile("chrome", ".dir");
   273             dir.delete();
   274             dir.mkdirs();
   275             String[] cmd = { 
   276                 "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
   277             };
   278             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   279             final Process process = Runtime.getRuntime().exec(cmd);
   280             return new Object[] { process, dir };
   281         }
   282     }
   283     
   284     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
   285         Process process = (Process)brwsr[0];
   286         
   287         server.stop();
   288         InputStream stdout = process.getInputStream();
   289         InputStream stderr = process.getErrorStream();
   290         drain("StdOut", stdout);
   291         drain("StdErr", stderr);
   292         process.destroy();
   293         int res = process.waitFor();
   294         LOG.log(Level.INFO, "Exit code: {0}", res);
   295 
   296         deleteTree((File)brwsr[1]);
   297     }
   298     
   299     private static void drain(String name, InputStream is) throws IOException {
   300         int av = is.available();
   301         if (av > 0) {
   302             StringBuilder sb = new StringBuilder();
   303             sb.append("v== ").append(name).append(" ==v\n");
   304             while (av-- > 0) {
   305                 sb.append((char)is.read());
   306             }
   307             sb.append("\n^== ").append(name).append(" ==^");
   308             LOG.log(Level.INFO, sb.toString());
   309         }
   310     }
   311 
   312     private void deleteTree(File file) {
   313         File[] arr = file.listFiles();
   314         if (arr != null) {
   315             for (File s : arr) {
   316                 deleteTree(s);
   317             }
   318         }
   319         file.delete();
   320     }
   321 
   322     private class Res implements Bck2Brwsr.Resources {
   323         @Override
   324         public InputStream get(String resource) throws IOException {
   325             for (ClassLoader l : loaders) {
   326                 URL u = null;
   327                 Enumeration<URL> en = l.getResources(resource);
   328                 while (en.hasMoreElements()) {
   329                     u = en.nextElement();
   330                 }
   331                 if (u != null) {
   332                     return u.openStream();
   333                 }
   334             }
   335             throw new IOException("Can't find " + resource);
   336         }
   337     }
   338 
   339     private static class Page extends HttpHandler {
   340         private final String resource;
   341         private final String[] args;
   342         private final Res res;
   343         
   344         public Page(Res res, String resource, String... args) {
   345             this.res = res;
   346             this.resource = resource;
   347             this.args = args;
   348         }
   349 
   350         @Override
   351         public void service(Request request, Response response) throws Exception {
   352             String r = resource;
   353             if (r == null) {
   354                 r = request.getHttpHandlerPath();
   355                 if (r.startsWith("/")) {
   356                     r = r.substring(1);
   357                 }
   358             }
   359             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   360                 response.setContentType("text/html");
   361             }
   362             OutputStream os = response.getOutputStream();
   363             try (InputStream is = res.get(r)) {
   364                 copyStream(is, os, request.getRequestURL().toString(), args);
   365             } catch (IOException ex) {
   366                 response.setDetailMessage(ex.getLocalizedMessage());
   367                 response.setError();
   368                 response.setStatus(404);
   369             }
   370         }
   371     }
   372 
   373     private static class VM extends HttpHandler {
   374         private final Res loader;
   375 
   376         public VM(Res loader) {
   377             this.loader = loader;
   378         }
   379 
   380         @Override
   381         public void service(Request request, Response response) throws Exception {
   382             response.setCharacterEncoding("UTF-8");
   383             response.setContentType("text/javascript");
   384             Bck2Brwsr.generate(response.getWriter(), loader);
   385         }
   386     }
   387     private static class VMInit extends HttpHandler {
   388         public VMInit() {
   389         }
   390 
   391         @Override
   392         public void service(Request request, Response response) throws Exception {
   393             response.setCharacterEncoding("UTF-8");
   394             response.setContentType("text/javascript");
   395             response.getWriter().append(
   396                 "function ldCls(res) {\n"
   397                 + "  var request = new XMLHttpRequest();\n"
   398                 + "  request.open('GET', '/classes/' + res, false);\n"
   399                 + "  request.send();\n"
   400                 + "  var arr = eval('(' + request.responseText + ')');\n"
   401                 + "  return arr;\n"
   402                 + "}\n"
   403                 + "var vm = new bck2brwsr(ldCls);\n");
   404         }
   405     }
   406 
   407     private static class Classes extends HttpHandler {
   408         private final Res loader;
   409 
   410         public Classes(Res loader) {
   411             this.loader = loader;
   412         }
   413 
   414         @Override
   415         public void service(Request request, Response response) throws Exception {
   416             String res = request.getHttpHandlerPath();
   417             if (res.startsWith("/")) {
   418                 res = res.substring(1);
   419             }
   420             try (InputStream is = loader.get(res)) {
   421                 response.setContentType("text/javascript");
   422                 Writer w = response.getWriter();
   423                 w.append("[");
   424                 for (int i = 0;; i++) {
   425                     int b = is.read();
   426                     if (b == -1) {
   427                         break;
   428                     }
   429                     if (i > 0) {
   430                         w.append(", ");
   431                     }
   432                     if (i % 20 == 0) {
   433                         w.write("\n");
   434                     }
   435                     if (b > 127) {
   436                         b = b - 256;
   437                     }
   438                     w.append(Integer.toString(b));
   439                 }
   440                 w.append("\n]");
   441             } catch (IOException ex) {
   442                 response.setError();
   443                 response.setDetailMessage(ex.getMessage());
   444             }
   445         }
   446     }
   447     
   448     public static final class MethodInvocation {
   449         final String className;
   450         final String methodName;
   451         String result;
   452 
   453         MethodInvocation(String className, String methodName) {
   454             this.className = className;
   455             this.methodName = methodName;
   456         }
   457 
   458         @Override
   459         public String toString() {
   460             return result;
   461         }
   462     }
   463 }