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