launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 22 Dec 2012 21:00:23 +0100
branchlauncher
changeset 365 4c8388f797b2
parent 364 91f5b1f604d8
child 366 ca2be963f3b9
permissions -rw-r--r--
Starting and also shutdowning the browser. Currently optimized from chrome
     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         Thread.sleep(5000);
   293         process.destroy();
   294         int res = process.waitFor();
   295         LOG.log(Level.INFO, "Exit code: {0}", res);
   296 
   297         deleteTree((File)brwsr[1]);
   298     }
   299     
   300     private static void drain(String name, InputStream is) throws IOException {
   301         int av = is.available();
   302         if (av > 0) {
   303             StringBuilder sb = new StringBuilder();
   304             sb.append("v== ").append(name).append(" ==v\n");
   305             while (av-- > 0) {
   306                 sb.append((char)is.read());
   307             }
   308             sb.append("\n^== ").append(name).append(" ==^");
   309             LOG.log(Level.INFO, sb.toString());
   310         }
   311     }
   312 
   313     private void deleteTree(File file) {
   314         File[] arr = file.listFiles();
   315         if (arr != null) {
   316             for (File s : arr) {
   317                 deleteTree(s);
   318             }
   319         }
   320         file.delete();
   321     }
   322 
   323     private class Res implements Bck2Brwsr.Resources {
   324         @Override
   325         public InputStream get(String resource) throws IOException {
   326             for (ClassLoader l : loaders) {
   327                 URL u = null;
   328                 Enumeration<URL> en = l.getResources(resource);
   329                 while (en.hasMoreElements()) {
   330                     u = en.nextElement();
   331                 }
   332                 if (u != null) {
   333                     return u.openStream();
   334                 }
   335             }
   336             throw new IOException("Can't find " + resource);
   337         }
   338     }
   339 
   340     private static class Page extends HttpHandler {
   341         private final String resource;
   342         private final String[] args;
   343         private final Res res;
   344         
   345         public Page(Res res, String resource, String... args) {
   346             this.res = res;
   347             this.resource = resource;
   348             this.args = args;
   349         }
   350 
   351         @Override
   352         public void service(Request request, Response response) throws Exception {
   353             String r = resource;
   354             if (r == null) {
   355                 r = request.getHttpHandlerPath();
   356                 if (r.startsWith("/")) {
   357                     r = r.substring(1);
   358                 }
   359             }
   360             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   361                 response.setContentType("text/html");
   362             }
   363             OutputStream os = response.getOutputStream();
   364             try (InputStream is = res.get(r)) {
   365                 copyStream(is, os, request.getRequestURL().toString(), args);
   366             } catch (IOException ex) {
   367                 response.setDetailMessage(ex.getLocalizedMessage());
   368                 response.setError();
   369                 response.setStatus(404);
   370             }
   371         }
   372     }
   373 
   374     private static class VM extends HttpHandler {
   375         private final Res loader;
   376 
   377         public VM(Res loader) {
   378             this.loader = loader;
   379         }
   380 
   381         @Override
   382         public void service(Request request, Response response) throws Exception {
   383             response.setCharacterEncoding("UTF-8");
   384             response.setContentType("text/javascript");
   385             Bck2Brwsr.generate(response.getWriter(), loader);
   386         }
   387     }
   388     private static class VMInit extends HttpHandler {
   389         public VMInit() {
   390         }
   391 
   392         @Override
   393         public void service(Request request, Response response) throws Exception {
   394             response.setCharacterEncoding("UTF-8");
   395             response.setContentType("text/javascript");
   396             response.getWriter().append(
   397                 "function ldCls(res) {\n"
   398                 + "  var request = new XMLHttpRequest();\n"
   399                 + "  request.open('GET', '/classes/' + res, false);\n"
   400                 + "  request.send();\n"
   401                 + "  var arr = eval('(' + request.responseText + ')');\n"
   402                 + "  return arr;\n"
   403                 + "}\n"
   404                 + "var vm = new bck2brwsr(ldCls);\n");
   405         }
   406     }
   407 
   408     private static class Classes extends HttpHandler {
   409         private final Res loader;
   410 
   411         public Classes(Res loader) {
   412             this.loader = loader;
   413         }
   414 
   415         @Override
   416         public void service(Request request, Response response) throws Exception {
   417             String res = request.getHttpHandlerPath();
   418             if (res.startsWith("/")) {
   419                 res = res.substring(1);
   420             }
   421             try (InputStream is = loader.get(res)) {
   422                 response.setContentType("text/javascript");
   423                 Writer w = response.getWriter();
   424                 w.append("[");
   425                 for (int i = 0;; i++) {
   426                     int b = is.read();
   427                     if (b == -1) {
   428                         break;
   429                     }
   430                     if (i > 0) {
   431                         w.append(", ");
   432                     }
   433                     if (i % 20 == 0) {
   434                         w.write("\n");
   435                     }
   436                     if (b > 127) {
   437                         b = b - 256;
   438                     }
   439                     w.append(Integer.toString(b));
   440                 }
   441                 w.append("\n]");
   442             } catch (IOException ex) {
   443                 response.setError();
   444                 response.setDetailMessage(ex.getMessage());
   445             }
   446         }
   447     }
   448     
   449     public static final class MethodInvocation {
   450         final String className;
   451         final String methodName;
   452         String result;
   453 
   454         MethodInvocation(String className, String methodName) {
   455             this.className = className;
   456             this.methodName = methodName;
   457         }
   458 
   459         @Override
   460         public String toString() {
   461             return result;
   462         }
   463     }
   464 }