launcher/http/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 07 May 2013 16:16:21 +0200
changeset 1081 47687dce809a
parent 1076 892dcb178737
child 1088 4b65abc39565
permissions -rw-r--r--
No need for hacks anymore now when GRIZZLY-1450 was fixed
     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                 
   212                 
   213                 InvocationContext mi = null;
   214                 int caseNmbr = -1;
   215                 
   216                 if (id != null && value != null) {
   217                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   218                     value = decodeURL(value);
   219                     int indx = Integer.parseInt(id);
   220                     cases.get(indx).result(value, null);
   221                     if (++indx < cases.size()) {
   222                         mi = cases.get(indx);
   223                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   224                         caseNmbr = indx;
   225                     }
   226                 } else {
   227                     if (!cases.isEmpty()) {
   228                         LOG.info("Re-executing test cases");
   229                         mi = cases.get(0);
   230                         caseNmbr = 0;
   231                     }
   232                 }
   233                 
   234                 if (prev != null) {
   235                     prev.close();
   236                     prev = null;
   237                 }
   238                 
   239                 if (mi == null) {
   240                     mi = methods.take();
   241                     caseNmbr = cnt++;
   242                 }
   243                 if (mi == END) {
   244                     response.getWriter().write("");
   245                     wait.countDown();
   246                     cnt = 0;
   247                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   248                     return;
   249                 }
   250                 
   251                 if (!mi.resources.isEmpty()) {
   252                     prev = new DynamicResourceHandler(mi);
   253                 }
   254                 
   255                 cases.add(mi);
   256                 final String cn = mi.clazz.getName();
   257                 final String mn = mi.methodName;
   258                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   259                 response.getWriter().write("{"
   260                     + "className: '" + cn + "', "
   261                     + "methodName: '" + mn + "', "
   262                     + "request: " + caseNmbr
   263                 );
   264                 if (mi.html != null) {
   265                     response.getWriter().write(", html: '");
   266                     response.getWriter().write(encodeJSON(mi.html));
   267                     response.getWriter().write("'");
   268                 }
   269                 response.getWriter().write("}");
   270             }
   271         }, "/data");
   272 
   273         this.brwsr = launchServerAndBrwsr(server, "/execute");
   274     }
   275     
   276     private static String encodeJSON(String in) {
   277         StringBuilder sb = new StringBuilder();
   278         for (int i = 0; i < in.length(); i++) {
   279             char ch = in.charAt(i);
   280             if (ch < 32 || ch == '\'' || ch == '"') {
   281                 sb.append("\\u");
   282                 String hs = "0000" + Integer.toHexString(ch);
   283                 hs = hs.substring(hs.length() - 4);
   284                 sb.append(hs);
   285             } else {
   286                 sb.append(ch);
   287             }
   288         }
   289         return sb.toString();
   290     }
   291     
   292     @Override
   293     public void shutdown() throws IOException {
   294         methods.offer(END);
   295         for (;;) {
   296             int prev = methods.size();
   297             try {
   298                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   299                     break;
   300                 }
   301             } catch (InterruptedException ex) {
   302                 throw new IOException(ex);
   303             }
   304             if (prev == methods.size()) {
   305                 LOG.log(
   306                     Level.WARNING, 
   307                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   308                     methods.size()
   309                 );
   310                 break;
   311             }
   312             LOG.log(Level.INFO, 
   313                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   314                 new Object[]{prev, methods.size()}
   315             );
   316         }
   317         stopServerAndBrwsr(server, brwsr);
   318     }
   319     
   320     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   321         for (;;) {
   322             int ch = is.read();
   323             if (ch == -1) {
   324                 break;
   325             }
   326             if (ch == '$' && params.length > 0) {
   327                 int cnt = is.read() - '0';
   328                 if (baseURL != null && cnt == 'U' - '0') {
   329                     os.write(baseURL.getBytes("UTF-8"));
   330                 } else {
   331                     if (cnt >= 0 && cnt < params.length) {
   332                         os.write(params[cnt].getBytes("UTF-8"));
   333                     } else {
   334                         os.write('$');
   335                         os.write(cnt + '0');
   336                     }
   337                 }
   338             } else {
   339                 os.write(ch);
   340             }
   341         }
   342     }
   343 
   344     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   345         server.start();
   346         NetworkListener listener = server.getListeners().iterator().next();
   347         int port = listener.getPort();
   348         
   349         URI uri = new URI("http://localhost:" + port + page);
   350         LOG.log(Level.INFO, "Showing {0}", uri);
   351         if (cmd == null) {
   352             try {
   353                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   354                     System.getProperty("java.vm.name"),
   355                     System.getProperty("java.vm.vendor"),
   356                     System.getProperty("java.vm.version"),
   357                 });
   358                 java.awt.Desktop.getDesktop().browse(uri);
   359                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   360                 return null;
   361             } catch (UnsupportedOperationException ex) {
   362                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   363                 LOG.log(Level.FINE, null, ex);
   364             }
   365         }
   366         {
   367             String cmdName = cmd == null ? "xdg-open" : cmd;
   368             String[] cmdArr = { 
   369                 cmdName, uri.toString()
   370             };
   371             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   372             final Process process = Runtime.getRuntime().exec(cmdArr);
   373             return new Object[] { process, null };
   374         }
   375     }
   376     
   377     private static String decodeURL(String s) {
   378         for (;;) {
   379             int pos = s.indexOf('%');
   380             if (pos == -1) {
   381                 return s;
   382             }
   383             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   384             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   385         }
   386     }
   387     
   388     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   389         if (brwsr == null) {
   390             return;
   391         }
   392         Process process = (Process)brwsr[0];
   393         
   394         server.stop();
   395         InputStream stdout = process.getInputStream();
   396         InputStream stderr = process.getErrorStream();
   397         drain("StdOut", stdout);
   398         drain("StdErr", stderr);
   399         process.destroy();
   400         int res;
   401         try {
   402             res = process.waitFor();
   403         } catch (InterruptedException ex) {
   404             throw new IOException(ex);
   405         }
   406         LOG.log(Level.INFO, "Exit code: {0}", res);
   407 
   408         deleteTree((File)brwsr[1]);
   409     }
   410     
   411     private static void drain(String name, InputStream is) throws IOException {
   412         int av = is.available();
   413         if (av > 0) {
   414             StringBuilder sb = new StringBuilder();
   415             sb.append("v== ").append(name).append(" ==v\n");
   416             while (av-- > 0) {
   417                 sb.append((char)is.read());
   418             }
   419             sb.append("\n^== ").append(name).append(" ==^");
   420             LOG.log(Level.INFO, sb.toString());
   421         }
   422     }
   423 
   424     private void deleteTree(File file) {
   425         if (file == null) {
   426             return;
   427         }
   428         File[] arr = file.listFiles();
   429         if (arr != null) {
   430             for (File s : arr) {
   431                 deleteTree(s);
   432             }
   433         }
   434         file.delete();
   435     }
   436 
   437     @Override
   438     public HttpServer call() throws Exception {
   439         return server;
   440     }
   441     
   442     @Override
   443     public void close() throws IOException {
   444         shutdown();
   445     }
   446 
   447     private class Res implements Bck2Brwsr.Resources {
   448         @Override
   449         public InputStream get(String resource) throws IOException {
   450             URL u = null;
   451             for (ClassLoader l : loaders) {
   452                 Enumeration<URL> en = l.getResources(resource);
   453                 while (en.hasMoreElements()) {
   454                     u = en.nextElement();
   455                 }
   456             }
   457             if (u != null) {
   458                 return u.openStream();
   459             }
   460             throw new IOException("Can't find " + resource);
   461         }
   462     }
   463 
   464     private static class Page extends HttpHandler {
   465         final String resource;
   466         private final String[] args;
   467         private final Res res;
   468         
   469         public Page(Res res, String resource, String... args) {
   470             this.res = res;
   471             this.resource = resource;
   472             this.args = args.length == 0 ? new String[] { "$0" } : args;
   473         }
   474 
   475         @Override
   476         public void service(Request request, Response response) throws Exception {
   477             String r = computePage(request);
   478             if (r.startsWith("/")) {
   479                 r = r.substring(1);
   480             }
   481             String[] replace = {};
   482             if (r.endsWith(".html")) {
   483                 response.setContentType("text/html");
   484                 LOG.info("Content type text/html");
   485                 replace = args;
   486             }
   487             if (r.endsWith(".xhtml")) {
   488                 response.setContentType("application/xhtml+xml");
   489                 LOG.info("Content type application/xhtml+xml");
   490                 replace = args;
   491             }
   492             OutputStream os = response.getOutputStream();
   493             try (InputStream is = res.get(r)) {
   494                 copyStream(is, os, request.getRequestURL().toString(), replace);
   495             } catch (IOException ex) {
   496                 response.setDetailMessage(ex.getLocalizedMessage());
   497                 response.setError();
   498                 response.setStatus(404);
   499             }
   500         }
   501 
   502         protected String computePage(Request request) {
   503             String r = resource;
   504             if (r == null) {
   505                 r = request.getHttpHandlerPath();
   506             }
   507             return r;
   508         }
   509     }
   510     
   511     private static class SubTree extends Page {
   512 
   513         public SubTree(Res res, String resource, String... args) {
   514             super(res, resource, args);
   515         }
   516 
   517         @Override
   518         protected String computePage(Request request) {
   519             return resource + request.getHttpHandlerPath();
   520         }
   521         
   522         
   523     }
   524 
   525     private static class VM extends HttpHandler {
   526         private final String bck2brwsr;
   527 
   528         public VM(Res loader) throws IOException {
   529             StringBuilder sb = new StringBuilder();
   530             Bck2Brwsr.generate(sb, loader);
   531             sb.append(
   532                   "(function WrapperVM(global) {"
   533                 + "  function ldCls(res) {\n"
   534                 + "    var request = new XMLHttpRequest();\n"
   535                 + "    request.open('GET', '/classes/' + res, false);\n"
   536                 + "    request.send();\n"
   537                 + "    if (request.status !== 200) return null;\n"
   538                 + "    var arr = eval('(' + request.responseText + ')');\n"
   539                 + "    return arr;\n"
   540                 + "  }\n"
   541                 + "  var prevvm = global.bck2brwsr;\n"
   542                 + "  global.bck2brwsr = function() {\n"
   543                 + "    var args = Array.prototype.slice.apply(arguments);\n"
   544                 + "    args.unshift(ldCls);\n"
   545                 + "    return prevvm.apply(null, args);\n"
   546                 + "  };\n"
   547                 + "})(this);\n"
   548             );
   549             this.bck2brwsr = sb.toString();
   550         }
   551 
   552         @Override
   553         public void service(Request request, Response response) throws Exception {
   554             response.setCharacterEncoding("UTF-8");
   555             response.setContentType("text/javascript");
   556             response.getWriter().write(bck2brwsr);
   557         }
   558     }
   559 
   560     private static class Classes extends HttpHandler {
   561         private final Res loader;
   562 
   563         public Classes(Res loader) {
   564             this.loader = loader;
   565         }
   566 
   567         @Override
   568         public void service(Request request, Response response) throws Exception {
   569             String res = request.getHttpHandlerPath();
   570             if (res.startsWith("/")) {
   571                 res = res.substring(1);
   572             }
   573             try (InputStream is = loader.get(res)) {
   574                 response.setContentType("text/javascript");
   575                 Writer w = response.getWriter();
   576                 w.append("[");
   577                 for (int i = 0;; i++) {
   578                     int b = is.read();
   579                     if (b == -1) {
   580                         break;
   581                     }
   582                     if (i > 0) {
   583                         w.append(", ");
   584                     }
   585                     if (i % 20 == 0) {
   586                         w.write("\n");
   587                     }
   588                     if (b > 127) {
   589                         b = b - 256;
   590                     }
   591                     w.append(Integer.toString(b));
   592                 }
   593                 w.append("\n]");
   594             } catch (IOException ex) {
   595                 response.setStatus(HttpStatus.NOT_FOUND_404);
   596                 response.setError();
   597                 response.setDetailMessage(ex.getMessage());
   598             }
   599         }
   600     }
   601 }