launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 28 May 2013 21:49:38 +0200
changeset 1165 06e7a74c72cf
parent 1098 fcf1d05b0d39
child 1186 265edcee24ed
permissions -rw-r--r--
Make sure the launchers run on JDK6
     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.Reader;
    27 import java.io.UnsupportedEncodingException;
    28 import java.io.Writer;
    29 import java.net.URI;
    30 import java.net.URISyntaxException;
    31 import java.net.URL;
    32 import java.util.ArrayList;
    33 import java.util.Arrays;
    34 import java.util.Enumeration;
    35 import java.util.LinkedHashSet;
    36 import java.util.List;
    37 import java.util.Set;
    38 import java.util.concurrent.BlockingQueue;
    39 import java.util.concurrent.Callable;
    40 import java.util.concurrent.CountDownLatch;
    41 import java.util.concurrent.LinkedBlockingQueue;
    42 import java.util.concurrent.TimeUnit;
    43 import java.util.logging.Level;
    44 import java.util.logging.Logger;
    45 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
    46 import org.glassfish.grizzly.PortRange;
    47 import org.glassfish.grizzly.http.server.HttpHandler;
    48 import org.glassfish.grizzly.http.server.HttpServer;
    49 import org.glassfish.grizzly.http.server.NetworkListener;
    50 import org.glassfish.grizzly.http.server.Request;
    51 import org.glassfish.grizzly.http.server.Response;
    52 import org.glassfish.grizzly.http.server.ServerConfiguration;
    53 import org.glassfish.grizzly.http.util.HttpStatus;
    54 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
    55 
    56 /**
    57  * Lightweight server to launch Bck2Brwsr applications and tests.
    58  * Supports execution in native browser as well as Java's internal 
    59  * execution engine.
    60  */
    61 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
    62     static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
    63     private static final InvocationContext END = new InvocationContext(null, null, null);
    64     private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
    65     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
    66     private long timeOut;
    67     private final Res resources = new Res();
    68     private final String cmd;
    69     private Object[] brwsr;
    70     private HttpServer server;
    71     private CountDownLatch wait;
    72     
    73     public BaseHTTPLauncher(String cmd) {
    74         this.cmd = cmd;
    75         addClassLoader(BaseHTTPLauncher.class.getClassLoader());
    76         setTimeout(180000);
    77     }
    78     
    79     @Override
    80     InvocationContext runMethod(InvocationContext c) throws IOException {
    81         loaders.add(c.clazz.getClassLoader());
    82         methods.add(c);
    83         try {
    84             c.await(timeOut);
    85         } catch (InterruptedException ex) {
    86             throw new IOException(ex);
    87         }
    88         return c;
    89     }
    90     
    91     public void setTimeout(long ms) {
    92         timeOut = ms;
    93     }
    94     
    95     public void addClassLoader(ClassLoader url) {
    96         this.loaders.add(url);
    97     }
    98     
    99     ClassLoader[] loaders() {
   100         return loaders.toArray(new ClassLoader[loaders.size()]);
   101     }
   102 
   103     public void showURL(String startpage) throws IOException {
   104         if (!startpage.startsWith("/")) {
   105             startpage = "/" + startpage;
   106         }
   107         HttpServer s = initServer(".", true);
   108         int last = startpage.lastIndexOf('/');
   109         String prefix = startpage.substring(0, last);
   110         String simpleName = startpage.substring(last);
   111         s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
   112         server = s;
   113         try {
   114             launchServerAndBrwsr(s, simpleName);
   115         } catch (Exception ex) {
   116             throw new IOException(ex);
   117         }
   118     }
   119 
   120     void showDirectory(File dir, String startpage) throws IOException {
   121         if (!startpage.startsWith("/")) {
   122             startpage = "/" + startpage;
   123         }
   124         HttpServer s = initServer(dir.getPath(), false);
   125         try {
   126             launchServerAndBrwsr(s, startpage);
   127         } catch (Exception ex) {
   128             throw new IOException(ex);
   129         }
   130     }
   131 
   132     @Override
   133     public void initialize() throws IOException {
   134         try {
   135             executeInBrowser();
   136         } catch (InterruptedException ex) {
   137             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   138             iio.initCause(ex);
   139             throw iio;
   140         } catch (Exception ex) {
   141             if (ex instanceof IOException) {
   142                 throw (IOException)ex;
   143             }
   144             if (ex instanceof RuntimeException) {
   145                 throw (RuntimeException)ex;
   146             }
   147             throw new IOException(ex);
   148         }
   149     }
   150     
   151     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   152         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   153 
   154         ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
   155             setPoolName("Fx/Bck2 Brwsr").
   156             setCorePoolSize(1).
   157             setMaxPoolSize(5);
   158         ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
   159             setPoolName("Kernel Fx/Bck2").
   160             setCorePoolSize(1).
   161             setMaxPoolSize(3);
   162         for (NetworkListener nl : s.getListeners()) {
   163             nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
   164             nl.getTransport().setKernelThreadPoolConfig(oneKernel);
   165         }
   166         
   167         final ServerConfiguration conf = s.getServerConfiguration();
   168         if (addClasses) {
   169             conf.addHttpHandler(new VM(), "/bck2brwsr.js");
   170             conf.addHttpHandler(new Classes(resources), "/classes/");
   171         }
   172         return s;
   173     }
   174     
   175     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   176         wait = new CountDownLatch(1);
   177         server = initServer(".", true);
   178         final ServerConfiguration conf = server.getServerConfiguration();
   179         
   180         class DynamicResourceHandler extends HttpHandler {
   181             private final InvocationContext ic;
   182             public DynamicResourceHandler(InvocationContext ic) {
   183                 if (ic == null || ic.resources.isEmpty()) {
   184                     throw new NullPointerException();
   185                 }
   186                 this.ic = ic;
   187                 for (Resource r : ic.resources) {
   188                     conf.addHttpHandler(this, r.httpPath);
   189                 }
   190             }
   191 
   192             public void close() {
   193                 conf.removeHttpHandler(this);
   194             }
   195             
   196             @Override
   197             public void service(Request request, Response response) throws Exception {
   198                 for (Resource r : ic.resources) {
   199                     if (r.httpPath.equals(request.getRequestURI())) {
   200                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   201                         response.setContentType(r.httpType);
   202                         r.httpContent.reset();
   203                         String[] params = null;
   204                         if (r.parameters.length != 0) {
   205                             params = new String[r.parameters.length];
   206                             for (int i = 0; i < r.parameters.length; i++) {
   207                                 params[i] = request.getParameter(r.parameters[i]);
   208                                 if (params[i] == null) {
   209                                     if ("http.method".equals(r.parameters[i])) {
   210                                         params[i] = request.getMethod().toString();
   211                                     } else if ("http.requestBody".equals(r.parameters[i])) {
   212                                         Reader rdr = request.getReader();
   213                                         StringBuilder sb = new StringBuilder();
   214                                         for (;;) {
   215                                             int ch = rdr.read();
   216                                             if (ch == -1) {
   217                                                 break;
   218                                             }
   219                                             sb.append((char)ch);
   220                                         }
   221                                         params[i] = sb.toString();
   222                                     }
   223                                 }
   224                                 if (params[i] == null) {
   225                                     params[i] = "null";
   226                                 }
   227                             }
   228                         }
   229                         
   230                         copyStream(r.httpContent, response.getOutputStream(), null, params);
   231                     }
   232                 }
   233             }
   234         }
   235         
   236         conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
   237         
   238         conf.addHttpHandler(new HttpHandler() {
   239             int cnt;
   240             List<InvocationContext> cases = new ArrayList<InvocationContext>();
   241             DynamicResourceHandler prev;
   242             @Override
   243             public void service(Request request, Response response) throws Exception {
   244                 String id = request.getParameter("request");
   245                 String value = request.getParameter("result");
   246                 if (value != null && value.indexOf((char)0xC5) != -1) {
   247                     value = toUTF8(value);
   248                 }
   249                 
   250                 
   251                 InvocationContext mi = null;
   252                 int caseNmbr = -1;
   253                 
   254                 if (id != null && value != null) {
   255                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   256                     value = decodeURL(value);
   257                     int indx = Integer.parseInt(id);
   258                     cases.get(indx).result(value, null);
   259                     if (++indx < cases.size()) {
   260                         mi = cases.get(indx);
   261                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   262                         caseNmbr = indx;
   263                     }
   264                 } else {
   265                     if (!cases.isEmpty()) {
   266                         LOG.info("Re-executing test cases");
   267                         mi = cases.get(0);
   268                         caseNmbr = 0;
   269                     }
   270                 }
   271                 
   272                 if (prev != null) {
   273                     prev.close();
   274                     prev = null;
   275                 }
   276                 
   277                 if (mi == null) {
   278                     mi = methods.take();
   279                     caseNmbr = cnt++;
   280                 }
   281                 if (mi == END) {
   282                     response.getWriter().write("");
   283                     wait.countDown();
   284                     cnt = 0;
   285                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   286                     return;
   287                 }
   288                 
   289                 if (!mi.resources.isEmpty()) {
   290                     prev = new DynamicResourceHandler(mi);
   291                 }
   292                 
   293                 cases.add(mi);
   294                 final String cn = mi.clazz.getName();
   295                 final String mn = mi.methodName;
   296                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   297                 response.getWriter().write("{"
   298                     + "className: '" + cn + "', "
   299                     + "methodName: '" + mn + "', "
   300                     + "request: " + caseNmbr
   301                 );
   302                 if (mi.html != null) {
   303                     response.getWriter().write(", html: '");
   304                     response.getWriter().write(encodeJSON(mi.html));
   305                     response.getWriter().write("'");
   306                 }
   307                 response.getWriter().write("}");
   308             }
   309         }, "/data");
   310 
   311         this.brwsr = launchServerAndBrwsr(server, "/execute");
   312     }
   313     
   314     private static String encodeJSON(String in) {
   315         StringBuilder sb = new StringBuilder();
   316         for (int i = 0; i < in.length(); i++) {
   317             char ch = in.charAt(i);
   318             if (ch < 32 || ch == '\'' || ch == '"') {
   319                 sb.append("\\u");
   320                 String hs = "0000" + Integer.toHexString(ch);
   321                 hs = hs.substring(hs.length() - 4);
   322                 sb.append(hs);
   323             } else {
   324                 sb.append(ch);
   325             }
   326         }
   327         return sb.toString();
   328     }
   329     
   330     @Override
   331     public void shutdown() throws IOException {
   332         methods.offer(END);
   333         for (;;) {
   334             int prev = methods.size();
   335             try {
   336                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   337                     break;
   338                 }
   339             } catch (InterruptedException ex) {
   340                 throw new IOException(ex);
   341             }
   342             if (prev == methods.size()) {
   343                 LOG.log(
   344                     Level.WARNING, 
   345                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   346                     methods.size()
   347                 );
   348                 break;
   349             }
   350             LOG.log(Level.INFO, 
   351                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   352                 new Object[]{prev, methods.size()}
   353             );
   354         }
   355         stopServerAndBrwsr(server, brwsr);
   356     }
   357     
   358     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   359         for (;;) {
   360             int ch = is.read();
   361             if (ch == -1) {
   362                 break;
   363             }
   364             if (ch == '$' && params.length > 0) {
   365                 int cnt = is.read() - '0';
   366                 if (baseURL != null && cnt == 'U' - '0') {
   367                     os.write(baseURL.getBytes("UTF-8"));
   368                 } else {
   369                     if (cnt >= 0 && cnt < params.length) {
   370                         os.write(params[cnt].getBytes("UTF-8"));
   371                     } else {
   372                         os.write('$');
   373                         os.write(cnt + '0');
   374                     }
   375                 }
   376             } else {
   377                 os.write(ch);
   378             }
   379         }
   380     }
   381 
   382     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   383         server.start();
   384         NetworkListener listener = server.getListeners().iterator().next();
   385         int port = listener.getPort();
   386         
   387         URI uri = new URI("http://localhost:" + port + page);
   388         return showBrwsr(uri);
   389     }
   390     private static String toUTF8(String value) throws UnsupportedEncodingException {
   391         byte[] arr = new byte[value.length()];
   392         for (int i = 0; i < arr.length; i++) {
   393             arr[i] = (byte)value.charAt(i);
   394         }
   395         return new String(arr, "UTF-8");
   396     }
   397     
   398     private static String decodeURL(String s) {
   399         for (;;) {
   400             int pos = s.indexOf('%');
   401             if (pos == -1) {
   402                 return s;
   403             }
   404             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   405             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   406         }
   407     }
   408     
   409     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   410         if (brwsr == null) {
   411             return;
   412         }
   413         Process process = (Process)brwsr[0];
   414         
   415         server.stop();
   416         InputStream stdout = process.getInputStream();
   417         InputStream stderr = process.getErrorStream();
   418         drain("StdOut", stdout);
   419         drain("StdErr", stderr);
   420         process.destroy();
   421         int res;
   422         try {
   423             res = process.waitFor();
   424         } catch (InterruptedException ex) {
   425             throw new IOException(ex);
   426         }
   427         LOG.log(Level.INFO, "Exit code: {0}", res);
   428 
   429         deleteTree((File)brwsr[1]);
   430     }
   431     
   432     private static void drain(String name, InputStream is) throws IOException {
   433         int av = is.available();
   434         if (av > 0) {
   435             StringBuilder sb = new StringBuilder();
   436             sb.append("v== ").append(name).append(" ==v\n");
   437             while (av-- > 0) {
   438                 sb.append((char)is.read());
   439             }
   440             sb.append("\n^== ").append(name).append(" ==^");
   441             LOG.log(Level.INFO, sb.toString());
   442         }
   443     }
   444 
   445     private void deleteTree(File file) {
   446         if (file == null) {
   447             return;
   448         }
   449         File[] arr = file.listFiles();
   450         if (arr != null) {
   451             for (File s : arr) {
   452                 deleteTree(s);
   453             }
   454         }
   455         file.delete();
   456     }
   457 
   458     @Override
   459     public HttpServer call() throws Exception {
   460         return server;
   461     }
   462     
   463     @Override
   464     public void close() throws IOException {
   465         shutdown();
   466     }
   467 
   468     protected Object[] showBrwsr(URI uri) throws IOException {
   469         LOG.log(Level.INFO, "Showing {0}", uri);
   470         if (cmd == null) {
   471             try {
   472                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   473                     System.getProperty("java.vm.name"),
   474                     System.getProperty("java.vm.vendor"),
   475                     System.getProperty("java.vm.version"),
   476                 });
   477                 java.awt.Desktop.getDesktop().browse(uri);
   478                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   479                 return null;
   480             } catch (UnsupportedOperationException ex) {
   481                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   482                 LOG.log(Level.FINE, null, ex);
   483             }
   484         }
   485         {
   486             String cmdName = cmd == null ? "xdg-open" : cmd;
   487             String[] cmdArr = { 
   488                 cmdName, uri.toString()
   489             };
   490             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   491             final Process process = Runtime.getRuntime().exec(cmdArr);
   492             return new Object[] { process, null };
   493         }
   494     }
   495 
   496     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   497     abstract String harnessResource();
   498 
   499     class Res {
   500         public InputStream get(String resource) throws IOException {
   501             URL u = null;
   502             for (ClassLoader l : loaders) {
   503                 Enumeration<URL> en = l.getResources(resource);
   504                 while (en.hasMoreElements()) {
   505                     u = en.nextElement();
   506                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   507                         return u.openStream();
   508                     }
   509                 }
   510             }
   511             if (u != null) {
   512                 if (u.toExternalForm().contains("rt.jar")) {
   513                     LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
   514                 }
   515                 return u.openStream();
   516             }
   517             throw new IOException("Can't find " + resource);
   518         }
   519     }
   520 
   521     private static class Page extends HttpHandler {
   522         final String resource;
   523         private final String[] args;
   524         private final Res res;
   525         
   526         public Page(Res res, String resource, String... args) {
   527             this.res = res;
   528             this.resource = resource;
   529             this.args = args.length == 0 ? new String[] { "$0" } : args;
   530         }
   531 
   532         @Override
   533         public void service(Request request, Response response) throws Exception {
   534             String r = computePage(request);
   535             if (r.startsWith("/")) {
   536                 r = r.substring(1);
   537             }
   538             String[] replace = {};
   539             if (r.endsWith(".html")) {
   540                 response.setContentType("text/html");
   541                 LOG.info("Content type text/html");
   542                 replace = args;
   543             }
   544             if (r.endsWith(".xhtml")) {
   545                 response.setContentType("application/xhtml+xml");
   546                 LOG.info("Content type application/xhtml+xml");
   547                 replace = args;
   548             }
   549             OutputStream os = response.getOutputStream();
   550             try { 
   551                 InputStream is = res.get(r);
   552                 copyStream(is, os, request.getRequestURL().toString(), replace);
   553             } catch (IOException ex) {
   554                 response.setDetailMessage(ex.getLocalizedMessage());
   555                 response.setError();
   556                 response.setStatus(404);
   557             }
   558         }
   559 
   560         protected String computePage(Request request) {
   561             String r = resource;
   562             if (r == null) {
   563                 r = request.getHttpHandlerPath();
   564             }
   565             return r;
   566         }
   567     }
   568     
   569     private static class SubTree extends Page {
   570 
   571         public SubTree(Res res, String resource, String... args) {
   572             super(res, resource, args);
   573         }
   574 
   575         @Override
   576         protected String computePage(Request request) {
   577             return resource + request.getHttpHandlerPath();
   578         }
   579         
   580         
   581     }
   582 
   583     private class VM extends HttpHandler {
   584         @Override
   585         public void service(Request request, Response response) throws Exception {
   586             response.setCharacterEncoding("UTF-8");
   587             response.setContentType("text/javascript");
   588             StringBuilder sb = new StringBuilder();
   589             generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   590             response.getWriter().write(sb.toString());
   591         }
   592     }
   593 
   594     private static class Classes extends HttpHandler {
   595         private final Res loader;
   596 
   597         public Classes(Res loader) {
   598             this.loader = loader;
   599         }
   600 
   601         @Override
   602         public void service(Request request, Response response) throws Exception {
   603             String res = request.getHttpHandlerPath();
   604             if (res.startsWith("/")) {
   605                 res = res.substring(1);
   606             }
   607             InputStream is = null;
   608             try {
   609                 is = loader.get(res);
   610                 response.setContentType("text/javascript");
   611                 Writer w = response.getWriter();
   612                 w.append("[");
   613                 for (int i = 0;; i++) {
   614                     int b = is.read();
   615                     if (b == -1) {
   616                         break;
   617                     }
   618                     if (i > 0) {
   619                         w.append(", ");
   620                     }
   621                     if (i % 20 == 0) {
   622                         w.write("\n");
   623                     }
   624                     if (b > 127) {
   625                         b = b - 256;
   626                     }
   627                     w.append(Integer.toString(b));
   628                 }
   629                 w.append("\n]");
   630             } catch (IOException ex) {
   631                 response.setStatus(HttpStatus.NOT_FOUND_404);
   632                 response.setError();
   633                 response.setDetailMessage(ex.getMessage());
   634             } finally {
   635                 if (is != null) {
   636                     is.close();
   637                 }
   638             }
   639         }
   640     }
   641 }