dew/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Jan 2013 13:18:46 +0100
branchdew
changeset 544 08ffdc3938e7
parent 543 launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java@1adce93fea0f
permissions -rw-r--r--
Moving Development Environment for Web to own project
     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, 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      MethodInvocation addMethod(Class<?> clazz, String method, String html) throws IOException {
    76         loaders.add(clazz.getClassLoader());
    77         MethodInvocation c = new MethodInvocation(clazz.getName(), method, html);
    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                 if (mi.html != null) {
   192                     response.getWriter().write(", html: '");
   193                     response.getWriter().write(encodeJSON(mi.html));
   194                     response.getWriter().write("'");
   195                 }
   196                 response.getWriter().write("}");
   197                 cnt++;
   198             }
   199         }, "/data");
   200 
   201         this.brwsr = launchServerAndBrwsr(server, "/execute");
   202     }
   203     
   204     private static String encodeJSON(String in) {
   205         StringBuilder sb = new StringBuilder();
   206         for (int i = 0; i < in.length(); i++) {
   207             char ch = in.charAt(i);
   208             if (ch < 32 || ch == '\'' || ch == '"') {
   209                 sb.append("\\u");
   210                 String hs = "0000" + Integer.toHexString(ch);
   211                 hs = hs.substring(hs.length() - 4);
   212                 sb.append(hs);
   213             } else {
   214                 sb.append(ch);
   215             }
   216         }
   217         return sb.toString();
   218     }
   219     
   220     @Override
   221     public void shutdown() throws IOException {
   222         methods.offer(END);
   223         for (;;) {
   224             int prev = methods.size();
   225             try {
   226                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   227                     break;
   228                 }
   229             } catch (InterruptedException ex) {
   230                 throw new IOException(ex);
   231             }
   232             if (prev == methods.size()) {
   233                 LOG.log(
   234                     Level.WARNING, 
   235                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   236                     methods.size()
   237                 );
   238                 break;
   239             }
   240             LOG.log(Level.INFO, 
   241                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   242                 new Object[]{prev, methods.size()}
   243             );
   244         }
   245         stopServerAndBrwsr(server, brwsr);
   246     }
   247     
   248     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   249         for (;;) {
   250             int ch = is.read();
   251             if (ch == -1) {
   252                 break;
   253             }
   254             if (ch == '$' && params.length > 0) {
   255                 int cnt = is.read() - '0';
   256                 if (cnt == 'U' - '0') {
   257                     os.write(baseURL.getBytes());
   258                 }
   259                 if (cnt >= 0 && cnt < params.length) {
   260                     os.write(params[cnt].getBytes());
   261                 }
   262             } else {
   263                 os.write(ch);
   264             }
   265         }
   266     }
   267 
   268     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   269         server.start();
   270         NetworkListener listener = server.getListeners().iterator().next();
   271         int port = listener.getPort();
   272         
   273         URI uri = new URI("http://localhost:" + port + page);
   274         LOG.log(Level.INFO, "Showing {0}", uri);
   275         if (cmd == null) {
   276             try {
   277                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   278                     System.getProperty("java.vm.name"),
   279                     System.getProperty("java.vm.vendor"),
   280                     System.getProperty("java.vm.version"),
   281                 });
   282                 java.awt.Desktop.getDesktop().browse(uri);
   283                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   284                 return null;
   285             } catch (UnsupportedOperationException ex) {
   286                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   287                 LOG.log(Level.FINE, null, ex);
   288             }
   289         }
   290         {
   291             String cmdName = cmd == null ? "xdg-open" : cmd;
   292             String[] cmdArr = { 
   293                 cmdName, uri.toString()
   294             };
   295             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   296             final Process process = Runtime.getRuntime().exec(cmdArr);
   297             return new Object[] { process, null };
   298         }
   299     }
   300     
   301     private static String decodeURL(String s) {
   302         for (;;) {
   303             int pos = s.indexOf('%');
   304             if (pos == -1) {
   305                 return s;
   306             }
   307             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   308             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   309         }
   310     }
   311     
   312     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   313         if (brwsr == null) {
   314             return;
   315         }
   316         Process process = (Process)brwsr[0];
   317         
   318         server.stop();
   319         InputStream stdout = process.getInputStream();
   320         InputStream stderr = process.getErrorStream();
   321         drain("StdOut", stdout);
   322         drain("StdErr", stderr);
   323         process.destroy();
   324         int res;
   325         try {
   326             res = process.waitFor();
   327         } catch (InterruptedException ex) {
   328             throw new IOException(ex);
   329         }
   330         LOG.log(Level.INFO, "Exit code: {0}", res);
   331 
   332         deleteTree((File)brwsr[1]);
   333     }
   334     
   335     private static void drain(String name, InputStream is) throws IOException {
   336         int av = is.available();
   337         if (av > 0) {
   338             StringBuilder sb = new StringBuilder();
   339             sb.append("v== ").append(name).append(" ==v\n");
   340             while (av-- > 0) {
   341                 sb.append((char)is.read());
   342             }
   343             sb.append("\n^== ").append(name).append(" ==^");
   344             LOG.log(Level.INFO, sb.toString());
   345         }
   346     }
   347 
   348     private void deleteTree(File file) {
   349         if (file == null) {
   350             return;
   351         }
   352         File[] arr = file.listFiles();
   353         if (arr != null) {
   354             for (File s : arr) {
   355                 deleteTree(s);
   356             }
   357         }
   358         file.delete();
   359     }
   360 
   361     @Override
   362     public void close() throws IOException {
   363         shutdown();
   364     }
   365 
   366     private class Res implements Bck2Brwsr.Resources {
   367         @Override
   368         public InputStream get(String resource) throws IOException {
   369             for (ClassLoader l : loaders) {
   370                 URL u = null;
   371                 Enumeration<URL> en = l.getResources(resource);
   372                 while (en.hasMoreElements()) {
   373                     u = en.nextElement();
   374                 }
   375                 if (u != null) {
   376                     return u.openStream();
   377                 }
   378             }
   379             for (Bck2Brwsr.Resources r : xRes) {
   380                 InputStream is = r.get(resource);
   381                 if (is != null) {
   382                     return is;
   383                 }
   384             }
   385             throw new IOException("Can't find " + resource);
   386         }
   387     }
   388 
   389     private static class Page extends HttpHandler {
   390         private final String resource;
   391         private final String[] args;
   392         private final Res res;
   393         
   394         public Page(Res res, String resource, String... args) {
   395             this.res = res;
   396             this.resource = resource;
   397             this.args = args.length == 0 ? new String[] { "$0" } : args;
   398         }
   399 
   400         @Override
   401         public void service(Request request, Response response) throws Exception {
   402             String r = resource;
   403             if (r == null) {
   404                 r = request.getHttpHandlerPath();
   405                 if (r.startsWith("/")) {
   406                     r = r.substring(1);
   407                 }
   408             }
   409             String[] replace = {};
   410             if (r.endsWith(".html")) {
   411                 response.setContentType("text/html");
   412                 LOG.info("Content type text/html");
   413                 replace = args;
   414             }
   415             if (r.endsWith(".xhtml")) {
   416                 response.setContentType("application/xhtml+xml");
   417                 LOG.info("Content type application/xhtml+xml");
   418                 replace = args;
   419             }
   420             OutputStream os = response.getOutputStream();
   421             try (InputStream is = res.get(r)) {
   422                 copyStream(is, os, request.getRequestURL().toString(), replace);
   423             } catch (IOException ex) {
   424                 response.setDetailMessage(ex.getLocalizedMessage());
   425                 response.setError();
   426                 response.setStatus(404);
   427             }
   428         }
   429     }
   430 
   431     private static class VM extends HttpHandler {
   432         private final Res loader;
   433 
   434         public VM(Res loader) {
   435             this.loader = loader;
   436         }
   437 
   438         @Override
   439         public void service(Request request, Response response) throws Exception {
   440             response.setCharacterEncoding("UTF-8");
   441             response.setContentType("text/javascript");
   442             Bck2Brwsr.generate(response.getWriter(), loader);
   443         }
   444     }
   445     private static class VMInit extends HttpHandler {
   446         public VMInit() {
   447         }
   448 
   449         @Override
   450         public void service(Request request, Response response) throws Exception {
   451             response.setCharacterEncoding("UTF-8");
   452             response.setContentType("text/javascript");
   453             response.getWriter().append(
   454                 "function ldCls(res) {\n"
   455                 + "  var request = new XMLHttpRequest();\n"
   456                 + "  request.open('GET', '/classes/' + res, false);\n"
   457                 + "  request.send();\n"
   458                 + "  var arr = eval('(' + request.responseText + ')');\n"
   459                 + "  return arr;\n"
   460                 + "}\n"
   461                 + "var vm = new bck2brwsr(ldCls);\n");
   462         }
   463     }
   464 
   465     private static class Classes extends HttpHandler {
   466         private final Res loader;
   467 
   468         public Classes(Res loader) {
   469             this.loader = loader;
   470         }
   471 
   472         @Override
   473         public void service(Request request, Response response) throws Exception {
   474             String res = request.getHttpHandlerPath();
   475             if (res.startsWith("/")) {
   476                 res = res.substring(1);
   477             }
   478             try (InputStream is = loader.get(res)) {
   479                 response.setContentType("text/javascript");
   480                 Writer w = response.getWriter();
   481                 w.append("[");
   482                 for (int i = 0;; i++) {
   483                     int b = is.read();
   484                     if (b == -1) {
   485                         break;
   486                     }
   487                     if (i > 0) {
   488                         w.append(", ");
   489                     }
   490                     if (i % 20 == 0) {
   491                         w.write("\n");
   492                     }
   493                     if (b > 127) {
   494                         b = b - 256;
   495                     }
   496                     w.append(Integer.toString(b));
   497                 }
   498                 w.append("\n]");
   499             } catch (IOException ex) {
   500                 response.setError();
   501                 response.setDetailMessage(ex.getMessage());
   502             }
   503         }
   504     }
   505 }