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