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