launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 22 Dec 2012 15:01:20 +0100
branchlauncher
changeset 364 91f5b1f604d8
parent 363 8b59e6f8c837
child 365 4c8388f797b2
permissions -rw-r--r--
Log also what is happening in the server
     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                 
   190                 if (id != null && value != null) {
   191                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   192                     value = value.replace("%20", " ");
   193                     cases[Integer.parseInt(id)].result = value;
   194                 }
   195                 currentTest[0] = cnt;
   196                 
   197                 if (cnt >= cases.length) {
   198                     response.getWriter().write("");
   199                     wait.countDown();
   200                     cnt = 0;
   201                     return;
   202                 }
   203                 
   204                 final String cn = cases[cnt].className;
   205                 final String mn = cases[cnt].methodName;
   206                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
   207                 response.getWriter().write("{"
   208                     + "className: '" + cn + "', "
   209                     + "methodName: '" + mn + "', "
   210                     + "request: " + cnt
   211                     + "}");
   212                 cnt++;
   213             }
   214         }, "/data");
   215 
   216         launchServerAndBrwsr(server, "/execute");
   217         
   218         for (;;) {
   219             int prev = currentTest[0];
   220             if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   221                 break;
   222             }
   223             if (prev == currentTest[0]) {
   224                 LOG.log(
   225                     Level.WARNING, 
   226                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   227                     currentTest[0]
   228                 );
   229                 break;
   230             }
   231             LOG.log(Level.INFO, 
   232                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   233                 new Object[]{prev, currentTest[0]}
   234             );
   235         }
   236         server.stop();
   237     }
   238     
   239     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   240         for (;;) {
   241             int ch = is.read();
   242             if (ch == -1) {
   243                 break;
   244             }
   245             if (ch == '$') {
   246                 int cnt = is.read() - '0';
   247                 if (cnt == 'U' - '0') {
   248                     os.write(baseURL.getBytes());
   249                 }
   250                 if (cnt < params.length) {
   251                     os.write(params[cnt].getBytes());
   252                 }
   253             } else {
   254                 os.write(ch);
   255             }
   256         }
   257     }
   258 
   259     private void launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   260         server.start();
   261         NetworkListener listener = server.getListeners().iterator().next();
   262         int port = listener.getPort();
   263         
   264         URI uri = new URI("http://localhost:" + port + page);
   265         LOG.log(Level.INFO, "Showing {0}", uri);
   266         try {
   267             Desktop.getDesktop().browse(uri);
   268         } catch (UnsupportedOperationException ex) {
   269             String[] cmd = { 
   270                 "xdg-open", uri.toString()
   271             };
   272             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
   273             final Process process = Runtime.getRuntime().exec(cmd);
   274             InputStream stdout = process.getInputStream();
   275             InputStream stderr = process.getErrorStream();
   276             int res = process.waitFor();
   277             LOG.log(Level.INFO, "Exit code: {0}", res);
   278             drain("StdOut", stdout);
   279             drain("StdErr", stderr);
   280         }
   281     }
   282     
   283     private static void drain(String name, InputStream is) throws IOException {
   284         int av = is.available();
   285         if (av > 0) {
   286             StringBuilder sb = new StringBuilder();
   287             sb.append("v== ").append(name).append(" ==v\n");
   288             while (av-- > 0) {
   289                 sb.append((char)is.read());
   290             }
   291             sb.append("\n^== ").append(name).append(" ==^");
   292             LOG.log(Level.INFO, sb.toString());
   293         }
   294     }
   295 
   296     private class Res implements Bck2Brwsr.Resources {
   297         @Override
   298         public InputStream get(String resource) throws IOException {
   299             for (ClassLoader l : loaders) {
   300                 URL u = null;
   301                 Enumeration<URL> en = l.getResources(resource);
   302                 while (en.hasMoreElements()) {
   303                     u = en.nextElement();
   304                 }
   305                 if (u != null) {
   306                     return u.openStream();
   307                 }
   308             }
   309             throw new IOException("Can't find " + resource);
   310         }
   311     }
   312 
   313     private static class Page extends HttpHandler {
   314         private final String resource;
   315         private final String[] args;
   316         private final Res res;
   317         
   318         public Page(Res res, String resource, String... args) {
   319             this.res = res;
   320             this.resource = resource;
   321             this.args = args;
   322         }
   323 
   324         @Override
   325         public void service(Request request, Response response) throws Exception {
   326             String r = resource;
   327             if (r == null) {
   328                 r = request.getHttpHandlerPath();
   329                 if (r.startsWith("/")) {
   330                     r = r.substring(1);
   331                 }
   332             }
   333             if (r.endsWith(".html") || r.endsWith(".xhtml")) {
   334                 response.setContentType("text/html");
   335             }
   336             OutputStream os = response.getOutputStream();
   337             try (InputStream is = res.get(r)) {
   338                 copyStream(is, os, request.getRequestURL().toString(), args);
   339             } catch (IOException ex) {
   340                 response.setDetailMessage(ex.getLocalizedMessage());
   341                 response.setError();
   342                 response.setStatus(404);
   343             }
   344         }
   345     }
   346 
   347     private static class VM extends HttpHandler {
   348         private final Res loader;
   349 
   350         public VM(Res loader) {
   351             this.loader = loader;
   352         }
   353 
   354         @Override
   355         public void service(Request request, Response response) throws Exception {
   356             response.setCharacterEncoding("UTF-8");
   357             response.setContentType("text/javascript");
   358             Bck2Brwsr.generate(response.getWriter(), loader);
   359         }
   360     }
   361     private static class VMInit extends HttpHandler {
   362         public VMInit() {
   363         }
   364 
   365         @Override
   366         public void service(Request request, Response response) throws Exception {
   367             response.setCharacterEncoding("UTF-8");
   368             response.setContentType("text/javascript");
   369             response.getWriter().append(
   370                 "function ldCls(res) {\n"
   371                 + "  var request = new XMLHttpRequest();\n"
   372                 + "  request.open('GET', '/classes/' + res, false);\n"
   373                 + "  request.send();\n"
   374                 + "  var arr = eval('(' + request.responseText + ')');\n"
   375                 + "  return arr;\n"
   376                 + "}\n"
   377                 + "var vm = new bck2brwsr(ldCls);\n");
   378         }
   379     }
   380 
   381     private static class Classes extends HttpHandler {
   382         private final Res loader;
   383 
   384         public Classes(Res loader) {
   385             this.loader = loader;
   386         }
   387 
   388         @Override
   389         public void service(Request request, Response response) throws Exception {
   390             String res = request.getHttpHandlerPath();
   391             if (res.startsWith("/")) {
   392                 res = res.substring(1);
   393             }
   394             try (InputStream is = loader.get(res)) {
   395                 response.setContentType("text/javascript");
   396                 Writer w = response.getWriter();
   397                 w.append("[");
   398                 for (int i = 0;; i++) {
   399                     int b = is.read();
   400                     if (b == -1) {
   401                         break;
   402                     }
   403                     if (i > 0) {
   404                         w.append(", ");
   405                     }
   406                     if (i % 20 == 0) {
   407                         w.write("\n");
   408                     }
   409                     if (b > 127) {
   410                         b = b - 256;
   411                     }
   412                     w.append(Integer.toString(b));
   413                 }
   414                 w.append("\n]");
   415             } catch (IOException ex) {
   416                 response.setError();
   417                 response.setDetailMessage(ex.getMessage());
   418             }
   419         }
   420     }
   421     
   422     public static final class MethodInvocation {
   423         final String className;
   424         final String methodName;
   425         String result;
   426 
   427         MethodInvocation(String className, String methodName) {
   428             this.className = className;
   429             this.methodName = methodName;
   430         }
   431 
   432         @Override
   433         public String toString() {
   434             return result;
   435         }
   436     }
   437 }