launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 11 Feb 2013 19:47:46 +0100
branchemul
changeset 709 722c51330e75
parent 667 5866e89ef568
child 741 1343f52164f3
permissions -rw-r--r--
Support relaunching of test cases. Just reload the initial browser page and the test cases will be executed again. Useful when setting breakpoints.
     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.launcher.InvocationContext.Resource;
    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 InvocationContext END = new InvocationContext(null, null, null);
    60     private final Set<ClassLoader> loaders = new LinkedHashSet<>();
    61     private final BlockingQueue<InvocationContext> 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     InvocationContext runMethod(InvocationContext c) throws IOException {
    75         loaders.add(c.clazz.getClassLoader());
    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         final ServerConfiguration conf = server.getServerConfiguration();
   152         
   153         class DynamicResourceHandler extends HttpHandler {
   154             private final InvocationContext ic;
   155             public DynamicResourceHandler(InvocationContext ic) {
   156                 if (ic == null || ic.resources.isEmpty()) {
   157                     throw new NullPointerException();
   158                 }
   159                 this.ic = ic;
   160                 for (Resource r : ic.resources) {
   161                     conf.addHttpHandler(this, r.httpPath);
   162                 }
   163             }
   164 
   165             public void close() {
   166                 conf.removeHttpHandler(this);
   167             }
   168             
   169             @Override
   170             public void service(Request request, Response response) throws Exception {
   171                 for (Resource r : ic.resources) {
   172                     if (r.httpPath.equals(request.getRequestURI())) {
   173                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   174                         response.setContentType(r.httpType);
   175                         copyStream(r.httpContent, response.getOutputStream(), null);
   176                     }
   177                 }
   178             }
   179         }
   180         
   181         conf.addHttpHandler(new Page(resources, 
   182             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   183         ), "/execute");
   184         
   185         conf.addHttpHandler(new HttpHandler() {
   186             int cnt;
   187             List<InvocationContext> cases = new ArrayList<>();
   188             DynamicResourceHandler prev;
   189             @Override
   190             public void service(Request request, Response response) throws Exception {
   191                 String id = request.getParameter("request");
   192                 String value = request.getParameter("result");
   193                 
   194                 
   195                 InvocationContext mi = null;
   196                 int caseNmbr = -1;
   197                 
   198                 if (id != null && value != null) {
   199                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   200                     value = decodeURL(value);
   201                     int indx = Integer.parseInt(id);
   202                     cases.get(indx).result(value, null);
   203                     if (++indx < cases.size()) {
   204                         mi = cases.get(indx);
   205                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   206                         caseNmbr = indx;
   207                     }
   208                 } else {
   209                     if (!cases.isEmpty()) {
   210                         LOG.info("Re-executing test cases");
   211                         mi = cases.get(0);
   212                         caseNmbr = 0;
   213                     }
   214                 }
   215                 
   216                 if (prev != null) {
   217                     prev.close();
   218                     prev = null;
   219                 }
   220                 
   221                 if (mi == null) {
   222                     mi = methods.take();
   223                     caseNmbr = cnt++;
   224                 }
   225                 if (mi == END) {
   226                     response.getWriter().write("");
   227                     wait.countDown();
   228                     cnt = 0;
   229                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   230                     return;
   231                 }
   232                 
   233                 if (!mi.resources.isEmpty()) {
   234                     prev = new DynamicResourceHandler(mi);
   235                 }
   236                 
   237                 cases.add(mi);
   238                 final String cn = mi.clazz.getName();
   239                 final String mn = mi.methodName;
   240                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   241                 response.getWriter().write("{"
   242                     + "className: '" + cn + "', "
   243                     + "methodName: '" + mn + "', "
   244                     + "request: " + caseNmbr
   245                 );
   246                 if (mi.html != null) {
   247                     response.getWriter().write(", html: '");
   248                     response.getWriter().write(encodeJSON(mi.html));
   249                     response.getWriter().write("'");
   250                 }
   251                 response.getWriter().write("}");
   252             }
   253         }, "/data");
   254 
   255         this.brwsr = launchServerAndBrwsr(server, "/execute");
   256     }
   257     
   258     private static String encodeJSON(String in) {
   259         StringBuilder sb = new StringBuilder();
   260         for (int i = 0; i < in.length(); i++) {
   261             char ch = in.charAt(i);
   262             if (ch < 32 || ch == '\'' || ch == '"') {
   263                 sb.append("\\u");
   264                 String hs = "0000" + Integer.toHexString(ch);
   265                 hs = hs.substring(hs.length() - 4);
   266                 sb.append(hs);
   267             } else {
   268                 sb.append(ch);
   269             }
   270         }
   271         return sb.toString();
   272     }
   273     
   274     @Override
   275     public void shutdown() throws IOException {
   276         methods.offer(END);
   277         for (;;) {
   278             int prev = methods.size();
   279             try {
   280                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   281                     break;
   282                 }
   283             } catch (InterruptedException ex) {
   284                 throw new IOException(ex);
   285             }
   286             if (prev == methods.size()) {
   287                 LOG.log(
   288                     Level.WARNING, 
   289                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   290                     methods.size()
   291                 );
   292                 break;
   293             }
   294             LOG.log(Level.INFO, 
   295                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   296                 new Object[]{prev, methods.size()}
   297             );
   298         }
   299         stopServerAndBrwsr(server, brwsr);
   300     }
   301     
   302     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   303         for (;;) {
   304             int ch = is.read();
   305             if (ch == -1) {
   306                 break;
   307             }
   308             if (ch == '$' && params.length > 0) {
   309                 int cnt = is.read() - '0';
   310                 if (cnt == 'U' - '0') {
   311                     os.write(baseURL.getBytes());
   312                 }
   313                 if (cnt >= 0 && cnt < params.length) {
   314                     os.write(params[cnt].getBytes());
   315                 }
   316             } else {
   317                 os.write(ch);
   318             }
   319         }
   320     }
   321 
   322     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   323         server.start();
   324         NetworkListener listener = server.getListeners().iterator().next();
   325         int port = listener.getPort();
   326         
   327         URI uri = new URI("http://localhost:" + port + page);
   328         LOG.log(Level.INFO, "Showing {0}", uri);
   329         if (cmd == null) {
   330             try {
   331                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   332                     System.getProperty("java.vm.name"),
   333                     System.getProperty("java.vm.vendor"),
   334                     System.getProperty("java.vm.version"),
   335                 });
   336                 java.awt.Desktop.getDesktop().browse(uri);
   337                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   338                 return null;
   339             } catch (UnsupportedOperationException ex) {
   340                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   341                 LOG.log(Level.FINE, null, ex);
   342             }
   343         }
   344         {
   345             String cmdName = cmd == null ? "xdg-open" : cmd;
   346             String[] cmdArr = { 
   347                 cmdName, uri.toString()
   348             };
   349             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   350             final Process process = Runtime.getRuntime().exec(cmdArr);
   351             return new Object[] { process, null };
   352         }
   353     }
   354     
   355     private static String decodeURL(String s) {
   356         for (;;) {
   357             int pos = s.indexOf('%');
   358             if (pos == -1) {
   359                 return s;
   360             }
   361             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   362             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   363         }
   364     }
   365     
   366     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   367         if (brwsr == null) {
   368             return;
   369         }
   370         Process process = (Process)brwsr[0];
   371         
   372         server.stop();
   373         InputStream stdout = process.getInputStream();
   374         InputStream stderr = process.getErrorStream();
   375         drain("StdOut", stdout);
   376         drain("StdErr", stderr);
   377         process.destroy();
   378         int res;
   379         try {
   380             res = process.waitFor();
   381         } catch (InterruptedException ex) {
   382             throw new IOException(ex);
   383         }
   384         LOG.log(Level.INFO, "Exit code: {0}", res);
   385 
   386         deleteTree((File)brwsr[1]);
   387     }
   388     
   389     private static void drain(String name, InputStream is) throws IOException {
   390         int av = is.available();
   391         if (av > 0) {
   392             StringBuilder sb = new StringBuilder();
   393             sb.append("v== ").append(name).append(" ==v\n");
   394             while (av-- > 0) {
   395                 sb.append((char)is.read());
   396             }
   397             sb.append("\n^== ").append(name).append(" ==^");
   398             LOG.log(Level.INFO, sb.toString());
   399         }
   400     }
   401 
   402     private void deleteTree(File file) {
   403         if (file == null) {
   404             return;
   405         }
   406         File[] arr = file.listFiles();
   407         if (arr != null) {
   408             for (File s : arr) {
   409                 deleteTree(s);
   410             }
   411         }
   412         file.delete();
   413     }
   414 
   415     @Override
   416     public void close() throws IOException {
   417         shutdown();
   418     }
   419 
   420     private class Res implements Bck2Brwsr.Resources {
   421         @Override
   422         public InputStream get(String resource) throws IOException {
   423             for (ClassLoader l : loaders) {
   424                 URL u = null;
   425                 Enumeration<URL> en = l.getResources(resource);
   426                 while (en.hasMoreElements()) {
   427                     u = en.nextElement();
   428                 }
   429                 if (u != null) {
   430                     return u.openStream();
   431                 }
   432             }
   433             throw new IOException("Can't find " + resource);
   434         }
   435     }
   436 
   437     private static class Page extends HttpHandler {
   438         private final String resource;
   439         private final String[] args;
   440         private final Res res;
   441         
   442         public Page(Res res, String resource, String... args) {
   443             this.res = res;
   444             this.resource = resource;
   445             this.args = args.length == 0 ? new String[] { "$0" } : args;
   446         }
   447 
   448         @Override
   449         public void service(Request request, Response response) throws Exception {
   450             String r = resource;
   451             if (r == null) {
   452                 r = request.getHttpHandlerPath();
   453                 if (r.startsWith("/")) {
   454                     r = r.substring(1);
   455                 }
   456             }
   457             String[] replace = {};
   458             if (r.endsWith(".html")) {
   459                 response.setContentType("text/html");
   460                 LOG.info("Content type text/html");
   461                 replace = args;
   462             }
   463             if (r.endsWith(".xhtml")) {
   464                 response.setContentType("application/xhtml+xml");
   465                 LOG.info("Content type application/xhtml+xml");
   466                 replace = args;
   467             }
   468             OutputStream os = response.getOutputStream();
   469             try (InputStream is = res.get(r)) {
   470                 copyStream(is, os, request.getRequestURL().toString(), replace);
   471             } catch (IOException ex) {
   472                 response.setDetailMessage(ex.getLocalizedMessage());
   473                 response.setError();
   474                 response.setStatus(404);
   475             }
   476         }
   477     }
   478 
   479     private static class VM extends HttpHandler {
   480         private final String bck2brwsr;
   481 
   482         public VM(Res loader) throws IOException {
   483             StringBuilder sb = new StringBuilder();
   484             Bck2Brwsr.generate(sb, loader);
   485             sb.append(
   486                 "function ldCls(res) {\n"
   487                 + "  var request = new XMLHttpRequest();\n"
   488                 + "  request.open('GET', '/classes/' + res, false);\n"
   489                 + "  request.send();\n"
   490                 + "  var arr = eval('(' + request.responseText + ')');\n"
   491                 + "  return arr;\n"
   492                 + "}\n"
   493                 + "var vm = new bck2brwsr(ldCls);\n"
   494             );
   495             this.bck2brwsr = sb.toString();
   496         }
   497 
   498         @Override
   499         public void service(Request request, Response response) throws Exception {
   500             response.setCharacterEncoding("UTF-8");
   501             response.setContentType("text/javascript");
   502             response.getWriter().write(bck2brwsr);
   503         }
   504     }
   505 
   506     private static class Classes extends HttpHandler {
   507         private final Res loader;
   508 
   509         public Classes(Res loader) {
   510             this.loader = loader;
   511         }
   512 
   513         @Override
   514         public void service(Request request, Response response) throws Exception {
   515             String res = request.getHttpHandlerPath();
   516             if (res.startsWith("/")) {
   517                 res = res.substring(1);
   518             }
   519             try (InputStream is = loader.get(res)) {
   520                 response.setContentType("text/javascript");
   521                 Writer w = response.getWriter();
   522                 w.append("[");
   523                 for (int i = 0;; i++) {
   524                     int b = is.read();
   525                     if (b == -1) {
   526                         break;
   527                     }
   528                     if (i > 0) {
   529                         w.append(", ");
   530                     }
   531                     if (i % 20 == 0) {
   532                         w.write("\n");
   533                     }
   534                     if (b > 127) {
   535                         b = b - 256;
   536                     }
   537                     w.append(Integer.toString(b));
   538                 }
   539                 w.append("\n]");
   540             } catch (IOException ex) {
   541                 response.setError();
   542                 response.setDetailMessage(ex.getMessage());
   543             }
   544         }
   545     }
   546 }