launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 12 Feb 2013 12:07:55 +0100
changeset 714 ef50c4f07e4f
parent 626 f08eb4df84c1
child 747 ae352b763959
permissions -rw-r--r--
Explicitly specify UTF-8
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.launcher;
    19 
    20 import java.io.Closeable;
    21 import java.io.File;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.io.InterruptedIOException;
    25 import java.io.OutputStream;
    26 import java.io.Writer;
    27 import java.net.URI;
    28 import java.net.URISyntaxException;
    29 import java.net.URL;
    30 import java.util.ArrayList;
    31 import java.util.Arrays;
    32 import java.util.Enumeration;
    33 import java.util.LinkedHashSet;
    34 import java.util.List;
    35 import java.util.Set;
    36 import java.util.concurrent.BlockingQueue;
    37 import java.util.concurrent.CountDownLatch;
    38 import java.util.concurrent.LinkedBlockingQueue;
    39 import java.util.concurrent.TimeUnit;
    40 import java.util.logging.Level;
    41 import java.util.logging.Logger;
    42 import org.apidesign.vm4brwsr.Bck2Brwsr;
    43 import org.glassfish.grizzly.PortRange;
    44 import org.glassfish.grizzly.http.server.HttpHandler;
    45 import org.glassfish.grizzly.http.server.HttpServer;
    46 import org.glassfish.grizzly.http.server.NetworkListener;
    47 import org.glassfish.grizzly.http.server.Request;
    48 import org.glassfish.grizzly.http.server.Response;
    49 import org.glassfish.grizzly.http.server.ServerConfiguration;
    50 
    51 /**
    52  * Lightweight server to launch Bck2Brwsr applications and tests.
    53  * Supports execution in native browser as well as Java's internal 
    54  * execution engine.
    55  */
    56 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
    57     private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
    58     private static final InvocationContext END = new InvocationContext(null, null, null);
    59     private final Set<ClassLoader> loaders = new LinkedHashSet<>();
    60     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
    61     private long timeOut;
    62     private final Res resources = new Res();
    63     private final String cmd;
    64     private Object[] brwsr;
    65     private HttpServer server;
    66     private CountDownLatch wait;
    67     
    68     public Bck2BrwsrLauncher(String cmd) {
    69         this.cmd = cmd;
    70     }
    71     
    72     @Override
    73     InvocationContext runMethod(InvocationContext c) throws IOException {
    74         loaders.add(c.clazz.getClassLoader());
    75         methods.add(c);
    76         try {
    77             c.await(timeOut);
    78         } catch (InterruptedException ex) {
    79             throw new IOException(ex);
    80         }
    81         return c;
    82     }
    83     
    84     public void setTimeout(long ms) {
    85         timeOut = ms;
    86     }
    87     
    88     public void addClassLoader(ClassLoader url) {
    89         this.loaders.add(url);
    90     }
    91 
    92     public void showURL(String startpage) throws IOException {
    93         if (!startpage.startsWith("/")) {
    94             startpage = "/" + startpage;
    95         }
    96         HttpServer s = initServer(".", true);
    97         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
    98         try {
    99             launchServerAndBrwsr(s, startpage);
   100         } catch (URISyntaxException | InterruptedException ex) {
   101             throw new IOException(ex);
   102         }
   103     }
   104 
   105     void showDirectory(File dir, String startpage) throws IOException {
   106         if (!startpage.startsWith("/")) {
   107             startpage = "/" + startpage;
   108         }
   109         HttpServer s = initServer(dir.getPath(), false);
   110         try {
   111             launchServerAndBrwsr(s, startpage);
   112         } catch (URISyntaxException | InterruptedException ex) {
   113             throw new IOException(ex);
   114         }
   115     }
   116 
   117     @Override
   118     public void initialize() throws IOException {
   119         try {
   120             executeInBrowser();
   121         } catch (InterruptedException ex) {
   122             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   123             iio.initCause(ex);
   124             throw iio;
   125         } catch (Exception ex) {
   126             if (ex instanceof IOException) {
   127                 throw (IOException)ex;
   128             }
   129             if (ex instanceof RuntimeException) {
   130                 throw (RuntimeException)ex;
   131             }
   132             throw new IOException(ex);
   133         }
   134     }
   135     
   136     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   137         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   138 
   139         final ServerConfiguration conf = s.getServerConfiguration();
   140         if (addClasses) {
   141             conf.addHttpHandler(new VM(resources), "/vm.js");
   142             conf.addHttpHandler(new Classes(resources), "/classes/");
   143         }
   144         return s;
   145     }
   146     
   147     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   148         wait = new CountDownLatch(1);
   149         server = initServer(".", true);
   150         final ServerConfiguration conf = server.getServerConfiguration();
   151         
   152         class DynamicResourceHandler extends HttpHandler {
   153             private final InvocationContext ic;
   154             public DynamicResourceHandler(InvocationContext ic) {
   155                 if (ic == null || ic.httpPath == null) {
   156                     throw new NullPointerException();
   157                 }
   158                 this.ic = ic;
   159                 conf.addHttpHandler(this, ic.httpPath);
   160             }
   161 
   162             public void close() {
   163                 conf.removeHttpHandler(this);
   164             }
   165             
   166             @Override
   167             public void service(Request request, Response response) throws Exception {
   168                 if (ic.httpPath.equals(request.getRequestURI())) {
   169                     LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   170                     response.setContentType(ic.httpType);
   171                     copyStream(ic.httpContent, response.getOutputStream(), null);
   172                 }
   173             }
   174         }
   175         
   176         conf.addHttpHandler(new Page(resources, 
   177             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   178         ), "/execute");
   179         
   180         conf.addHttpHandler(new HttpHandler() {
   181             int cnt;
   182             List<InvocationContext> cases = new ArrayList<>();
   183             DynamicResourceHandler prev;
   184             @Override
   185             public void service(Request request, Response response) throws Exception {
   186                 String id = request.getParameter("request");
   187                 String value = request.getParameter("result");
   188                 
   189                 if (id != null && value != null) {
   190                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   191                     value = decodeURL(value);
   192                     cases.get(Integer.parseInt(id)).result(value, null);
   193                 }
   194                 
   195                 if (prev != null) {
   196                     prev.close();
   197                     prev = null;
   198                 }
   199                 
   200                 InvocationContext mi = methods.take();
   201                 if (mi == END) {
   202                     response.getWriter().write("");
   203                     wait.countDown();
   204                     cnt = 0;
   205                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   206                     return;
   207                 }
   208                 
   209                 if (mi.httpPath != null) {
   210                     prev = new DynamicResourceHandler(mi);
   211                 }
   212                 
   213                 cases.add(mi);
   214                 final String cn = mi.clazz.getName();
   215                 final String mn = mi.methodName;
   216                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   217                 response.getWriter().write("{"
   218                     + "className: '" + cn + "', "
   219                     + "methodName: '" + mn + "', "
   220                     + "request: " + cnt
   221                 );
   222                 if (mi.html != null) {
   223                     response.getWriter().write(", html: '");
   224                     response.getWriter().write(encodeJSON(mi.html));
   225                     response.getWriter().write("'");
   226                 }
   227                 response.getWriter().write("}");
   228                 cnt++;
   229             }
   230         }, "/data");
   231 
   232         this.brwsr = launchServerAndBrwsr(server, "/execute");
   233     }
   234     
   235     private static String encodeJSON(String in) {
   236         StringBuilder sb = new StringBuilder();
   237         for (int i = 0; i < in.length(); i++) {
   238             char ch = in.charAt(i);
   239             if (ch < 32 || ch == '\'' || ch == '"') {
   240                 sb.append("\\u");
   241                 String hs = "0000" + Integer.toHexString(ch);
   242                 hs = hs.substring(hs.length() - 4);
   243                 sb.append(hs);
   244             } else {
   245                 sb.append(ch);
   246             }
   247         }
   248         return sb.toString();
   249     }
   250     
   251     @Override
   252     public void shutdown() throws IOException {
   253         methods.offer(END);
   254         for (;;) {
   255             int prev = methods.size();
   256             try {
   257                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   258                     break;
   259                 }
   260             } catch (InterruptedException ex) {
   261                 throw new IOException(ex);
   262             }
   263             if (prev == methods.size()) {
   264                 LOG.log(
   265                     Level.WARNING, 
   266                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   267                     methods.size()
   268                 );
   269                 break;
   270             }
   271             LOG.log(Level.INFO, 
   272                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   273                 new Object[]{prev, methods.size()}
   274             );
   275         }
   276         stopServerAndBrwsr(server, brwsr);
   277     }
   278     
   279     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   280         for (;;) {
   281             int ch = is.read();
   282             if (ch == -1) {
   283                 break;
   284             }
   285             if (ch == '$' && params.length > 0) {
   286                 int cnt = is.read() - '0';
   287                 if (cnt == 'U' - '0') {
   288                     os.write(baseURL.getBytes("UTF-8"));
   289                 }
   290                 if (cnt >= 0 && cnt < params.length) {
   291                     os.write(params[cnt].getBytes("UTF-8"));
   292                 }
   293             } else {
   294                 os.write(ch);
   295             }
   296         }
   297     }
   298 
   299     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   300         server.start();
   301         NetworkListener listener = server.getListeners().iterator().next();
   302         int port = listener.getPort();
   303         
   304         URI uri = new URI("http://localhost:" + port + page);
   305         LOG.log(Level.INFO, "Showing {0}", uri);
   306         if (cmd == null) {
   307             try {
   308                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   309                     System.getProperty("java.vm.name"),
   310                     System.getProperty("java.vm.vendor"),
   311                     System.getProperty("java.vm.version"),
   312                 });
   313                 java.awt.Desktop.getDesktop().browse(uri);
   314                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   315                 return null;
   316             } catch (UnsupportedOperationException ex) {
   317                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   318                 LOG.log(Level.FINE, null, ex);
   319             }
   320         }
   321         {
   322             String cmdName = cmd == null ? "xdg-open" : cmd;
   323             String[] cmdArr = { 
   324                 cmdName, uri.toString()
   325             };
   326             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   327             final Process process = Runtime.getRuntime().exec(cmdArr);
   328             return new Object[] { process, null };
   329         }
   330     }
   331     
   332     private static String decodeURL(String s) {
   333         for (;;) {
   334             int pos = s.indexOf('%');
   335             if (pos == -1) {
   336                 return s;
   337             }
   338             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   339             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   340         }
   341     }
   342     
   343     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   344         if (brwsr == null) {
   345             return;
   346         }
   347         Process process = (Process)brwsr[0];
   348         
   349         server.stop();
   350         InputStream stdout = process.getInputStream();
   351         InputStream stderr = process.getErrorStream();
   352         drain("StdOut", stdout);
   353         drain("StdErr", stderr);
   354         process.destroy();
   355         int res;
   356         try {
   357             res = process.waitFor();
   358         } catch (InterruptedException ex) {
   359             throw new IOException(ex);
   360         }
   361         LOG.log(Level.INFO, "Exit code: {0}", res);
   362 
   363         deleteTree((File)brwsr[1]);
   364     }
   365     
   366     private static void drain(String name, InputStream is) throws IOException {
   367         int av = is.available();
   368         if (av > 0) {
   369             StringBuilder sb = new StringBuilder();
   370             sb.append("v== ").append(name).append(" ==v\n");
   371             while (av-- > 0) {
   372                 sb.append((char)is.read());
   373             }
   374             sb.append("\n^== ").append(name).append(" ==^");
   375             LOG.log(Level.INFO, sb.toString());
   376         }
   377     }
   378 
   379     private void deleteTree(File file) {
   380         if (file == null) {
   381             return;
   382         }
   383         File[] arr = file.listFiles();
   384         if (arr != null) {
   385             for (File s : arr) {
   386                 deleteTree(s);
   387             }
   388         }
   389         file.delete();
   390     }
   391 
   392     @Override
   393     public void close() throws IOException {
   394         shutdown();
   395     }
   396 
   397     private class Res implements Bck2Brwsr.Resources {
   398         @Override
   399         public InputStream get(String resource) throws IOException {
   400             for (ClassLoader l : loaders) {
   401                 URL u = null;
   402                 Enumeration<URL> en = l.getResources(resource);
   403                 while (en.hasMoreElements()) {
   404                     u = en.nextElement();
   405                 }
   406                 if (u != null) {
   407                     return u.openStream();
   408                 }
   409             }
   410             throw new IOException("Can't find " + resource);
   411         }
   412     }
   413 
   414     private static class Page extends HttpHandler {
   415         private final String resource;
   416         private final String[] args;
   417         private final Res res;
   418         
   419         public Page(Res res, String resource, String... args) {
   420             this.res = res;
   421             this.resource = resource;
   422             this.args = args.length == 0 ? new String[] { "$0" } : args;
   423         }
   424 
   425         @Override
   426         public void service(Request request, Response response) throws Exception {
   427             String r = resource;
   428             if (r == null) {
   429                 r = request.getHttpHandlerPath();
   430                 if (r.startsWith("/")) {
   431                     r = r.substring(1);
   432                 }
   433             }
   434             String[] replace = {};
   435             if (r.endsWith(".html")) {
   436                 response.setContentType("text/html");
   437                 LOG.info("Content type text/html");
   438                 replace = args;
   439             }
   440             if (r.endsWith(".xhtml")) {
   441                 response.setContentType("application/xhtml+xml");
   442                 LOG.info("Content type application/xhtml+xml");
   443                 replace = args;
   444             }
   445             OutputStream os = response.getOutputStream();
   446             try (InputStream is = res.get(r)) {
   447                 copyStream(is, os, request.getRequestURL().toString(), replace);
   448             } catch (IOException ex) {
   449                 response.setDetailMessage(ex.getLocalizedMessage());
   450                 response.setError();
   451                 response.setStatus(404);
   452             }
   453         }
   454     }
   455 
   456     private static class VM extends HttpHandler {
   457         private final String bck2brwsr;
   458 
   459         public VM(Res loader) throws IOException {
   460             StringBuilder sb = new StringBuilder();
   461             Bck2Brwsr.generate(sb, loader);
   462             sb.append(
   463                 "function ldCls(res) {\n"
   464                 + "  var request = new XMLHttpRequest();\n"
   465                 + "  request.open('GET', '/classes/' + res, false);\n"
   466                 + "  request.send();\n"
   467                 + "  var arr = eval('(' + request.responseText + ')');\n"
   468                 + "  return arr;\n"
   469                 + "}\n"
   470                 + "var vm = new bck2brwsr(ldCls);\n"
   471             );
   472             this.bck2brwsr = sb.toString();
   473         }
   474 
   475         @Override
   476         public void service(Request request, Response response) throws Exception {
   477             response.setCharacterEncoding("UTF-8");
   478             response.setContentType("text/javascript");
   479             response.getWriter().write(bck2brwsr);
   480         }
   481     }
   482 
   483     private static class Classes extends HttpHandler {
   484         private final Res loader;
   485 
   486         public Classes(Res loader) {
   487             this.loader = loader;
   488         }
   489 
   490         @Override
   491         public void service(Request request, Response response) throws Exception {
   492             String res = request.getHttpHandlerPath();
   493             if (res.startsWith("/")) {
   494                 res = res.substring(1);
   495             }
   496             try (InputStream is = loader.get(res)) {
   497                 response.setContentType("text/javascript");
   498                 Writer w = response.getWriter();
   499                 w.append("[");
   500                 for (int i = 0;; i++) {
   501                     int b = is.read();
   502                     if (b == -1) {
   503                         break;
   504                     }
   505                     if (i > 0) {
   506                         w.append(", ");
   507                     }
   508                     if (i % 20 == 0) {
   509                         w.write("\n");
   510                     }
   511                     if (b > 127) {
   512                         b = b - 256;
   513                     }
   514                     w.append(Integer.toString(b));
   515                 }
   516                 w.append("\n]");
   517             } catch (IOException ex) {
   518                 response.setError();
   519                 response.setDetailMessage(ex.getMessage());
   520             }
   521         }
   522     }
   523 }