launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 15 Feb 2013 19:28:31 +0100
branchemul
changeset 742 3035beed09a1
parent 741 1343f52164f3
child 745 51ce6a73fcb2
permissions -rw-r--r--
Using simple name should allow us to support multiple pages in the future
     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.launcher.InvocationContext.Resource;
    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 InvocationContext END = new InvocationContext(null, null, null);
    60     private final Set<ClassLoader> loaders = new LinkedHashSet<>();
    61     private final BlockingQueue<InvocationContext> 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     InvocationContext runMethod(InvocationContext c) throws IOException {
    75         loaders.add(c.clazz.getClassLoader());
    76         methods.add(c);
    77         try {
    78             c.await(timeOut);
    79         } catch (InterruptedException ex) {
    80             throw new IOException(ex);
    81         }
    82         return c;
    83     }
    84     
    85     public void setTimeout(long ms) {
    86         timeOut = ms;
    87     }
    88     
    89     public void addClassLoader(ClassLoader url) {
    90         this.loaders.add(url);
    91     }
    92 
    93     public void showURL(String startpage) throws IOException {
    94         if (!startpage.startsWith("/")) {
    95             startpage = "/" + startpage;
    96         }
    97         HttpServer s = initServer(".", true);
    98         int last = startpage.lastIndexOf('/');
    99         String simpleName = startpage.substring(last);
   100         s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), simpleName);
   101         s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
   102         try {
   103             launchServerAndBrwsr(s, simpleName);
   104         } catch (URISyntaxException | InterruptedException ex) {
   105             throw new IOException(ex);
   106         }
   107     }
   108 
   109     void showDirectory(File dir, String startpage) throws IOException {
   110         if (!startpage.startsWith("/")) {
   111             startpage = "/" + startpage;
   112         }
   113         HttpServer s = initServer(dir.getPath(), false);
   114         try {
   115             launchServerAndBrwsr(s, startpage);
   116         } catch (URISyntaxException | InterruptedException ex) {
   117             throw new IOException(ex);
   118         }
   119     }
   120 
   121     @Override
   122     public void initialize() throws IOException {
   123         try {
   124             executeInBrowser();
   125         } catch (InterruptedException ex) {
   126             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   127             iio.initCause(ex);
   128             throw iio;
   129         } catch (Exception ex) {
   130             if (ex instanceof IOException) {
   131                 throw (IOException)ex;
   132             }
   133             if (ex instanceof RuntimeException) {
   134                 throw (RuntimeException)ex;
   135             }
   136             throw new IOException(ex);
   137         }
   138     }
   139     
   140     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   141         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   142 
   143         final ServerConfiguration conf = s.getServerConfiguration();
   144         if (addClasses) {
   145             conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   146             conf.addHttpHandler(new Classes(resources), "/classes/");
   147         }
   148         return s;
   149     }
   150     
   151     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   152         wait = new CountDownLatch(1);
   153         server = initServer(".", true);
   154         final ServerConfiguration conf = server.getServerConfiguration();
   155         
   156         class DynamicResourceHandler extends HttpHandler {
   157             private final InvocationContext ic;
   158             public DynamicResourceHandler(InvocationContext ic) {
   159                 if (ic == null || ic.resources.isEmpty()) {
   160                     throw new NullPointerException();
   161                 }
   162                 this.ic = ic;
   163                 for (Resource r : ic.resources) {
   164                     conf.addHttpHandler(this, r.httpPath);
   165                 }
   166             }
   167 
   168             public void close() {
   169                 conf.removeHttpHandler(this);
   170             }
   171             
   172             @Override
   173             public void service(Request request, Response response) throws Exception {
   174                 for (Resource r : ic.resources) {
   175                     if (r.httpPath.equals(request.getRequestURI())) {
   176                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   177                         response.setContentType(r.httpType);
   178                         copyStream(r.httpContent, response.getOutputStream(), null);
   179                     }
   180                 }
   181             }
   182         }
   183         
   184         conf.addHttpHandler(new Page(resources, 
   185             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   186         ), "/execute");
   187         
   188         conf.addHttpHandler(new HttpHandler() {
   189             int cnt;
   190             List<InvocationContext> cases = new ArrayList<>();
   191             DynamicResourceHandler prev;
   192             @Override
   193             public void service(Request request, Response response) throws Exception {
   194                 String id = request.getParameter("request");
   195                 String value = request.getParameter("result");
   196                 
   197                 
   198                 InvocationContext mi = null;
   199                 int caseNmbr = -1;
   200                 
   201                 if (id != null && value != null) {
   202                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   203                     value = decodeURL(value);
   204                     int indx = Integer.parseInt(id);
   205                     cases.get(indx).result(value, null);
   206                     if (++indx < cases.size()) {
   207                         mi = cases.get(indx);
   208                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   209                         caseNmbr = indx;
   210                     }
   211                 } else {
   212                     if (!cases.isEmpty()) {
   213                         LOG.info("Re-executing test cases");
   214                         mi = cases.get(0);
   215                         caseNmbr = 0;
   216                     }
   217                 }
   218                 
   219                 if (prev != null) {
   220                     prev.close();
   221                     prev = null;
   222                 }
   223                 
   224                 if (mi == null) {
   225                     mi = methods.take();
   226                     caseNmbr = cnt++;
   227                 }
   228                 if (mi == END) {
   229                     response.getWriter().write("");
   230                     wait.countDown();
   231                     cnt = 0;
   232                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   233                     return;
   234                 }
   235                 
   236                 if (!mi.resources.isEmpty()) {
   237                     prev = new DynamicResourceHandler(mi);
   238                 }
   239                 
   240                 cases.add(mi);
   241                 final String cn = mi.clazz.getName();
   242                 final String mn = mi.methodName;
   243                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   244                 response.getWriter().write("{"
   245                     + "className: '" + cn + "', "
   246                     + "methodName: '" + mn + "', "
   247                     + "request: " + caseNmbr
   248                 );
   249                 if (mi.html != null) {
   250                     response.getWriter().write(", html: '");
   251                     response.getWriter().write(encodeJSON(mi.html));
   252                     response.getWriter().write("'");
   253                 }
   254                 response.getWriter().write("}");
   255             }
   256         }, "/data");
   257 
   258         this.brwsr = launchServerAndBrwsr(server, "/execute");
   259     }
   260     
   261     private static String encodeJSON(String in) {
   262         StringBuilder sb = new StringBuilder();
   263         for (int i = 0; i < in.length(); i++) {
   264             char ch = in.charAt(i);
   265             if (ch < 32 || ch == '\'' || ch == '"') {
   266                 sb.append("\\u");
   267                 String hs = "0000" + Integer.toHexString(ch);
   268                 hs = hs.substring(hs.length() - 4);
   269                 sb.append(hs);
   270             } else {
   271                 sb.append(ch);
   272             }
   273         }
   274         return sb.toString();
   275     }
   276     
   277     @Override
   278     public void shutdown() throws IOException {
   279         methods.offer(END);
   280         for (;;) {
   281             int prev = methods.size();
   282             try {
   283                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   284                     break;
   285                 }
   286             } catch (InterruptedException ex) {
   287                 throw new IOException(ex);
   288             }
   289             if (prev == methods.size()) {
   290                 LOG.log(
   291                     Level.WARNING, 
   292                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   293                     methods.size()
   294                 );
   295                 break;
   296             }
   297             LOG.log(Level.INFO, 
   298                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   299                 new Object[]{prev, methods.size()}
   300             );
   301         }
   302         stopServerAndBrwsr(server, brwsr);
   303     }
   304     
   305     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   306         for (;;) {
   307             int ch = is.read();
   308             if (ch == -1) {
   309                 break;
   310             }
   311             if (ch == '$' && params.length > 0) {
   312                 int cnt = is.read() - '0';
   313                 if (cnt == 'U' - '0') {
   314                     os.write(baseURL.getBytes());
   315                 }
   316                 if (cnt >= 0 && cnt < params.length) {
   317                     os.write(params[cnt].getBytes());
   318                 }
   319             } else {
   320                 os.write(ch);
   321             }
   322         }
   323     }
   324 
   325     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   326         server.start();
   327         NetworkListener listener = server.getListeners().iterator().next();
   328         int port = listener.getPort();
   329         
   330         URI uri = new URI("http://localhost:" + port + page);
   331         LOG.log(Level.INFO, "Showing {0}", uri);
   332         if (cmd == null) {
   333             try {
   334                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   335                     System.getProperty("java.vm.name"),
   336                     System.getProperty("java.vm.vendor"),
   337                     System.getProperty("java.vm.version"),
   338                 });
   339                 java.awt.Desktop.getDesktop().browse(uri);
   340                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   341                 return null;
   342             } catch (UnsupportedOperationException ex) {
   343                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   344                 LOG.log(Level.FINE, null, ex);
   345             }
   346         }
   347         {
   348             String cmdName = cmd == null ? "xdg-open" : cmd;
   349             String[] cmdArr = { 
   350                 cmdName, uri.toString()
   351             };
   352             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   353             final Process process = Runtime.getRuntime().exec(cmdArr);
   354             return new Object[] { process, null };
   355         }
   356     }
   357     
   358     private static String decodeURL(String s) {
   359         for (;;) {
   360             int pos = s.indexOf('%');
   361             if (pos == -1) {
   362                 return s;
   363             }
   364             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   365             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   366         }
   367     }
   368     
   369     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   370         if (brwsr == null) {
   371             return;
   372         }
   373         Process process = (Process)brwsr[0];
   374         
   375         server.stop();
   376         InputStream stdout = process.getInputStream();
   377         InputStream stderr = process.getErrorStream();
   378         drain("StdOut", stdout);
   379         drain("StdErr", stderr);
   380         process.destroy();
   381         int res;
   382         try {
   383             res = process.waitFor();
   384         } catch (InterruptedException ex) {
   385             throw new IOException(ex);
   386         }
   387         LOG.log(Level.INFO, "Exit code: {0}", res);
   388 
   389         deleteTree((File)brwsr[1]);
   390     }
   391     
   392     private static void drain(String name, InputStream is) throws IOException {
   393         int av = is.available();
   394         if (av > 0) {
   395             StringBuilder sb = new StringBuilder();
   396             sb.append("v== ").append(name).append(" ==v\n");
   397             while (av-- > 0) {
   398                 sb.append((char)is.read());
   399             }
   400             sb.append("\n^== ").append(name).append(" ==^");
   401             LOG.log(Level.INFO, sb.toString());
   402         }
   403     }
   404 
   405     private void deleteTree(File file) {
   406         if (file == null) {
   407             return;
   408         }
   409         File[] arr = file.listFiles();
   410         if (arr != null) {
   411             for (File s : arr) {
   412                 deleteTree(s);
   413             }
   414         }
   415         file.delete();
   416     }
   417 
   418     @Override
   419     public void close() throws IOException {
   420         shutdown();
   421     }
   422 
   423     private class Res implements Bck2Brwsr.Resources {
   424         @Override
   425         public InputStream get(String resource) throws IOException {
   426             for (ClassLoader l : loaders) {
   427                 URL u = null;
   428                 Enumeration<URL> en = l.getResources(resource);
   429                 while (en.hasMoreElements()) {
   430                     u = en.nextElement();
   431                 }
   432                 if (u != null) {
   433                     return u.openStream();
   434                 }
   435             }
   436             throw new IOException("Can't find " + resource);
   437         }
   438     }
   439 
   440     private static class Page extends HttpHandler {
   441         private final String resource;
   442         private final String[] args;
   443         private final Res res;
   444         
   445         public Page(Res res, String resource, String... args) {
   446             this.res = res;
   447             this.resource = resource;
   448             this.args = args.length == 0 ? new String[] { "$0" } : args;
   449         }
   450 
   451         @Override
   452         public void service(Request request, Response response) throws Exception {
   453             String r = resource;
   454             if (r == null) {
   455                 r = request.getHttpHandlerPath();
   456             }
   457             if (r.startsWith("/")) {
   458                 r = r.substring(1);
   459             }
   460             String[] replace = {};
   461             if (r.endsWith(".html")) {
   462                 response.setContentType("text/html");
   463                 LOG.info("Content type text/html");
   464                 replace = args;
   465             }
   466             if (r.endsWith(".xhtml")) {
   467                 response.setContentType("application/xhtml+xml");
   468                 LOG.info("Content type application/xhtml+xml");
   469                 replace = args;
   470             }
   471             OutputStream os = response.getOutputStream();
   472             try (InputStream is = res.get(r)) {
   473                 copyStream(is, os, request.getRequestURL().toString(), replace);
   474             } catch (IOException ex) {
   475                 response.setDetailMessage(ex.getLocalizedMessage());
   476                 response.setError();
   477                 response.setStatus(404);
   478             }
   479         }
   480     }
   481 
   482     private static class VM extends HttpHandler {
   483         private final String bck2brwsr;
   484 
   485         public VM(Res loader) throws IOException {
   486             StringBuilder sb = new StringBuilder();
   487             Bck2Brwsr.generate(sb, loader);
   488             sb.append(
   489                   "(function WrapperVM(global) {"
   490                 + "  function ldCls(res) {\n"
   491                 + "    var request = new XMLHttpRequest();\n"
   492                 + "    request.open('GET', '/classes/' + res, false);\n"
   493                 + "    request.send();\n"
   494                 + "    var arr = eval('(' + request.responseText + ')');\n"
   495                 + "    return arr;\n"
   496                 + "  }\n"
   497                 + "  var prevvm = global.bck2brwsr;\n"
   498                 + "  global.bck2brwsr = function() {\n"
   499                 + "    return prevvm(ldCls);\n"
   500                 + "  };\n"
   501                 + "})(this);\n"
   502             );
   503             this.bck2brwsr = sb.toString();
   504         }
   505 
   506         @Override
   507         public void service(Request request, Response response) throws Exception {
   508             response.setCharacterEncoding("UTF-8");
   509             response.setContentType("text/javascript");
   510             response.getWriter().write(bck2brwsr);
   511         }
   512     }
   513 
   514     private static class Classes extends HttpHandler {
   515         private final Res loader;
   516 
   517         public Classes(Res loader) {
   518             this.loader = loader;
   519         }
   520 
   521         @Override
   522         public void service(Request request, Response response) throws Exception {
   523             String res = request.getHttpHandlerPath();
   524             if (res.startsWith("/")) {
   525                 res = res.substring(1);
   526             }
   527             try (InputStream is = loader.get(res)) {
   528                 response.setContentType("text/javascript");
   529                 Writer w = response.getWriter();
   530                 w.append("[");
   531                 for (int i = 0;; i++) {
   532                     int b = is.read();
   533                     if (b == -1) {
   534                         break;
   535                     }
   536                     if (i > 0) {
   537                         w.append(", ");
   538                     }
   539                     if (i % 20 == 0) {
   540                         w.write("\n");
   541                     }
   542                     if (b > 127) {
   543                         b = b - 256;
   544                     }
   545                     w.append(Integer.toString(b));
   546                 }
   547                 w.append("\n]");
   548             } catch (IOException ex) {
   549                 response.setError();
   550                 response.setDetailMessage(ex.getMessage());
   551             }
   552         }
   553     }
   554 }