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