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