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