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