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