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