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