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