rt/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 747 launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java@ae352b763959
child 800 3661b82478e0
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
     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 import org.glassfish.grizzly.http.util.HttpStatus;
    52 
    53 /**
    54  * Lightweight server to launch Bck2Brwsr applications and tests.
    55  * Supports execution in native browser as well as Java's internal 
    56  * execution engine.
    57  */
    58 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
    59     private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
    60     private static final InvocationContext END = new InvocationContext(null, null, null);
    61     private final Set<ClassLoader> loaders = new LinkedHashSet<>();
    62     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
    63     private long timeOut;
    64     private final Res resources = new Res();
    65     private final String cmd;
    66     private Object[] brwsr;
    67     private HttpServer server;
    68     private CountDownLatch wait;
    69     
    70     public Bck2BrwsrLauncher(String cmd) {
    71         this.cmd = cmd;
    72     }
    73     
    74     @Override
    75     InvocationContext runMethod(InvocationContext c) throws IOException {
    76         loaders.add(c.clazz.getClassLoader());
    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(".", true);
    99         int last = startpage.lastIndexOf('/');
   100         String simpleName = startpage.substring(last);
   101         s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), simpleName);
   102         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
   103         try {
   104             launchServerAndBrwsr(s, simpleName);
   105         } catch (URISyntaxException | InterruptedException ex) {
   106             throw new IOException(ex);
   107         }
   108     }
   109 
   110     void showDirectory(File dir, String startpage) throws IOException {
   111         if (!startpage.startsWith("/")) {
   112             startpage = "/" + startpage;
   113         }
   114         HttpServer s = initServer(dir.getPath(), false);
   115         try {
   116             launchServerAndBrwsr(s, startpage);
   117         } catch (URISyntaxException | InterruptedException ex) {
   118             throw new IOException(ex);
   119         }
   120     }
   121 
   122     @Override
   123     public void initialize() throws IOException {
   124         try {
   125             executeInBrowser();
   126         } catch (InterruptedException ex) {
   127             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   128             iio.initCause(ex);
   129             throw iio;
   130         } catch (Exception ex) {
   131             if (ex instanceof IOException) {
   132                 throw (IOException)ex;
   133             }
   134             if (ex instanceof RuntimeException) {
   135                 throw (RuntimeException)ex;
   136             }
   137             throw new IOException(ex);
   138         }
   139     }
   140     
   141     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   142         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   143 
   144         final ServerConfiguration conf = s.getServerConfiguration();
   145         if (addClasses) {
   146             conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   147             conf.addHttpHandler(new Classes(resources), "/classes/");
   148         }
   149         return s;
   150     }
   151     
   152     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   153         wait = new CountDownLatch(1);
   154         server = initServer(".", true);
   155         final ServerConfiguration conf = server.getServerConfiguration();
   156         
   157         class DynamicResourceHandler extends HttpHandler {
   158             private final InvocationContext ic;
   159             public DynamicResourceHandler(InvocationContext ic) {
   160                 if (ic == null || ic.resources.isEmpty()) {
   161                     throw new NullPointerException();
   162                 }
   163                 this.ic = ic;
   164                 for (Resource r : ic.resources) {
   165                     conf.addHttpHandler(this, r.httpPath);
   166                 }
   167             }
   168 
   169             public void close() {
   170                 conf.removeHttpHandler(this);
   171             }
   172             
   173             @Override
   174             public void service(Request request, Response response) throws Exception {
   175                 for (Resource r : ic.resources) {
   176                     if (r.httpPath.equals(request.getRequestURI())) {
   177                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   178                         response.setContentType(r.httpType);
   179                         copyStream(r.httpContent, response.getOutputStream(), null);
   180                     }
   181                 }
   182             }
   183         }
   184         
   185         conf.addHttpHandler(new Page(resources, 
   186             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   187         ), "/execute");
   188         
   189         conf.addHttpHandler(new HttpHandler() {
   190             int cnt;
   191             List<InvocationContext> cases = new ArrayList<>();
   192             DynamicResourceHandler prev;
   193             @Override
   194             public void service(Request request, Response response) throws Exception {
   195                 String id = request.getParameter("request");
   196                 String value = request.getParameter("result");
   197                 
   198                 
   199                 InvocationContext mi = null;
   200                 int caseNmbr = -1;
   201                 
   202                 if (id != null && value != null) {
   203                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   204                     value = decodeURL(value);
   205                     int indx = Integer.parseInt(id);
   206                     cases.get(indx).result(value, null);
   207                     if (++indx < cases.size()) {
   208                         mi = cases.get(indx);
   209                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   210                         caseNmbr = indx;
   211                     }
   212                 } else {
   213                     if (!cases.isEmpty()) {
   214                         LOG.info("Re-executing test cases");
   215                         mi = cases.get(0);
   216                         caseNmbr = 0;
   217                     }
   218                 }
   219                 
   220                 if (prev != null) {
   221                     prev.close();
   222                     prev = null;
   223                 }
   224                 
   225                 if (mi == null) {
   226                     mi = methods.take();
   227                     caseNmbr = cnt++;
   228                 }
   229                 if (mi == END) {
   230                     response.getWriter().write("");
   231                     wait.countDown();
   232                     cnt = 0;
   233                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   234                     return;
   235                 }
   236                 
   237                 if (!mi.resources.isEmpty()) {
   238                     prev = new DynamicResourceHandler(mi);
   239                 }
   240                 
   241                 cases.add(mi);
   242                 final String cn = mi.clazz.getName();
   243                 final String mn = mi.methodName;
   244                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   245                 response.getWriter().write("{"
   246                     + "className: '" + cn + "', "
   247                     + "methodName: '" + mn + "', "
   248                     + "request: " + caseNmbr
   249                 );
   250                 if (mi.html != null) {
   251                     response.getWriter().write(", html: '");
   252                     response.getWriter().write(encodeJSON(mi.html));
   253                     response.getWriter().write("'");
   254                 }
   255                 response.getWriter().write("}");
   256             }
   257         }, "/data");
   258 
   259         this.brwsr = launchServerAndBrwsr(server, "/execute");
   260     }
   261     
   262     private static String encodeJSON(String in) {
   263         StringBuilder sb = new StringBuilder();
   264         for (int i = 0; i < in.length(); i++) {
   265             char ch = in.charAt(i);
   266             if (ch < 32 || ch == '\'' || ch == '"') {
   267                 sb.append("\\u");
   268                 String hs = "0000" + Integer.toHexString(ch);
   269                 hs = hs.substring(hs.length() - 4);
   270                 sb.append(hs);
   271             } else {
   272                 sb.append(ch);
   273             }
   274         }
   275         return sb.toString();
   276     }
   277     
   278     @Override
   279     public void shutdown() throws IOException {
   280         methods.offer(END);
   281         for (;;) {
   282             int prev = methods.size();
   283             try {
   284                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   285                     break;
   286                 }
   287             } catch (InterruptedException ex) {
   288                 throw new IOException(ex);
   289             }
   290             if (prev == methods.size()) {
   291                 LOG.log(
   292                     Level.WARNING, 
   293                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   294                     methods.size()
   295                 );
   296                 break;
   297             }
   298             LOG.log(Level.INFO, 
   299                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   300                 new Object[]{prev, methods.size()}
   301             );
   302         }
   303         stopServerAndBrwsr(server, brwsr);
   304     }
   305     
   306     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   307         for (;;) {
   308             int ch = is.read();
   309             if (ch == -1) {
   310                 break;
   311             }
   312             if (ch == '$' && params.length > 0) {
   313                 int cnt = is.read() - '0';
   314                 if (cnt == 'U' - '0') {
   315                     os.write(baseURL.getBytes("UTF-8"));
   316                 }
   317                 if (cnt >= 0 && cnt < params.length) {
   318                     os.write(params[cnt].getBytes("UTF-8"));
   319                 }
   320             } else {
   321                 os.write(ch);
   322             }
   323         }
   324     }
   325 
   326     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   327         server.start();
   328         NetworkListener listener = server.getListeners().iterator().next();
   329         int port = listener.getPort();
   330         
   331         URI uri = new URI("http://localhost:" + port + page);
   332         LOG.log(Level.INFO, "Showing {0}", uri);
   333         if (cmd == null) {
   334             try {
   335                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   336                     System.getProperty("java.vm.name"),
   337                     System.getProperty("java.vm.vendor"),
   338                     System.getProperty("java.vm.version"),
   339                 });
   340                 java.awt.Desktop.getDesktop().browse(uri);
   341                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   342                 return null;
   343             } catch (UnsupportedOperationException ex) {
   344                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   345                 LOG.log(Level.FINE, null, ex);
   346             }
   347         }
   348         {
   349             String cmdName = cmd == null ? "xdg-open" : cmd;
   350             String[] cmdArr = { 
   351                 cmdName, uri.toString()
   352             };
   353             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   354             final Process process = Runtime.getRuntime().exec(cmdArr);
   355             return new Object[] { process, null };
   356         }
   357     }
   358     
   359     private static String decodeURL(String s) {
   360         for (;;) {
   361             int pos = s.indexOf('%');
   362             if (pos == -1) {
   363                 return s;
   364             }
   365             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   366             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   367         }
   368     }
   369     
   370     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   371         if (brwsr == null) {
   372             return;
   373         }
   374         Process process = (Process)brwsr[0];
   375         
   376         server.stop();
   377         InputStream stdout = process.getInputStream();
   378         InputStream stderr = process.getErrorStream();
   379         drain("StdOut", stdout);
   380         drain("StdErr", stderr);
   381         process.destroy();
   382         int res;
   383         try {
   384             res = process.waitFor();
   385         } catch (InterruptedException ex) {
   386             throw new IOException(ex);
   387         }
   388         LOG.log(Level.INFO, "Exit code: {0}", res);
   389 
   390         deleteTree((File)brwsr[1]);
   391     }
   392     
   393     private static void drain(String name, InputStream is) throws IOException {
   394         int av = is.available();
   395         if (av > 0) {
   396             StringBuilder sb = new StringBuilder();
   397             sb.append("v== ").append(name).append(" ==v\n");
   398             while (av-- > 0) {
   399                 sb.append((char)is.read());
   400             }
   401             sb.append("\n^== ").append(name).append(" ==^");
   402             LOG.log(Level.INFO, sb.toString());
   403         }
   404     }
   405 
   406     private void deleteTree(File file) {
   407         if (file == null) {
   408             return;
   409         }
   410         File[] arr = file.listFiles();
   411         if (arr != null) {
   412             for (File s : arr) {
   413                 deleteTree(s);
   414             }
   415         }
   416         file.delete();
   417     }
   418 
   419     @Override
   420     public void close() throws IOException {
   421         shutdown();
   422     }
   423 
   424     private class Res implements Bck2Brwsr.Resources {
   425         @Override
   426         public InputStream get(String resource) throws IOException {
   427             for (ClassLoader l : loaders) {
   428                 URL u = null;
   429                 Enumeration<URL> en = l.getResources(resource);
   430                 while (en.hasMoreElements()) {
   431                     u = en.nextElement();
   432                 }
   433                 if (u != null) {
   434                     return u.openStream();
   435                 }
   436             }
   437             throw new IOException("Can't find " + resource);
   438         }
   439     }
   440 
   441     private static class Page extends HttpHandler {
   442         private final String resource;
   443         private final String[] args;
   444         private final Res res;
   445         
   446         public Page(Res res, String resource, String... args) {
   447             this.res = res;
   448             this.resource = resource;
   449             this.args = args.length == 0 ? new String[] { "$0" } : args;
   450         }
   451 
   452         @Override
   453         public void service(Request request, Response response) throws Exception {
   454             String r = resource;
   455             if (r == null) {
   456                 r = request.getHttpHandlerPath();
   457             }
   458             if (r.startsWith("/")) {
   459                 r = r.substring(1);
   460             }
   461             String[] replace = {};
   462             if (r.endsWith(".html")) {
   463                 response.setContentType("text/html");
   464                 LOG.info("Content type text/html");
   465                 replace = args;
   466             }
   467             if (r.endsWith(".xhtml")) {
   468                 response.setContentType("application/xhtml+xml");
   469                 LOG.info("Content type application/xhtml+xml");
   470                 replace = args;
   471             }
   472             OutputStream os = response.getOutputStream();
   473             try (InputStream is = res.get(r)) {
   474                 copyStream(is, os, request.getRequestURL().toString(), replace);
   475             } catch (IOException ex) {
   476                 response.setDetailMessage(ex.getLocalizedMessage());
   477                 response.setError();
   478                 response.setStatus(404);
   479             }
   480         }
   481     }
   482 
   483     private static class VM extends HttpHandler {
   484         private final String bck2brwsr;
   485 
   486         public VM(Res loader) throws IOException {
   487             StringBuilder sb = new StringBuilder();
   488             Bck2Brwsr.generate(sb, loader);
   489             sb.append(
   490                   "(function WrapperVM(global) {"
   491                 + "  function ldCls(res) {\n"
   492                 + "    var request = new XMLHttpRequest();\n"
   493                 + "    request.open('GET', '/classes/' + res, false);\n"
   494                 + "    request.send();\n"
   495                 + "    if (request.status !== 200) return null;\n"
   496                 + "    var arr = eval('(' + request.responseText + ')');\n"
   497                 + "    return arr;\n"
   498                 + "  }\n"
   499                 + "  var prevvm = global.bck2brwsr;\n"
   500                 + "  global.bck2brwsr = function() {\n"
   501                 + "    var args = Array.prototype.slice.apply(arguments);\n"
   502                 + "    args.unshift(ldCls);\n"
   503                 + "    return prevvm.apply(null, args);\n"
   504                 + "  };\n"
   505                 + "})(this);\n"
   506             );
   507             this.bck2brwsr = sb.toString();
   508         }
   509 
   510         @Override
   511         public void service(Request request, Response response) throws Exception {
   512             response.setCharacterEncoding("UTF-8");
   513             response.setContentType("text/javascript");
   514             response.getWriter().write(bck2brwsr);
   515         }
   516     }
   517 
   518     private static class Classes extends HttpHandler {
   519         private final Res loader;
   520 
   521         public Classes(Res loader) {
   522             this.loader = loader;
   523         }
   524 
   525         @Override
   526         public void service(Request request, Response response) throws Exception {
   527             String res = request.getHttpHandlerPath();
   528             if (res.startsWith("/")) {
   529                 res = res.substring(1);
   530             }
   531             try (InputStream is = loader.get(res)) {
   532                 response.setContentType("text/javascript");
   533                 Writer w = response.getWriter();
   534                 w.append("[");
   535                 for (int i = 0;; i++) {
   536                     int b = is.read();
   537                     if (b == -1) {
   538                         break;
   539                     }
   540                     if (i > 0) {
   541                         w.append(", ");
   542                     }
   543                     if (i % 20 == 0) {
   544                         w.write("\n");
   545                     }
   546                     if (b > 127) {
   547                         b = b - 256;
   548                     }
   549                     w.append(Integer.toString(b));
   550                 }
   551                 w.append("\n]");
   552             } catch (IOException ex) {
   553                 response.setStatus(HttpStatus.NOT_FOUND_404);
   554                 response.setError();
   555                 response.setDetailMessage(ex.getMessage());
   556             }
   557         }
   558     }
   559 }