launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 25 Dec 2012 14:07:02 +0100
changeset 381 70d15cf323ba
parent 372 3485327d3080
child 382 57fc3a0563c9
permissions -rw-r--r--
Can execute the matrix multiplication test using VMTest
     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 = decodeURL(value);
   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 static String decodeURL(String s) {
   257         for (;;) {
   258             int pos = s.indexOf('%');
   259             if (pos == -1) {
   260                 return s;
   261             }
   262             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   263             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   264         }
   265     }
   266     
   267     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
   268         Process process = (Process)brwsr[0];
   269         
   270         server.stop();
   271         InputStream stdout = process.getInputStream();
   272         InputStream stderr = process.getErrorStream();
   273         drain("StdOut", stdout);
   274         drain("StdErr", stderr);
   275         process.destroy();
   276         int res = process.waitFor();
   277         LOG.log(Level.INFO, "Exit code: {0}", res);
   278 
   279         deleteTree((File)brwsr[1]);
   280     }
   281     
   282     private static void drain(String name, InputStream is) throws IOException {
   283         int av = is.available();
   284         if (av > 0) {
   285             StringBuilder sb = new StringBuilder();
   286             sb.append("v== ").append(name).append(" ==v\n");
   287             while (av-- > 0) {
   288                 sb.append((char)is.read());
   289             }
   290             sb.append("\n^== ").append(name).append(" ==^");
   291             LOG.log(Level.INFO, sb.toString());
   292         }
   293     }
   294 
   295     private void deleteTree(File file) {
   296         if (file == null) {
   297             return;
   298         }
   299         File[] arr = file.listFiles();
   300         if (arr != null) {
   301             for (File s : arr) {
   302                 deleteTree(s);
   303             }
   304         }
   305         file.delete();
   306     }
   307 
   308     private class Res implements Bck2Brwsr.Resources {
   309         @Override
   310         public InputStream get(String resource) throws IOException {
   311             for (ClassLoader l : loaders) {
   312                 URL u = null;
   313                 Enumeration<URL> en = l.getResources(resource);
   314                 while (en.hasMoreElements()) {
   315                     u = en.nextElement();
   316                 }
   317                 if (u != null) {
   318                     return u.openStream();
   319                 }
   320             }
   321             throw new IOException("Can't find " + resource);
   322         }
   323     }
   324 
   325     private static class Page extends HttpHandler {
   326         private final String resource;
   327         private final String[] args;
   328         private final Res res;
   329         
   330         public Page(Res res, String resource, String... args) {
   331             this.res = res;
   332             this.resource = resource;
   333             this.args = args;
   334         }
   335 
   336         @Override
   337         public void service(Request request, Response response) throws Exception {
   338             String r = resource;
   339             if (r == null) {
   340                 r = request.getHttpHandlerPath();
   341                 if (r.startsWith("/")) {
   342                     r = r.substring(1);
   343                 }
   344             }
   345             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   346                 response.setContentType("text/html");
   347             }
   348             OutputStream os = response.getOutputStream();
   349             try (InputStream is = res.get(r)) {
   350                 copyStream(is, os, request.getRequestURL().toString(), args);
   351             } catch (IOException ex) {
   352                 response.setDetailMessage(ex.getLocalizedMessage());
   353                 response.setError();
   354                 response.setStatus(404);
   355             }
   356         }
   357     }
   358 
   359     private static class VM extends HttpHandler {
   360         private final Res loader;
   361 
   362         public VM(Res loader) {
   363             this.loader = loader;
   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             Bck2Brwsr.generate(response.getWriter(), loader);
   371         }
   372     }
   373     private static class VMInit extends HttpHandler {
   374         public VMInit() {
   375         }
   376 
   377         @Override
   378         public void service(Request request, Response response) throws Exception {
   379             response.setCharacterEncoding("UTF-8");
   380             response.setContentType("text/javascript");
   381             response.getWriter().append(
   382                 "function ldCls(res) {\n"
   383                 + "  var request = new XMLHttpRequest();\n"
   384                 + "  request.open('GET', '/classes/' + res, false);\n"
   385                 + "  request.send();\n"
   386                 + "  var arr = eval('(' + request.responseText + ')');\n"
   387                 + "  return arr;\n"
   388                 + "}\n"
   389                 + "var vm = new bck2brwsr(ldCls);\n");
   390         }
   391     }
   392 
   393     private static class Classes extends HttpHandler {
   394         private final Res loader;
   395 
   396         public Classes(Res loader) {
   397             this.loader = loader;
   398         }
   399 
   400         @Override
   401         public void service(Request request, Response response) throws Exception {
   402             String res = request.getHttpHandlerPath();
   403             if (res.startsWith("/")) {
   404                 res = res.substring(1);
   405             }
   406             try (InputStream is = loader.get(res)) {
   407                 response.setContentType("text/javascript");
   408                 Writer w = response.getWriter();
   409                 w.append("[");
   410                 for (int i = 0;; i++) {
   411                     int b = is.read();
   412                     if (b == -1) {
   413                         break;
   414                     }
   415                     if (i > 0) {
   416                         w.append(", ");
   417                     }
   418                     if (i % 20 == 0) {
   419                         w.write("\n");
   420                     }
   421                     if (b > 127) {
   422                         b = b - 256;
   423                     }
   424                     w.append(Integer.toString(b));
   425                 }
   426                 w.append("\n]");
   427             } catch (IOException ex) {
   428                 response.setError();
   429                 response.setDetailMessage(ex.getMessage());
   430             }
   431         }
   432     }
   433 }