launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 23 Dec 2012 23:30:06 +0100
branchlauncher
changeset 372 3485327d3080
parent 371 bafc670aa10d
child 381 70d15cf323ba
permissions -rw-r--r--
Execution time reported by TestNG reflect the time it took to run the query inside of a browser
     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.File;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import java.io.InterruptedIOException;
    24 import java.io.OutputStream;
    25 import java.io.Writer;
    26 import java.net.URI;
    27 import java.net.URISyntaxException;
    28 import java.net.URL;
    29 import java.util.ArrayList;
    30 import java.util.Arrays;
    31 import java.util.Enumeration;
    32 import java.util.LinkedHashSet;
    33 import java.util.List;
    34 import java.util.Set;
    35 import java.util.concurrent.BlockingQueue;
    36 import java.util.concurrent.CountDownLatch;
    37 import java.util.concurrent.LinkedBlockingQueue;
    38 import java.util.concurrent.TimeUnit;
    39 import java.util.logging.Level;
    40 import java.util.logging.Logger;
    41 import org.apidesign.vm4brwsr.Bck2Brwsr;
    42 import org.glassfish.grizzly.PortRange;
    43 import org.glassfish.grizzly.http.server.HttpHandler;
    44 import org.glassfish.grizzly.http.server.HttpServer;
    45 import org.glassfish.grizzly.http.server.NetworkListener;
    46 import org.glassfish.grizzly.http.server.Request;
    47 import org.glassfish.grizzly.http.server.Response;
    48 import org.glassfish.grizzly.http.server.ServerConfiguration;
    49 
    50 /**
    51  * Lightweight server to launch Bck2Brwsr applications and tests.
    52  * Supports execution in native browser as well as Java's internal 
    53  * execution engine.
    54  */
    55 public class Bck2BrwsrLauncher {
    56     private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
    57     private static final MethodInvocation END = new MethodInvocation(null, null);
    58     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    59     private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
    60     private long timeOut;
    61     private final Res resources = new Res();
    62     private Object[] brwsr;
    63     private HttpServer server;
    64     private CountDownLatch wait;
    65     
    66     
    67     public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
    68         loaders.add(clazz.getClassLoader());
    69         MethodInvocation c = new MethodInvocation(clazz.getName(), method);
    70         methods.add(c);
    71         try {
    72             c.await(timeOut);
    73         } catch (InterruptedException ex) {
    74             throw new IOException(ex);
    75         }
    76         return c;
    77     }
    78     
    79     public void setTimeout(long ms) {
    80         timeOut = ms;
    81     }
    82     
    83     public void addClassLoader(ClassLoader url) {
    84         this.loaders.add(url);
    85     }
    86     
    87     public static void main( String[] args ) throws Exception {
    88         Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
    89         l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
    90         l.showURL("org/apidesign/bck2brwsr/launcher/console.xhtml");
    91         System.in.read();
    92     }
    93 
    94     public void showURL(String startpage) throws URISyntaxException, InterruptedException, IOException {
    95         if (!startpage.startsWith("/")) {
    96             startpage = "/" + startpage;
    97         }
    98         HttpServer s = initServer();
    99         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
   100         launchServerAndBrwsr(s, startpage);
   101     }
   102 
   103     public void initialize() throws IOException {
   104         try {
   105             executeInBrowser();
   106         } catch (InterruptedException ex) {
   107             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   108             iio.initCause(ex);
   109             throw iio;
   110         } catch (Exception ex) {
   111             if (ex instanceof IOException) {
   112                 throw (IOException)ex;
   113             }
   114             if (ex instanceof RuntimeException) {
   115                 throw (RuntimeException)ex;
   116             }
   117             throw new IOException(ex);
   118         }
   119     }
   120     
   121     private HttpServer initServer() {
   122         HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
   123 
   124         final ServerConfiguration conf = s.getServerConfiguration();
   125         conf.addHttpHandler(new Page(resources, 
   126             "org/apidesign/bck2brwsr/launcher/console.xhtml",
   127             "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
   128         ), "/console");
   129         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   130         conf.addHttpHandler(new VMInit(), "/vm.js");
   131         conf.addHttpHandler(new Classes(resources), "/classes/");
   132         return s;
   133     }
   134     
   135     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   136         wait = new CountDownLatch(1);
   137         server = initServer();
   138         ServerConfiguration conf = server.getServerConfiguration();
   139         conf.addHttpHandler(new Page(resources, 
   140             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   141         ), "/execute");
   142         conf.addHttpHandler(new HttpHandler() {
   143             int cnt;
   144             List<MethodInvocation> cases = new ArrayList<>();
   145             @Override
   146             public void service(Request request, Response response) throws Exception {
   147                 String id = request.getParameter("request");
   148                 String value = request.getParameter("result");
   149                 
   150                 if (id != null && value != null) {
   151                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   152                     value = value.replace("%20", " ");
   153                     cases.get(Integer.parseInt(id)).result(value, null);
   154                 }
   155                 
   156                 MethodInvocation mi = methods.take();
   157                 if (mi == END) {
   158                     response.getWriter().write("");
   159                     wait.countDown();
   160                     cnt = 0;
   161                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   162                     return;
   163                 }
   164                 
   165                 cases.add(mi);
   166                 final String cn = mi.className;
   167                 final String mn = mi.methodName;
   168                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   169                 response.getWriter().write("{"
   170                     + "className: '" + cn + "', "
   171                     + "methodName: '" + mn + "', "
   172                     + "request: " + cnt
   173                     + "}");
   174                 cnt++;
   175             }
   176         }, "/data");
   177 
   178         this.brwsr = launchServerAndBrwsr(server, "/execute");
   179     }
   180     
   181     public void shutdown() throws InterruptedException, IOException {
   182         methods.offer(END);
   183         for (;;) {
   184             int prev = methods.size();
   185             if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   186                 break;
   187             }
   188             if (prev == methods.size()) {
   189                 LOG.log(
   190                     Level.WARNING, 
   191                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   192                     methods.size()
   193                 );
   194                 break;
   195             }
   196             LOG.log(Level.INFO, 
   197                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   198                 new Object[]{prev, methods.size()}
   199             );
   200         }
   201         stopServerAndBrwsr(server, brwsr);
   202     }
   203     
   204     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   205         for (;;) {
   206             int ch = is.read();
   207             if (ch == -1) {
   208                 break;
   209             }
   210             if (ch == '$') {
   211                 int cnt = is.read() - '0';
   212                 if (cnt == 'U' - '0') {
   213                     os.write(baseURL.getBytes());
   214                 }
   215                 if (cnt < params.length) {
   216                     os.write(params[cnt].getBytes());
   217                 }
   218             } else {
   219                 os.write(ch);
   220             }
   221         }
   222     }
   223 
   224     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   225         server.start();
   226         NetworkListener listener = server.getListeners().iterator().next();
   227         int port = listener.getPort();
   228         
   229         URI uri = new URI("http://localhost:" + port + page);
   230         LOG.log(Level.INFO, "Showing {0}", uri);
   231 //        try {
   232 //            Desktop.getDesktop().browse(uri);
   233 //            return null;
   234 //        } catch (UnsupportedOperationException ex)
   235         {
   236 //            File dir = File.createTempFile("chrome", ".dir");
   237 //            dir.delete();
   238 //            dir.mkdirs();
   239 //            String[] cmd = { 
   240 //                "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
   241 //            };
   242 //            LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   243 //            final Process process = Runtime.getRuntime().exec(cmd);
   244 //            return new Object[] { process, dir };
   245         }
   246         {
   247             String[] cmd = { 
   248                 "xdg-open", uri.toString()
   249             };
   250             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   251             final Process process = Runtime.getRuntime().exec(cmd);
   252             return new Object[] { process, null };
   253         }
   254     }
   255     
   256     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
   257         Process process = (Process)brwsr[0];
   258         
   259         server.stop();
   260         InputStream stdout = process.getInputStream();
   261         InputStream stderr = process.getErrorStream();
   262         drain("StdOut", stdout);
   263         drain("StdErr", stderr);
   264         process.destroy();
   265         int res = process.waitFor();
   266         LOG.log(Level.INFO, "Exit code: {0}", res);
   267 
   268         deleteTree((File)brwsr[1]);
   269     }
   270     
   271     private static void drain(String name, InputStream is) throws IOException {
   272         int av = is.available();
   273         if (av > 0) {
   274             StringBuilder sb = new StringBuilder();
   275             sb.append("v== ").append(name).append(" ==v\n");
   276             while (av-- > 0) {
   277                 sb.append((char)is.read());
   278             }
   279             sb.append("\n^== ").append(name).append(" ==^");
   280             LOG.log(Level.INFO, sb.toString());
   281         }
   282     }
   283 
   284     private void deleteTree(File file) {
   285         if (file == null) {
   286             return;
   287         }
   288         File[] arr = file.listFiles();
   289         if (arr != null) {
   290             for (File s : arr) {
   291                 deleteTree(s);
   292             }
   293         }
   294         file.delete();
   295     }
   296 
   297     private class Res implements Bck2Brwsr.Resources {
   298         @Override
   299         public InputStream get(String resource) throws IOException {
   300             for (ClassLoader l : loaders) {
   301                 URL u = null;
   302                 Enumeration<URL> en = l.getResources(resource);
   303                 while (en.hasMoreElements()) {
   304                     u = en.nextElement();
   305                 }
   306                 if (u != null) {
   307                     return u.openStream();
   308                 }
   309             }
   310             throw new IOException("Can't find " + resource);
   311         }
   312     }
   313 
   314     private static class Page extends HttpHandler {
   315         private final String resource;
   316         private final String[] args;
   317         private final Res res;
   318         
   319         public Page(Res res, String resource, String... args) {
   320             this.res = res;
   321             this.resource = resource;
   322             this.args = args;
   323         }
   324 
   325         @Override
   326         public void service(Request request, Response response) throws Exception {
   327             String r = resource;
   328             if (r == null) {
   329                 r = request.getHttpHandlerPath();
   330                 if (r.startsWith("/")) {
   331                     r = r.substring(1);
   332                 }
   333             }
   334             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   335                 response.setContentType("text/html");
   336             }
   337             OutputStream os = response.getOutputStream();
   338             try (InputStream is = res.get(r)) {
   339                 copyStream(is, os, request.getRequestURL().toString(), args);
   340             } catch (IOException ex) {
   341                 response.setDetailMessage(ex.getLocalizedMessage());
   342                 response.setError();
   343                 response.setStatus(404);
   344             }
   345         }
   346     }
   347 
   348     private static class VM extends HttpHandler {
   349         private final Res loader;
   350 
   351         public VM(Res loader) {
   352             this.loader = loader;
   353         }
   354 
   355         @Override
   356         public void service(Request request, Response response) throws Exception {
   357             response.setCharacterEncoding("UTF-8");
   358             response.setContentType("text/javascript");
   359             Bck2Brwsr.generate(response.getWriter(), loader);
   360         }
   361     }
   362     private static class VMInit extends HttpHandler {
   363         public VMInit() {
   364         }
   365 
   366         @Override
   367         public void service(Request request, Response response) throws Exception {
   368             response.setCharacterEncoding("UTF-8");
   369             response.setContentType("text/javascript");
   370             response.getWriter().append(
   371                 "function ldCls(res) {\n"
   372                 + "  var request = new XMLHttpRequest();\n"
   373                 + "  request.open('GET', '/classes/' + res, false);\n"
   374                 + "  request.send();\n"
   375                 + "  var arr = eval('(' + request.responseText + ')');\n"
   376                 + "  return arr;\n"
   377                 + "}\n"
   378                 + "var vm = new bck2brwsr(ldCls);\n");
   379         }
   380     }
   381 
   382     private static class Classes extends HttpHandler {
   383         private final Res loader;
   384 
   385         public Classes(Res loader) {
   386             this.loader = loader;
   387         }
   388 
   389         @Override
   390         public void service(Request request, Response response) throws Exception {
   391             String res = request.getHttpHandlerPath();
   392             if (res.startsWith("/")) {
   393                 res = res.substring(1);
   394             }
   395             try (InputStream is = loader.get(res)) {
   396                 response.setContentType("text/javascript");
   397                 Writer w = response.getWriter();
   398                 w.append("[");
   399                 for (int i = 0;; i++) {
   400                     int b = is.read();
   401                     if (b == -1) {
   402                         break;
   403                     }
   404                     if (i > 0) {
   405                         w.append(", ");
   406                     }
   407                     if (i % 20 == 0) {
   408                         w.write("\n");
   409                     }
   410                     if (b > 127) {
   411                         b = b - 256;
   412                     }
   413                     w.append(Integer.toString(b));
   414                 }
   415                 w.append("\n]");
   416             } catch (IOException ex) {
   417                 response.setError();
   418                 response.setDetailMessage(ex.getMessage());
   419             }
   420         }
   421     }
   422 }