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