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