launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 23 Dec 2012 09:17:26 +0100
branchlauncher
changeset 369 723d854272ae
parent 367 02641a16e272
child 370 ed48023d1d85
permissions -rw-r--r--
Trying again behavior of xdg-open on the hudson runner
     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.awt.Desktop;
    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.nio.file.Files;
    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.CountDownLatch;
    38 import java.util.concurrent.TimeUnit;
    39 import java.util.logging.Level;
    40 import java.util.logging.Logger;
    41 import javax.script.Invocable;
    42 import javax.script.ScriptEngine;
    43 import javax.script.ScriptEngineManager;
    44 import javax.script.ScriptException;
    45 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
    46 import org.apidesign.vm4brwsr.Bck2Brwsr;
    47 import org.glassfish.grizzly.PortRange;
    48 import org.glassfish.grizzly.http.server.HttpHandler;
    49 import org.glassfish.grizzly.http.server.HttpServer;
    50 import org.glassfish.grizzly.http.server.NetworkListener;
    51 import org.glassfish.grizzly.http.server.Request;
    52 import org.glassfish.grizzly.http.server.Response;
    53 import org.glassfish.grizzly.http.server.ServerConfiguration;
    54 
    55 /**
    56  * Lightweight server to launch Bck2Brwsr applications and tests.
    57  * Supports execution in native browser as well as Java's internal 
    58  * execution engine.
    59  */
    60 public class Bck2BrwsrLauncher {
    61     private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
    62     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    63     private List<MethodInvocation> methods = new ArrayList<>();
    64     private long timeOut;
    65     private String sen;
    66     private String showURL;
    67     private final Res resources = new Res();
    68     
    69     
    70     public MethodInvocation addMethod(Class<?> clazz, String method) {
    71         loaders.add(clazz.getClassLoader());
    72         MethodInvocation c = new MethodInvocation(clazz.getName(), method);
    73         methods.add(c);
    74         return c;
    75     }
    76     
    77     public void setTimeout(long ms) {
    78         timeOut = ms;
    79     }
    80     
    81     public void setScriptEngineName(String sen) {
    82         this.sen = sen;
    83     }
    84 
    85     public void setStartPage(String startpage) {
    86         if (!startpage.startsWith("/")) {
    87             startpage = "/" + startpage;
    88         }
    89         this.showURL = startpage;
    90     }
    91 
    92     public void addClassLoader(ClassLoader url) {
    93         this.loaders.add(url);
    94     }
    95     
    96     public static void main( String[] args ) throws Exception {
    97         Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
    98         l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
    99         l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
   100         l.execute();
   101         System.in.read();
   102     }
   103 
   104 
   105     public void execute() throws IOException {
   106         try {
   107             if (sen != null) {
   108                 executeRhino();
   109             } else if (showURL != null) {
   110                 HttpServer server = initServer();
   111                 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
   112                 launchServerAndBrwsr(server, showURL);
   113             } else {
   114                 executeInBrowser();
   115             }
   116         } catch (InterruptedException ex) {
   117             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   118             iio.initCause(ex);
   119             throw iio;
   120         } catch (Exception ex) {
   121             if (ex instanceof IOException) {
   122                 throw (IOException)ex;
   123             }
   124             if (ex instanceof RuntimeException) {
   125                 throw (RuntimeException)ex;
   126             }
   127             throw new IOException(ex);
   128         }
   129     }
   130     
   131     private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
   132         StringBuilder sb = new StringBuilder();
   133         Bck2Brwsr.generate(sb, new Res());
   134 
   135         ScriptEngineManager sem = new ScriptEngineManager();
   136         ScriptEngine mach = sem.getEngineByExtension(sen);
   137 
   138         sb.append(
   139               "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
   140             + "\nfunction initVM() { return vm; };"
   141             + "\n");
   142 
   143         Object res = mach.eval(sb.toString());
   144         if (!(mach instanceof Invocable)) {
   145             throw new IOException("It is invocable object: " + res);
   146         }
   147         Invocable code = (Invocable) mach;
   148         
   149         Object vm = code.invokeFunction("initVM");
   150         Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
   151 
   152         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   153         for (MethodInvocation mi : cases) {
   154             mi.result = code.invokeMethod(console, 
   155                 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2", 
   156                 mi.className, mi.methodName
   157             ).toString();
   158         }
   159     }
   160     
   161     private HttpServer initServer() {
   162         HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
   163 
   164         final ServerConfiguration conf = server.getServerConfiguration();
   165         conf.addHttpHandler(new Page(resources, 
   166             "org/apidesign/bck2brwsr/launcher/console.xhtml",
   167             "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
   168         ), "/console");
   169         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
   170         conf.addHttpHandler(new VMInit(), "/vm.js");
   171         conf.addHttpHandler(new Classes(resources), "/classes/");
   172         return server;
   173     }
   174     
   175     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   176         final CountDownLatch wait = new CountDownLatch(1);
   177         final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
   178         
   179         HttpServer server = initServer();
   180         ServerConfiguration conf = server.getServerConfiguration();
   181         conf.addHttpHandler(new Page(resources, 
   182             "org/apidesign/bck2brwsr/launcher/harness.xhtml"
   183         ), "/execute");
   184         final int[] currentTest = { -1 };
   185         conf.addHttpHandler(new HttpHandler() {
   186             int cnt;
   187             @Override
   188             public void service(Request request, Response response) throws Exception {
   189                 String id = request.getParameter("request");
   190                 String value = request.getParameter("result");
   191                 
   192                 if (id != null && value != null) {
   193                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   194                     value = value.replace("%20", " ");
   195                     cases[Integer.parseInt(id)].result = value;
   196                 }
   197                 currentTest[0] = cnt;
   198                 
   199                 if (cnt >= cases.length) {
   200                     response.getWriter().write("");
   201                     wait.countDown();
   202                     cnt = 0;
   203                     return;
   204                 }
   205                 
   206                 final String cn = cases[cnt].className;
   207                 final String mn = cases[cnt].methodName;
   208                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   209                 response.getWriter().write("{"
   210                     + "className: '" + cn + "', "
   211                     + "methodName: '" + mn + "', "
   212                     + "request: " + cnt
   213                     + "}");
   214                 cnt++;
   215             }
   216         }, "/data");
   217 
   218         Object[] brwsr = launchServerAndBrwsr(server, "/execute");
   219         
   220         for (;;) {
   221             int prev = currentTest[0];
   222             if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   223                 break;
   224             }
   225             if (prev == currentTest[0]) {
   226                 LOG.log(
   227                     Level.WARNING, 
   228                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   229                     currentTest[0]
   230                 );
   231                 break;
   232             }
   233             LOG.log(Level.INFO, 
   234                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   235                 new Object[]{prev, currentTest[0]}
   236             );
   237         }
   238         stopServerAndBrwsr(server, brwsr);
   239     }
   240     
   241     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   242         for (;;) {
   243             int ch = is.read();
   244             if (ch == -1) {
   245                 break;
   246             }
   247             if (ch == '$') {
   248                 int cnt = is.read() - '0';
   249                 if (cnt == 'U' - '0') {
   250                     os.write(baseURL.getBytes());
   251                 }
   252                 if (cnt < params.length) {
   253                     os.write(params[cnt].getBytes());
   254                 }
   255             } else {
   256                 os.write(ch);
   257             }
   258         }
   259     }
   260 
   261     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   262         server.start();
   263         NetworkListener listener = server.getListeners().iterator().next();
   264         int port = listener.getPort();
   265         
   266         URI uri = new URI("http://localhost:" + port + page);
   267         LOG.log(Level.INFO, "Showing {0}", uri);
   268 //        try {
   269 //            Desktop.getDesktop().browse(uri);
   270 //            return null;
   271 //        } catch (UnsupportedOperationException ex)
   272         {
   273 //            File dir = File.createTempFile("chrome", ".dir");
   274 //            dir.delete();
   275 //            dir.mkdirs();
   276 //            String[] cmd = { 
   277 //                "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
   278 //            };
   279 //            LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   280 //            final Process process = Runtime.getRuntime().exec(cmd);
   281 //            return new Object[] { process, dir };
   282         }
   283         {
   284             String[] cmd = { 
   285                 "xdg-open", uri.toString()
   286             };
   287             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   288             final Process process = Runtime.getRuntime().exec(cmd);
   289             return new Object[] { process, null };
   290         }
   291     }
   292     
   293     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
   294         Process process = (Process)brwsr[0];
   295         
   296         server.stop();
   297         InputStream stdout = process.getInputStream();
   298         InputStream stderr = process.getErrorStream();
   299         drain("StdOut", stdout);
   300         drain("StdErr", stderr);
   301         process.destroy();
   302         int res = process.waitFor();
   303         LOG.log(Level.INFO, "Exit code: {0}", res);
   304 
   305         deleteTree((File)brwsr[1]);
   306     }
   307     
   308     private static void drain(String name, InputStream is) throws IOException {
   309         int av = is.available();
   310         if (av > 0) {
   311             StringBuilder sb = new StringBuilder();
   312             sb.append("v== ").append(name).append(" ==v\n");
   313             while (av-- > 0) {
   314                 sb.append((char)is.read());
   315             }
   316             sb.append("\n^== ").append(name).append(" ==^");
   317             LOG.log(Level.INFO, sb.toString());
   318         }
   319     }
   320 
   321     private void deleteTree(File file) {
   322         if (file == null) {
   323             return;
   324         }
   325         File[] arr = file.listFiles();
   326         if (arr != null) {
   327             for (File s : arr) {
   328                 deleteTree(s);
   329             }
   330         }
   331         file.delete();
   332     }
   333 
   334     private class Res implements Bck2Brwsr.Resources {
   335         @Override
   336         public InputStream get(String resource) throws IOException {
   337             for (ClassLoader l : loaders) {
   338                 URL u = null;
   339                 Enumeration<URL> en = l.getResources(resource);
   340                 while (en.hasMoreElements()) {
   341                     u = en.nextElement();
   342                 }
   343                 if (u != null) {
   344                     return u.openStream();
   345                 }
   346             }
   347             throw new IOException("Can't find " + resource);
   348         }
   349     }
   350 
   351     private static class Page extends HttpHandler {
   352         private final String resource;
   353         private final String[] args;
   354         private final Res res;
   355         
   356         public Page(Res res, String resource, String... args) {
   357             this.res = res;
   358             this.resource = resource;
   359             this.args = args;
   360         }
   361 
   362         @Override
   363         public void service(Request request, Response response) throws Exception {
   364             String r = resource;
   365             if (r == null) {
   366                 r = request.getHttpHandlerPath();
   367                 if (r.startsWith("/")) {
   368                     r = r.substring(1);
   369                 }
   370             }
   371             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   372                 response.setContentType("text/html");
   373             }
   374             OutputStream os = response.getOutputStream();
   375             try (InputStream is = res.get(r)) {
   376                 copyStream(is, os, request.getRequestURL().toString(), args);
   377             } catch (IOException ex) {
   378                 response.setDetailMessage(ex.getLocalizedMessage());
   379                 response.setError();
   380                 response.setStatus(404);
   381             }
   382         }
   383     }
   384 
   385     private static class VM extends HttpHandler {
   386         private final Res loader;
   387 
   388         public VM(Res loader) {
   389             this.loader = loader;
   390         }
   391 
   392         @Override
   393         public void service(Request request, Response response) throws Exception {
   394             response.setCharacterEncoding("UTF-8");
   395             response.setContentType("text/javascript");
   396             Bck2Brwsr.generate(response.getWriter(), loader);
   397         }
   398     }
   399     private static class VMInit extends HttpHandler {
   400         public VMInit() {
   401         }
   402 
   403         @Override
   404         public void service(Request request, Response response) throws Exception {
   405             response.setCharacterEncoding("UTF-8");
   406             response.setContentType("text/javascript");
   407             response.getWriter().append(
   408                 "function ldCls(res) {\n"
   409                 + "  var request = new XMLHttpRequest();\n"
   410                 + "  request.open('GET', '/classes/' + res, false);\n"
   411                 + "  request.send();\n"
   412                 + "  var arr = eval('(' + request.responseText + ')');\n"
   413                 + "  return arr;\n"
   414                 + "}\n"
   415                 + "var vm = new bck2brwsr(ldCls);\n");
   416         }
   417     }
   418 
   419     private static class Classes extends HttpHandler {
   420         private final Res loader;
   421 
   422         public Classes(Res loader) {
   423             this.loader = loader;
   424         }
   425 
   426         @Override
   427         public void service(Request request, Response response) throws Exception {
   428             String res = request.getHttpHandlerPath();
   429             if (res.startsWith("/")) {
   430                 res = res.substring(1);
   431             }
   432             try (InputStream is = loader.get(res)) {
   433                 response.setContentType("text/javascript");
   434                 Writer w = response.getWriter();
   435                 w.append("[");
   436                 for (int i = 0;; i++) {
   437                     int b = is.read();
   438                     if (b == -1) {
   439                         break;
   440                     }
   441                     if (i > 0) {
   442                         w.append(", ");
   443                     }
   444                     if (i % 20 == 0) {
   445                         w.write("\n");
   446                     }
   447                     if (b > 127) {
   448                         b = b - 256;
   449                     }
   450                     w.append(Integer.toString(b));
   451                 }
   452                 w.append("\n]");
   453             } catch (IOException ex) {
   454                 response.setError();
   455                 response.setDetailMessage(ex.getMessage());
   456             }
   457         }
   458     }
   459     
   460     public static final class MethodInvocation {
   461         final String className;
   462         final String methodName;
   463         String result;
   464 
   465         MethodInvocation(String className, String methodName) {
   466             this.className = className;
   467             this.methodName = methodName;
   468         }
   469 
   470         @Override
   471         public String toString() {
   472             return result;
   473         }
   474     }
   475 }