launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Jan 2013 13:18:46 +0100
branchdew
changeset 544 08ffdc3938e7
parent 543 1adce93fea0f
child 580 2f42cd9b5531
permissions -rw-r--r--
Moving Development Environment for Web to own project
     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 MethodInvocation END = new MethodInvocation(null, null, null);
    59     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    60     private BlockingQueue<MethodInvocation> 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      MethodInvocation addMethod(Class<?> clazz, String method, String html) throws IOException {
    74         loaders.add(clazz.getClassLoader());
    75         MethodInvocation c = new MethodInvocation(clazz.getName(), method, html);
    76         methods.add(c);
    77         try {
    78             c.await(timeOut);
    79         } catch (InterruptedException ex) {
    80             throw new IOException(ex);
    81         }
    82         return c;
    83     }
    84     
    85     public void setTimeout(long ms) {
    86         timeOut = ms;
    87     }
    88     
    89     public void addClassLoader(ClassLoader url) {
    90         this.loaders.add(url);
    91     }
    92 
    93     public void showURL(String startpage) throws IOException {
    94         if (!startpage.startsWith("/")) {
    95             startpage = "/" + startpage;
    96         }
    97         HttpServer s = initServer();
    98         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
    99         try {
   100             launchServerAndBrwsr(s, startpage);
   101         } catch (URISyntaxException | InterruptedException ex) {
   102             throw new IOException(ex);
   103         }
   104     }
   105 
   106     @Override
   107     public void initialize() throws IOException {
   108         try {
   109             executeInBrowser();
   110         } catch (InterruptedException ex) {
   111             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   112             iio.initCause(ex);
   113             throw iio;
   114         } catch (Exception ex) {
   115             if (ex instanceof IOException) {
   116                 throw (IOException)ex;
   117             }
   118             if (ex instanceof RuntimeException) {
   119                 throw (RuntimeException)ex;
   120             }
   121             throw new IOException(ex);
   122         }
   123     }
   124     
   125     private HttpServer initServer() {
   126         HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
   127 
   128         final ServerConfiguration conf = s.getServerConfiguration();
   129         conf.addHttpHandler(new Page(resources, 
   130             "org/apidesign/bck2brwsr/launcher/console.xhtml",
   131             "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
   132         ), "/console");
   133         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   134         conf.addHttpHandler(new VMInit(), "/vm.js");
   135         conf.addHttpHandler(new Classes(resources), "/classes/");
   136         return s;
   137     }
   138     
   139     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   140         wait = new CountDownLatch(1);
   141         server = initServer();
   142         ServerConfiguration conf = server.getServerConfiguration();
   143         conf.addHttpHandler(new Page(resources, 
   144             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   145         ), "/execute");
   146         conf.addHttpHandler(new HttpHandler() {
   147             int cnt;
   148             List<MethodInvocation> cases = new ArrayList<>();
   149             @Override
   150             public void service(Request request, Response response) throws Exception {
   151                 String id = request.getParameter("request");
   152                 String value = request.getParameter("result");
   153                 
   154                 if (id != null && value != null) {
   155                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   156                     value = decodeURL(value);
   157                     cases.get(Integer.parseInt(id)).result(value, null);
   158                 }
   159                 
   160                 MethodInvocation mi = methods.take();
   161                 if (mi == END) {
   162                     response.getWriter().write("");
   163                     wait.countDown();
   164                     cnt = 0;
   165                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   166                     return;
   167                 }
   168                 
   169                 cases.add(mi);
   170                 final String cn = mi.className;
   171                 final String mn = mi.methodName;
   172                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   173                 response.getWriter().write("{"
   174                     + "className: '" + cn + "', "
   175                     + "methodName: '" + mn + "', "
   176                     + "request: " + cnt
   177                 );
   178                 if (mi.html != null) {
   179                     response.getWriter().write(", html: '");
   180                     response.getWriter().write(encodeJSON(mi.html));
   181                     response.getWriter().write("'");
   182                 }
   183                 response.getWriter().write("}");
   184                 cnt++;
   185             }
   186         }, "/data");
   187 
   188         this.brwsr = launchServerAndBrwsr(server, "/execute");
   189     }
   190     
   191     private static String encodeJSON(String in) {
   192         StringBuilder sb = new StringBuilder();
   193         for (int i = 0; i < in.length(); i++) {
   194             char ch = in.charAt(i);
   195             if (ch < 32 || ch == '\'' || ch == '"') {
   196                 sb.append("\\u");
   197                 String hs = "0000" + Integer.toHexString(ch);
   198                 hs = hs.substring(hs.length() - 4);
   199                 sb.append(hs);
   200             } else {
   201                 sb.append(ch);
   202             }
   203         }
   204         return sb.toString();
   205     }
   206     
   207     @Override
   208     public void shutdown() throws IOException {
   209         methods.offer(END);
   210         for (;;) {
   211             int prev = methods.size();
   212             try {
   213                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   214                     break;
   215                 }
   216             } catch (InterruptedException ex) {
   217                 throw new IOException(ex);
   218             }
   219             if (prev == methods.size()) {
   220                 LOG.log(
   221                     Level.WARNING, 
   222                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   223                     methods.size()
   224                 );
   225                 break;
   226             }
   227             LOG.log(Level.INFO, 
   228                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   229                 new Object[]{prev, methods.size()}
   230             );
   231         }
   232         stopServerAndBrwsr(server, brwsr);
   233     }
   234     
   235     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   236         for (;;) {
   237             int ch = is.read();
   238             if (ch == -1) {
   239                 break;
   240             }
   241             if (ch == '$' && params.length > 0) {
   242                 int cnt = is.read() - '0';
   243                 if (cnt == 'U' - '0') {
   244                     os.write(baseURL.getBytes());
   245                 }
   246                 if (cnt >= 0 && cnt < params.length) {
   247                     os.write(params[cnt].getBytes());
   248                 }
   249             } else {
   250                 os.write(ch);
   251             }
   252         }
   253     }
   254 
   255     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   256         server.start();
   257         NetworkListener listener = server.getListeners().iterator().next();
   258         int port = listener.getPort();
   259         
   260         URI uri = new URI("http://localhost:" + port + page);
   261         LOG.log(Level.INFO, "Showing {0}", uri);
   262         if (cmd == null) {
   263             try {
   264                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   265                     System.getProperty("java.vm.name"),
   266                     System.getProperty("java.vm.vendor"),
   267                     System.getProperty("java.vm.version"),
   268                 });
   269                 java.awt.Desktop.getDesktop().browse(uri);
   270                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   271                 return null;
   272             } catch (UnsupportedOperationException ex) {
   273                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   274                 LOG.log(Level.FINE, null, ex);
   275             }
   276         }
   277         {
   278             String cmdName = cmd == null ? "xdg-open" : cmd;
   279             String[] cmdArr = { 
   280                 cmdName, uri.toString()
   281             };
   282             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   283             final Process process = Runtime.getRuntime().exec(cmdArr);
   284             return new Object[] { process, null };
   285         }
   286     }
   287     
   288     private static String decodeURL(String s) {
   289         for (;;) {
   290             int pos = s.indexOf('%');
   291             if (pos == -1) {
   292                 return s;
   293             }
   294             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   295             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   296         }
   297     }
   298     
   299     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   300         if (brwsr == null) {
   301             return;
   302         }
   303         Process process = (Process)brwsr[0];
   304         
   305         server.stop();
   306         InputStream stdout = process.getInputStream();
   307         InputStream stderr = process.getErrorStream();
   308         drain("StdOut", stdout);
   309         drain("StdErr", stderr);
   310         process.destroy();
   311         int res;
   312         try {
   313             res = process.waitFor();
   314         } catch (InterruptedException ex) {
   315             throw new IOException(ex);
   316         }
   317         LOG.log(Level.INFO, "Exit code: {0}", res);
   318 
   319         deleteTree((File)brwsr[1]);
   320     }
   321     
   322     private static void drain(String name, InputStream is) throws IOException {
   323         int av = is.available();
   324         if (av > 0) {
   325             StringBuilder sb = new StringBuilder();
   326             sb.append("v== ").append(name).append(" ==v\n");
   327             while (av-- > 0) {
   328                 sb.append((char)is.read());
   329             }
   330             sb.append("\n^== ").append(name).append(" ==^");
   331             LOG.log(Level.INFO, sb.toString());
   332         }
   333     }
   334 
   335     private void deleteTree(File file) {
   336         if (file == null) {
   337             return;
   338         }
   339         File[] arr = file.listFiles();
   340         if (arr != null) {
   341             for (File s : arr) {
   342                 deleteTree(s);
   343             }
   344         }
   345         file.delete();
   346     }
   347 
   348     @Override
   349     public void close() throws IOException {
   350         shutdown();
   351     }
   352 
   353     private class Res implements Bck2Brwsr.Resources {
   354         @Override
   355         public InputStream get(String resource) throws IOException {
   356             for (ClassLoader l : loaders) {
   357                 URL u = null;
   358                 Enumeration<URL> en = l.getResources(resource);
   359                 while (en.hasMoreElements()) {
   360                     u = en.nextElement();
   361                 }
   362                 if (u != null) {
   363                     return u.openStream();
   364                 }
   365             }
   366             throw new IOException("Can't find " + resource);
   367         }
   368     }
   369 
   370     private static class Page extends HttpHandler {
   371         private final String resource;
   372         private final String[] args;
   373         private final Res res;
   374         
   375         public Page(Res res, String resource, String... args) {
   376             this.res = res;
   377             this.resource = resource;
   378             this.args = args.length == 0 ? new String[] { "$0" } : args;
   379         }
   380 
   381         @Override
   382         public void service(Request request, Response response) throws Exception {
   383             String r = resource;
   384             if (r == null) {
   385                 r = request.getHttpHandlerPath();
   386                 if (r.startsWith("/")) {
   387                     r = r.substring(1);
   388                 }
   389             }
   390             String[] replace = {};
   391             if (r.endsWith(".html")) {
   392                 response.setContentType("text/html");
   393                 LOG.info("Content type text/html");
   394                 replace = args;
   395             }
   396             if (r.endsWith(".xhtml")) {
   397                 response.setContentType("application/xhtml+xml");
   398                 LOG.info("Content type application/xhtml+xml");
   399                 replace = args;
   400             }
   401             OutputStream os = response.getOutputStream();
   402             try (InputStream is = res.get(r)) {
   403                 copyStream(is, os, request.getRequestURL().toString(), replace);
   404             } catch (IOException ex) {
   405                 response.setDetailMessage(ex.getLocalizedMessage());
   406                 response.setError();
   407                 response.setStatus(404);
   408             }
   409         }
   410     }
   411 
   412     private static class VM extends HttpHandler {
   413         private final Res loader;
   414 
   415         public VM(Res loader) {
   416             this.loader = loader;
   417         }
   418 
   419         @Override
   420         public void service(Request request, Response response) throws Exception {
   421             response.setCharacterEncoding("UTF-8");
   422             response.setContentType("text/javascript");
   423             Bck2Brwsr.generate(response.getWriter(), loader);
   424         }
   425     }
   426     private static class VMInit extends HttpHandler {
   427         public VMInit() {
   428         }
   429 
   430         @Override
   431         public void service(Request request, Response response) throws Exception {
   432             response.setCharacterEncoding("UTF-8");
   433             response.setContentType("text/javascript");
   434             response.getWriter().append(
   435                 "function ldCls(res) {\n"
   436                 + "  var request = new XMLHttpRequest();\n"
   437                 + "  request.open('GET', '/classes/' + res, false);\n"
   438                 + "  request.send();\n"
   439                 + "  var arr = eval('(' + request.responseText + ')');\n"
   440                 + "  return arr;\n"
   441                 + "}\n"
   442                 + "var vm = new bck2brwsr(ldCls);\n");
   443         }
   444     }
   445 
   446     private static class Classes extends HttpHandler {
   447         private final Res loader;
   448 
   449         public Classes(Res loader) {
   450             this.loader = loader;
   451         }
   452 
   453         @Override
   454         public void service(Request request, Response response) throws Exception {
   455             String res = request.getHttpHandlerPath();
   456             if (res.startsWith("/")) {
   457                 res = res.substring(1);
   458             }
   459             try (InputStream is = loader.get(res)) {
   460                 response.setContentType("text/javascript");
   461                 Writer w = response.getWriter();
   462                 w.append("[");
   463                 for (int i = 0;; i++) {
   464                     int b = is.read();
   465                     if (b == -1) {
   466                         break;
   467                     }
   468                     if (i > 0) {
   469                         w.append(", ");
   470                     }
   471                     if (i % 20 == 0) {
   472                         w.write("\n");
   473                     }
   474                     if (b > 127) {
   475                         b = b - 256;
   476                     }
   477                     w.append(Integer.toString(b));
   478                 }
   479                 w.append("\n]");
   480             } catch (IOException ex) {
   481                 response.setError();
   482                 response.setDetailMessage(ex.getMessage());
   483             }
   484         }
   485     }
   486 }