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