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