launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 31 Jan 2013 16:58:27 +0100
branchemul
changeset 622 a07253cf2ca4
parent 613 a4a06840209a
child 623 4af0d3dedb9d
permissions -rw-r--r--
Better (more extensible and documented) API for the Launcher
     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 InvocationContext END = new InvocationContext(null, null, null);
    59     private final Set<ClassLoader> loaders = new LinkedHashSet<>();
    60     private final BlockingQueue<InvocationContext> 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     InvocationContext runMethod(InvocationContext c) throws IOException {
    74         loaders.add(c.clazz.getClassLoader());
    75         methods.add(c);
    76         try {
    77             c.await(timeOut);
    78         } catch (InterruptedException ex) {
    79             throw new IOException(ex);
    80         }
    81         return c;
    82     }
    83     
    84     public void setTimeout(long ms) {
    85         timeOut = ms;
    86     }
    87     
    88     public void addClassLoader(ClassLoader url) {
    89         this.loaders.add(url);
    90     }
    91 
    92     public void showURL(String startpage) throws IOException {
    93         if (!startpage.startsWith("/")) {
    94             startpage = "/" + startpage;
    95         }
    96         HttpServer s = initServer(".", true);
    97         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
    98         try {
    99             launchServerAndBrwsr(s, startpage);
   100         } catch (URISyntaxException | InterruptedException ex) {
   101             throw new IOException(ex);
   102         }
   103     }
   104 
   105     void showDirectory(File dir, String startpage) throws IOException {
   106         if (!startpage.startsWith("/")) {
   107             startpage = "/" + startpage;
   108         }
   109         HttpServer s = initServer(dir.getPath(), false);
   110         try {
   111             launchServerAndBrwsr(s, startpage);
   112         } catch (URISyntaxException | InterruptedException ex) {
   113             throw new IOException(ex);
   114         }
   115     }
   116 
   117     @Override
   118     public void initialize() throws IOException {
   119         try {
   120             executeInBrowser();
   121         } catch (InterruptedException ex) {
   122             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   123             iio.initCause(ex);
   124             throw iio;
   125         } catch (Exception ex) {
   126             if (ex instanceof IOException) {
   127                 throw (IOException)ex;
   128             }
   129             if (ex instanceof RuntimeException) {
   130                 throw (RuntimeException)ex;
   131             }
   132             throw new IOException(ex);
   133         }
   134     }
   135     
   136     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   137         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   138 
   139         final ServerConfiguration conf = s.getServerConfiguration();
   140         if (addClasses) {
   141             conf.addHttpHandler(new VM(resources), "/vm.js");
   142             conf.addHttpHandler(new Classes(resources), "/classes/");
   143         }
   144         return s;
   145     }
   146     
   147     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   148         wait = new CountDownLatch(1);
   149         server = initServer(".", true);
   150         ServerConfiguration conf = server.getServerConfiguration();
   151         conf.addHttpHandler(new Page(resources, 
   152             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   153         ), "/execute");
   154         conf.addHttpHandler(new HttpHandler() {
   155             int cnt;
   156             List<InvocationContext> cases = new ArrayList<>();
   157             @Override
   158             public void service(Request request, Response response) throws Exception {
   159                 String id = request.getParameter("request");
   160                 String value = request.getParameter("result");
   161                 
   162                 if (id != null && value != null) {
   163                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   164                     value = decodeURL(value);
   165                     cases.get(Integer.parseInt(id)).result(value, null);
   166                 }
   167                 
   168                 InvocationContext mi = methods.take();
   169                 if (mi == END) {
   170                     response.getWriter().write("");
   171                     wait.countDown();
   172                     cnt = 0;
   173                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   174                     return;
   175                 }
   176                 
   177                 cases.add(mi);
   178                 final String cn = mi.clazz.getName();
   179                 final String mn = mi.methodName;
   180                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   181                 response.getWriter().write("{"
   182                     + "className: '" + cn + "', "
   183                     + "methodName: '" + mn + "', "
   184                     + "request: " + cnt
   185                 );
   186                 if (mi.html != null) {
   187                     response.getWriter().write(", html: '");
   188                     response.getWriter().write(encodeJSON(mi.html));
   189                     response.getWriter().write("'");
   190                 }
   191                 response.getWriter().write("}");
   192                 cnt++;
   193             }
   194         }, "/data");
   195 
   196         this.brwsr = launchServerAndBrwsr(server, "/execute");
   197     }
   198     
   199     private static String encodeJSON(String in) {
   200         StringBuilder sb = new StringBuilder();
   201         for (int i = 0; i < in.length(); i++) {
   202             char ch = in.charAt(i);
   203             if (ch < 32 || ch == '\'' || ch == '"') {
   204                 sb.append("\\u");
   205                 String hs = "0000" + Integer.toHexString(ch);
   206                 hs = hs.substring(hs.length() - 4);
   207                 sb.append(hs);
   208             } else {
   209                 sb.append(ch);
   210             }
   211         }
   212         return sb.toString();
   213     }
   214     
   215     @Override
   216     public void shutdown() throws IOException {
   217         methods.offer(END);
   218         for (;;) {
   219             int prev = methods.size();
   220             try {
   221                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   222                     break;
   223                 }
   224             } catch (InterruptedException ex) {
   225                 throw new IOException(ex);
   226             }
   227             if (prev == methods.size()) {
   228                 LOG.log(
   229                     Level.WARNING, 
   230                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   231                     methods.size()
   232                 );
   233                 break;
   234             }
   235             LOG.log(Level.INFO, 
   236                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   237                 new Object[]{prev, methods.size()}
   238             );
   239         }
   240         stopServerAndBrwsr(server, brwsr);
   241     }
   242     
   243     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   244         for (;;) {
   245             int ch = is.read();
   246             if (ch == -1) {
   247                 break;
   248             }
   249             if (ch == '$' && params.length > 0) {
   250                 int cnt = is.read() - '0';
   251                 if (cnt == 'U' - '0') {
   252                     os.write(baseURL.getBytes());
   253                 }
   254                 if (cnt >= 0 && cnt < params.length) {
   255                     os.write(params[cnt].getBytes());
   256                 }
   257             } else {
   258                 os.write(ch);
   259             }
   260         }
   261     }
   262 
   263     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   264         server.start();
   265         NetworkListener listener = server.getListeners().iterator().next();
   266         int port = listener.getPort();
   267         
   268         URI uri = new URI("http://localhost:" + port + page);
   269         LOG.log(Level.INFO, "Showing {0}", uri);
   270         if (cmd == null) {
   271             try {
   272                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   273                     System.getProperty("java.vm.name"),
   274                     System.getProperty("java.vm.vendor"),
   275                     System.getProperty("java.vm.version"),
   276                 });
   277                 java.awt.Desktop.getDesktop().browse(uri);
   278                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   279                 return null;
   280             } catch (UnsupportedOperationException ex) {
   281                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   282                 LOG.log(Level.FINE, null, ex);
   283             }
   284         }
   285         {
   286             String cmdName = cmd == null ? "xdg-open" : cmd;
   287             String[] cmdArr = { 
   288                 cmdName, uri.toString()
   289             };
   290             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   291             final Process process = Runtime.getRuntime().exec(cmdArr);
   292             return new Object[] { process, null };
   293         }
   294     }
   295     
   296     private static String decodeURL(String s) {
   297         for (;;) {
   298             int pos = s.indexOf('%');
   299             if (pos == -1) {
   300                 return s;
   301             }
   302             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   303             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   304         }
   305     }
   306     
   307     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   308         if (brwsr == null) {
   309             return;
   310         }
   311         Process process = (Process)brwsr[0];
   312         
   313         server.stop();
   314         InputStream stdout = process.getInputStream();
   315         InputStream stderr = process.getErrorStream();
   316         drain("StdOut", stdout);
   317         drain("StdErr", stderr);
   318         process.destroy();
   319         int res;
   320         try {
   321             res = process.waitFor();
   322         } catch (InterruptedException ex) {
   323             throw new IOException(ex);
   324         }
   325         LOG.log(Level.INFO, "Exit code: {0}", res);
   326 
   327         deleteTree((File)brwsr[1]);
   328     }
   329     
   330     private static void drain(String name, InputStream is) throws IOException {
   331         int av = is.available();
   332         if (av > 0) {
   333             StringBuilder sb = new StringBuilder();
   334             sb.append("v== ").append(name).append(" ==v\n");
   335             while (av-- > 0) {
   336                 sb.append((char)is.read());
   337             }
   338             sb.append("\n^== ").append(name).append(" ==^");
   339             LOG.log(Level.INFO, sb.toString());
   340         }
   341     }
   342 
   343     private void deleteTree(File file) {
   344         if (file == null) {
   345             return;
   346         }
   347         File[] arr = file.listFiles();
   348         if (arr != null) {
   349             for (File s : arr) {
   350                 deleteTree(s);
   351             }
   352         }
   353         file.delete();
   354     }
   355 
   356     @Override
   357     public void close() throws IOException {
   358         shutdown();
   359     }
   360 
   361     private class Res implements Bck2Brwsr.Resources {
   362         @Override
   363         public InputStream get(String resource) throws IOException {
   364             for (ClassLoader l : loaders) {
   365                 URL u = null;
   366                 Enumeration<URL> en = l.getResources(resource);
   367                 while (en.hasMoreElements()) {
   368                     u = en.nextElement();
   369                 }
   370                 if (u != null) {
   371                     return u.openStream();
   372                 }
   373             }
   374             throw new IOException("Can't find " + resource);
   375         }
   376     }
   377 
   378     private static class Page extends HttpHandler {
   379         private final String resource;
   380         private final String[] args;
   381         private final Res res;
   382         
   383         public Page(Res res, String resource, String... args) {
   384             this.res = res;
   385             this.resource = resource;
   386             this.args = args.length == 0 ? new String[] { "$0" } : args;
   387         }
   388 
   389         @Override
   390         public void service(Request request, Response response) throws Exception {
   391             String r = resource;
   392             if (r == null) {
   393                 r = request.getHttpHandlerPath();
   394                 if (r.startsWith("/")) {
   395                     r = r.substring(1);
   396                 }
   397             }
   398             String[] replace = {};
   399             if (r.endsWith(".html")) {
   400                 response.setContentType("text/html");
   401                 LOG.info("Content type text/html");
   402                 replace = args;
   403             }
   404             if (r.endsWith(".xhtml")) {
   405                 response.setContentType("application/xhtml+xml");
   406                 LOG.info("Content type application/xhtml+xml");
   407                 replace = args;
   408             }
   409             OutputStream os = response.getOutputStream();
   410             try (InputStream is = res.get(r)) {
   411                 copyStream(is, os, request.getRequestURL().toString(), replace);
   412             } catch (IOException ex) {
   413                 response.setDetailMessage(ex.getLocalizedMessage());
   414                 response.setError();
   415                 response.setStatus(404);
   416             }
   417         }
   418     }
   419 
   420     private static class VM extends HttpHandler {
   421         private final String bck2brwsr;
   422 
   423         public VM(Res loader) throws IOException {
   424             StringBuilder sb = new StringBuilder();
   425             Bck2Brwsr.generate(sb, loader);
   426             sb.append(
   427                 "function ldCls(res) {\n"
   428                 + "  var request = new XMLHttpRequest();\n"
   429                 + "  request.open('GET', '/classes/' + res, false);\n"
   430                 + "  request.send();\n"
   431                 + "  var arr = eval('(' + request.responseText + ')');\n"
   432                 + "  return arr;\n"
   433                 + "}\n"
   434                 + "var vm = new bck2brwsr(ldCls);\n"
   435             );
   436             this.bck2brwsr = sb.toString();
   437         }
   438 
   439         @Override
   440         public void service(Request request, Response response) throws Exception {
   441             response.setCharacterEncoding("UTF-8");
   442             response.setContentType("text/javascript");
   443             response.getWriter().write(bck2brwsr);
   444         }
   445     }
   446 
   447     private static class Classes extends HttpHandler {
   448         private final Res loader;
   449 
   450         public Classes(Res loader) {
   451             this.loader = loader;
   452         }
   453 
   454         @Override
   455         public void service(Request request, Response response) throws Exception {
   456             String res = request.getHttpHandlerPath();
   457             if (res.startsWith("/")) {
   458                 res = res.substring(1);
   459             }
   460             try (InputStream is = loader.get(res)) {
   461                 response.setContentType("text/javascript");
   462                 Writer w = response.getWriter();
   463                 w.append("[");
   464                 for (int i = 0;; i++) {
   465                     int b = is.read();
   466                     if (b == -1) {
   467                         break;
   468                     }
   469                     if (i > 0) {
   470                         w.append(", ");
   471                     }
   472                     if (i % 20 == 0) {
   473                         w.write("\n");
   474                     }
   475                     if (b > 127) {
   476                         b = b - 256;
   477                     }
   478                     w.append(Integer.toString(b));
   479                 }
   480                 w.append("\n]");
   481             } catch (IOException ex) {
   482                 response.setError();
   483                 response.setDetailMessage(ex.getMessage());
   484             }
   485         }
   486     }
   487 }