launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 25 Mar 2016 11:12:16 +0100
changeset 1908 4f4554f69892
parent 1860 4ce38f21f4cd
child 1916 a9d37af23a00
permissions -rw-r--r--
Invoke methods with string parameters
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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.ByteArrayInputStream;
    21 import java.io.ByteArrayOutputStream;
    22 import java.io.Closeable;
    23 import java.io.File;
    24 import java.io.Flushable;
    25 import java.io.IOException;
    26 import java.io.InputStream;
    27 import java.io.InterruptedIOException;
    28 import java.io.OutputStream;
    29 import java.io.Reader;
    30 import java.io.UnsupportedEncodingException;
    31 import java.io.Writer;
    32 import java.net.JarURLConnection;
    33 import java.net.URI;
    34 import java.net.URISyntaxException;
    35 import java.net.URL;
    36 import java.net.URLConnection;
    37 import java.util.ArrayList;
    38 import java.util.Arrays;
    39 import java.util.Enumeration;
    40 import java.util.HashSet;
    41 import java.util.LinkedHashSet;
    42 import java.util.List;
    43 import java.util.Map;
    44 import java.util.Properties;
    45 import java.util.Set;
    46 import java.util.concurrent.BlockingQueue;
    47 import java.util.concurrent.Callable;
    48 import java.util.concurrent.CountDownLatch;
    49 import java.util.concurrent.LinkedBlockingQueue;
    50 import java.util.concurrent.TimeUnit;
    51 import java.util.jar.Attributes;
    52 import java.util.jar.Manifest;
    53 import java.util.logging.ConsoleHandler;
    54 import java.util.logging.Level;
    55 import java.util.logging.Logger;
    56 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
    57 import org.glassfish.grizzly.PortRange;
    58 import org.glassfish.grizzly.http.server.HttpHandler;
    59 import org.glassfish.grizzly.http.server.HttpServer;
    60 import org.glassfish.grizzly.http.server.NetworkListener;
    61 import org.glassfish.grizzly.http.server.Request;
    62 import org.glassfish.grizzly.http.server.Response;
    63 import org.glassfish.grizzly.http.server.ServerConfiguration;
    64 import org.glassfish.grizzly.http.server.StaticHttpHandler;
    65 import org.glassfish.grizzly.http.util.Header;
    66 import org.glassfish.grizzly.http.util.HttpStatus;
    67 import org.glassfish.grizzly.websockets.WebSocket;
    68 import org.glassfish.grizzly.websockets.WebSocketAddOn;
    69 import org.glassfish.grizzly.websockets.WebSocketApplication;
    70 import org.glassfish.grizzly.websockets.WebSocketEngine;
    71 
    72 /**
    73  * Lightweight server to launch Bck2Brwsr applications and tests.
    74  * Supports execution in native browser as well as Java's internal
    75  * execution engine.
    76  */
    77 abstract class BaseHTTPLauncher extends Launcher implements Flushable, Closeable, Callable<HttpServer> {
    78     static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
    79     private static final InvocationContext END = new InvocationContext(null, null, null);
    80     private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
    81     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
    82     private long timeOut;
    83     private final Res resources = new Res();
    84     private final String cmd;
    85     private Object[] brwsr;
    86     private HttpServer server;
    87     private CountDownLatch wait;
    88     private Thread flushing;
    89 
    90     public BaseHTTPLauncher(String cmd) {
    91         this.cmd = cmd;
    92         addClassLoader(BaseHTTPLauncher.class.getClassLoader());
    93         setTimeout(180000);
    94     }
    95 
    96     @Override
    97     InvocationContext runMethod(InvocationContext c) throws IOException {
    98         loaders.add(c.clazz.getClassLoader());
    99         methods.add(c);
   100         try {
   101             c.await(timeOut);
   102         } catch (InterruptedException ex) {
   103             throw new IOException(ex);
   104         }
   105         return c;
   106     }
   107 
   108     public void setTimeout(long ms) {
   109         timeOut = ms;
   110     }
   111 
   112     public void addClassLoader(ClassLoader url) {
   113         this.loaders.add(url);
   114     }
   115 
   116     ClassLoader[] loaders() {
   117         return loaders.toArray(new ClassLoader[loaders.size()]);
   118     }
   119 
   120     public void showURL(String startpage) throws IOException {
   121         if (!startpage.startsWith("/")) {
   122             startpage = "/" + startpage;
   123         }
   124         HttpServer s = initServer(".", true, "");
   125         int last = startpage.lastIndexOf('/');
   126         String prefix = startpage.substring(0, last);
   127         String simpleName = startpage.substring(last);
   128         s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
   129         server = s;
   130         try {
   131             launchServerAndBrwsr(s, simpleName);
   132         } catch (Exception ex) {
   133             throw new IOException(ex);
   134         }
   135     }
   136 
   137     void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
   138         if (!startpage.startsWith("/")) {
   139             startpage = "/" + startpage;
   140         }
   141         String prefix = null;
   142         if (!new File(dir, "bck2brwsr.js").exists()) {
   143             int last = startpage.lastIndexOf('/');
   144             if (last >= 0) {
   145                 prefix = startpage.substring(0, last);
   146             }
   147         }
   148         HttpServer s = initServer(dir.getPath(), addClasses, prefix);
   149         try {
   150             launchServerAndBrwsr(s, startpage);
   151         } catch (Exception ex) {
   152             throw new IOException(ex);
   153         }
   154     }
   155 
   156     @Override
   157     public void initialize() throws IOException {
   158         try {
   159             executeInBrowser();
   160         } catch (InterruptedException ex) {
   161             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   162             iio.initCause(ex);
   163             throw iio;
   164         } catch (Exception ex) {
   165             if (ex instanceof IOException) {
   166                 throw (IOException)ex;
   167             }
   168             if (ex instanceof RuntimeException) {
   169                 throw (RuntimeException)ex;
   170             }
   171             throw new IOException(ex);
   172         }
   173     }
   174 
   175     private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
   176         HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
   177         /*
   178         ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
   179             setPoolName("Fx/Bck2 Brwsr").
   180             setCorePoolSize(3).
   181             setMaxPoolSize(5);
   182         ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
   183             setPoolName("Kernel Fx/Bck2").
   184             setCorePoolSize(3).
   185             setMaxPoolSize(3);
   186         for (NetworkListener nl : s.getListeners()) {
   187             nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
   188             nl.getTransport().setKernelThreadPoolConfig(oneKernel);
   189         }
   190 */
   191         final ServerConfiguration conf = s.getServerConfiguration();
   192         VMAndPages vm = new VMAndPages();
   193         conf.addHttpHandler(vm, "/");
   194         if (vmPrefix != null) {
   195             vm.registerVM(vmPrefix + "/bck2brwsr.js");
   196         }
   197         if (path != null) {
   198             vm.addDocRoot(path);
   199         }
   200         if (addClasses) {
   201             conf.addHttpHandler(new Classes(resources), "/classes/");
   202         }
   203         final WebSocketAddOn addon = new WebSocketAddOn();
   204         for (NetworkListener listener : s.getListeners()) {
   205             listener.registerAddOn(addon);
   206         }
   207         Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
   208         l.setLevel(Level.FINE);
   209         l.setUseParentHandlers(false);
   210         ConsoleHandler ch = new ConsoleHandler();
   211         ch.setLevel(Level.ALL);
   212         l.addHandler(ch);
   213         return s;
   214     }
   215 
   216     private static int resourcesCount;
   217     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   218         wait = new CountDownLatch(1);
   219         server = initServer(".", true, "");
   220         final ServerConfiguration conf = server.getServerConfiguration();
   221 
   222         class DynamicResourceHandler extends HttpHandler {
   223             private final InvocationContext ic;
   224             DynamicResourceHandler delegate;
   225             public DynamicResourceHandler(InvocationContext ic) {
   226                 this.ic = ic;
   227                 for (Resource r : ic.resources) {
   228                     conf.addHttpHandler(this, r.httpPath);
   229                 }
   230             }
   231 
   232             public void close(DynamicResourceHandler del) {
   233                 conf.removeHttpHandler(this);
   234                 delegate = del;
   235             }
   236 
   237             @Override
   238             public void service(Request request, Response response) throws Exception {
   239                 if (delegate != null) {
   240                     delegate.service(request, response);
   241                     return;
   242                 }
   243 
   244                 if ("/dynamic".equals(request.getRequestURI())) {
   245                     boolean webSocket = false;
   246                     String mimeType = request.getParameter("mimeType");
   247                     List<String> params = new ArrayList<String>();
   248                     for (int i = 0; ; i++) {
   249                         String p = request.getParameter("param" + i);
   250                         if (p == null) {
   251                             break;
   252                         }
   253                         params.add(p);
   254                         if ("protocol:ws".equals(p)) {
   255                             webSocket = true;
   256                             continue;
   257                         }                    }
   258                     final String cnt = request.getParameter("content");
   259                     String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   260                     ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   261                     URI url;
   262                     final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   263                     if (webSocket) {
   264                         url = registerWebSocket(res);
   265                     } else {
   266                         url = registerResource(res);
   267                     }
   268                     response.setHeader(Header.CacheControl, "no-cache");
   269                     response.setHeader(Header.Pragma, "no-cache");
   270                     response.getWriter().write(url.toString());
   271                     response.getWriter().write("\n");
   272                     return;
   273                 }
   274 
   275                 for (Resource r : ic.resources) {
   276                     if (r.httpPath.equals(request.getRequestURI())) {
   277                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   278                         response.setContentType(r.httpType);
   279                         response.setHeader(Header.CacheControl, "no-cache");
   280                         response.setHeader(Header.Pragma, "no-cache");
   281                         r.httpContent.reset();
   282                         String[] params = null;
   283                         if (r.parameters.length != 0) {
   284                             params = new String[r.parameters.length];
   285                             for (int i = 0; i < r.parameters.length; i++) {
   286                                 params[i] = request.getParameter(r.parameters[i]);
   287                                 if (params[i] == null) {
   288                                     if ("http.method".equals(r.parameters[i])) {
   289                                         params[i] = request.getMethod().toString();
   290                                     } else if ("http.requestBody".equals(r.parameters[i])) {
   291                                         Reader rdr = request.getReader();
   292                                         StringBuilder sb = new StringBuilder();
   293                                         for (;;) {
   294                                             int ch = rdr.read();
   295                                             if (ch == -1) {
   296                                                 break;
   297                                             }
   298                                             sb.append((char)ch);
   299                                         }
   300                                         params[i] = sb.toString();
   301                                     } else if (r.parameters[i].startsWith("http.header.")) {
   302                                         params[i] = request.getHeader(r.parameters[i].substring(12));
   303                                     }
   304                                 }
   305                                 if (params[i] == null) {
   306                                     params[i] = "null";
   307                                 }
   308                             }
   309                         }
   310 
   311                         copyStream(r.httpContent, response.getOutputStream(), null, params);
   312                     }
   313                 }
   314             }
   315 
   316             private URI registerWebSocket(Resource r) {
   317                 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   318                 return pageURL("ws", server, r.httpPath);
   319             }
   320 
   321             private URI registerResource(Resource r) {
   322                 if (!ic.resources.contains(r)) {
   323                     ic.resources.add(r);
   324                     conf.addHttpHandler(this, r.httpPath);
   325                 }
   326                 return pageURL("http", server, r.httpPath);
   327             }
   328         }
   329 
   330         conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
   331 
   332         conf.addHttpHandler(new HttpHandler() {
   333             int cnt;
   334             List<InvocationContext> cases = new ArrayList<InvocationContext>();
   335             DynamicResourceHandler prev;
   336             @Override
   337             public void service(Request request, Response response) throws Exception {
   338                 String id = request.getParameter("request");
   339                 String value = request.getParameter("result");
   340                 String timeText = request.getParameter("time");
   341                 if (value != null && value.indexOf((char)0xC5) != -1) {
   342                     value = toUTF8(value);
   343                 }
   344                 int time;
   345                 if (timeText != null) {
   346                     try {
   347                         time = (int) Double.parseDouble(timeText);
   348                     } catch (NumberFormatException numberFormatException) {
   349                         time = 0;
   350                     }
   351                 } else {
   352                     time = 0;
   353                 }
   354 
   355                 InvocationContext mi = null;
   356                 int caseNmbr = -1;
   357 
   358                 if (id != null && value != null) {
   359                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   360                     value = decodeURL(value);
   361                     int indx = Integer.parseInt(id);
   362                     cases.get(indx).result(value, time, null);
   363                     if (++indx < cases.size()) {
   364                         mi = cases.get(indx);
   365                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   366                         caseNmbr = indx;
   367                     }
   368                 } else {
   369                     if (!cases.isEmpty()) {
   370                         LOG.info("Re-executing test cases");
   371                         mi = cases.get(0);
   372                         caseNmbr = 0;
   373                     }
   374                 }
   375 
   376                 if (mi == null) {
   377                     mi = methods.take();
   378                     caseNmbr = cnt++;
   379                 }
   380                 final Writer w = response.getWriter();
   381                 if (mi == END) {
   382                     w.write("");
   383                     wait.countDown();
   384                     cnt = 0;
   385                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   386                     return;
   387                 }
   388                 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
   389                 if (prev != null) {
   390                     prev.close(newRH);
   391                 }
   392                 prev = newRH;
   393                 conf.addHttpHandler(prev, "/dynamic");
   394 
   395                 cases.add(mi);
   396                 final String cn = mi.clazz.getName();
   397                 final String mn = mi.methodName;
   398                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   399                 w.write("{"
   400                     + "className: '" + cn + "', "
   401                     + "methodName: '" + mn + "', "
   402                     + "request: " + caseNmbr
   403                 );
   404                 if (mi.args != null) {
   405                     w.write(", args: [");
   406                     String sep = "";
   407                     for (String a : mi.args) {
   408                         w.write(sep);
   409                         w.write("'");
   410                         w.write(a);
   411                         w.write("'");
   412                         sep = ", ";
   413                     }
   414                     w.write("]");
   415                 }
   416                 if (mi.html != null) {
   417                     w.write(", html: '");
   418                     w.write(encodeJSON(mi.html));
   419                     w.write("'");
   420                 }
   421                 w.write("}");
   422             }
   423         }, "/data");
   424 
   425         this.brwsr = launchServerAndBrwsr(server, "/execute");
   426     }
   427 
   428     private static String encodeJSON(String in) {
   429         StringBuilder sb = new StringBuilder();
   430         for (int i = 0; i < in.length(); i++) {
   431             char ch = in.charAt(i);
   432             if (ch < 32 || ch == '\'' || ch == '"') {
   433                 sb.append("\\u");
   434                 String hs = "0000" + Integer.toHexString(ch);
   435                 hs = hs.substring(hs.length() - 4);
   436                 sb.append(hs);
   437             } else {
   438                 sb.append(ch);
   439             }
   440         }
   441         return sb.toString();
   442     }
   443 
   444     @Override
   445     public void shutdown() throws IOException {
   446         synchronized (this) {
   447             if (flushing != null) {
   448                 flushing.interrupt();
   449                 flushing = null;
   450             }
   451         }
   452         methods.offer(END);
   453         for (;;) {
   454             int prev = methods.size();
   455             try {
   456                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   457                     break;
   458                 }
   459             } catch (InterruptedException ex) {
   460                 throw new IOException(ex);
   461             }
   462             if (prev == methods.size()) {
   463                 LOG.log(
   464                     Level.WARNING,
   465                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
   466                     methods.size()
   467                 );
   468                 break;
   469             }
   470             LOG.log(Level.INFO,
   471                 "Timeout, but tests got from {0} to {1}. Trying again.",
   472                 new Object[]{prev, methods.size()}
   473             );
   474         }
   475         stopServerAndBrwsr(server, brwsr);
   476     }
   477 
   478     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   479         for (;;) {
   480             int ch = is.read();
   481             if (ch == -1) {
   482                 break;
   483             }
   484             if (ch == '$' && params.length > 0) {
   485                 int cnt = is.read() - '0';
   486                 if (baseURL != null && cnt == 'U' - '0') {
   487                     os.write(baseURL.getBytes("UTF-8"));
   488                 } else {
   489                     if (cnt >= 0 && cnt < params.length) {
   490                         os.write(params[cnt].getBytes("UTF-8"));
   491                     } else {
   492                         os.write('$');
   493                         os.write(cnt + '0');
   494                     }
   495                 }
   496             } else {
   497                 os.write(ch);
   498             }
   499         }
   500     }
   501 
   502     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   503         server.start();
   504         URI uri = pageURL("http", server, page);
   505         return showBrwsr(uri);
   506     }
   507     private static String toUTF8(String value) throws UnsupportedEncodingException {
   508         byte[] arr = new byte[value.length()];
   509         for (int i = 0; i < arr.length; i++) {
   510             arr[i] = (byte)value.charAt(i);
   511         }
   512         return new String(arr, "UTF-8");
   513     }
   514 
   515     private static String decodeURL(String s) {
   516         for (;;) {
   517             int pos = s.indexOf('%');
   518             if (pos == -1) {
   519                 return s;
   520             }
   521             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   522             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   523         }
   524     }
   525 
   526     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   527         if (brwsr == null) {
   528             return;
   529         }
   530         Process process = (Process)brwsr[0];
   531 
   532         server.stop();
   533         InputStream stdout = process.getInputStream();
   534         InputStream stderr = process.getErrorStream();
   535         drain("StdOut", stdout);
   536         drain("StdErr", stderr);
   537         process.destroy();
   538         int res;
   539         try {
   540             res = process.waitFor();
   541         } catch (InterruptedException ex) {
   542             throw new IOException(ex);
   543         }
   544         LOG.log(Level.INFO, "Exit code: {0}", res);
   545 
   546         deleteTree((File)brwsr[1]);
   547     }
   548 
   549     private static void drain(String name, InputStream is) throws IOException {
   550         int av = is.available();
   551         if (av > 0) {
   552             StringBuilder sb = new StringBuilder();
   553             sb.append("v== ").append(name).append(" ==v\n");
   554             while (av-- > 0) {
   555                 sb.append((char)is.read());
   556             }
   557             sb.append("\n^== ").append(name).append(" ==^");
   558             LOG.log(Level.INFO, sb.toString());
   559         }
   560     }
   561 
   562     private void deleteTree(File file) {
   563         if (file == null) {
   564             return;
   565         }
   566         File[] arr = file.listFiles();
   567         if (arr != null) {
   568             for (File s : arr) {
   569                 deleteTree(s);
   570             }
   571         }
   572         file.delete();
   573     }
   574 
   575     @Override
   576     public HttpServer call() throws Exception {
   577         return server;
   578     }
   579 
   580     @Override
   581     public synchronized void flush() throws IOException {
   582         flushing = Thread.currentThread();
   583         while (flushing == Thread.currentThread()) {
   584             try {
   585                 wait();
   586             } catch (InterruptedException ex) {
   587                 LOG.log(Level.FINE, null, ex);
   588             }
   589         }
   590     }
   591 
   592     @Override
   593     public void close() throws IOException {
   594         shutdown();
   595     }
   596 
   597     protected Object[] showBrwsr(URI uri) throws IOException {
   598         LOG.log(Level.INFO, "Showing {0}", uri);
   599         if (cmd == null) {
   600             try {
   601                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   602                     System.getProperty("java.vm.name"),
   603                     System.getProperty("java.vm.vendor"),
   604                     System.getProperty("java.vm.version"),
   605                 });
   606                 java.awt.Desktop.getDesktop().browse(uri);
   607                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   608                 return null;
   609             } catch (UnsupportedOperationException ex) {
   610                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   611                 LOG.log(Level.FINE, null, ex);
   612             } catch (IOException ex) {
   613                 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
   614                 LOG.log(Level.FINE, null, ex);
   615             }
   616         }
   617         {
   618             String cmdName = cmd == null ? "xdg-open" : cmd;
   619             String[] cmdArr = {
   620                 cmdName, uri.toString()
   621             };
   622             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   623             final Process process = Runtime.getRuntime().exec(cmdArr);
   624             return new Object[] { process, null };
   625         }
   626     }
   627 
   628     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   629     abstract String harnessResource();
   630     Object compileJar(URL jar, URL precompiled) throws IOException {
   631         return null;
   632     }
   633     String compileFromClassPath(URL f, Res loader) throws IOException {
   634         return null;
   635     }
   636 
   637     private static URI pageURL(String protocol, HttpServer server, final String page) {
   638         NetworkListener listener = server.getListeners().iterator().next();
   639         int port = listener.getPort();
   640         try {
   641             return new URI(protocol + "://localhost:" + port + page);
   642         } catch (URISyntaxException ex) {
   643             throw new IllegalStateException(ex);
   644         }
   645     }
   646 
   647     final class Res {
   648         private final Set<URL> ignore = new HashSet<URL>();
   649 
   650         Object compileJar(URL jarURL) throws IOException {
   651             List<String[]> libraries = new ArrayList<String[]>();
   652             for (ClassLoader loader : loaders) {
   653                 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
   654                 while (en.hasMoreElements()) {
   655                     URL e = en.nextElement();
   656                     Manifest mf = new Manifest(e.openStream());
   657                     for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
   658                         String key = entrySet.getKey();
   659                         Attributes attr = entrySet.getValue();
   660 
   661                         final String a = attr.getValue("Bck2BrwsrArtifactId");
   662                         final String g = attr.getValue("Bck2BrwsrGroupId");
   663                         final String v = attr.getValue("Bck2BrwsrVersion");
   664                         final String d = attr.getValue("Bck2BrwsrDebug");
   665 
   666                         if (g != null && a != null && v != null && "true".equals(d)) {
   667                             libraries.add(new String[] {
   668                                 a, g, v, key
   669                             });
   670                         }
   671                     }
   672                 }
   673             }
   674             URL precompiled = null;
   675             for (ClassLoader loader : loaders) {
   676                 for (String[] lib : libraries) {
   677                     final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
   678                     URL props = loader.getResource(res);
   679                     if (props != null) {
   680                         URLConnection c = props.openConnection();
   681                         Properties load = new Properties();
   682                         final InputStream is = c.getInputStream();
   683                         load.load(is);
   684                         is.close();
   685                         if (lib[2].equals(load.getProperty("version"))) {
   686                             if (c instanceof JarURLConnection) {
   687                                 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
   688                                 if (definedInURL.equals(jarURL)) {
   689                                     precompiled = loader.getResource(lib[3]);
   690                                 }
   691                             }
   692                         }
   693                     }
   694                 }
   695             }
   696             Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
   697             ignore.add(jarURL);
   698             return ret;
   699         }
   700         String compileFromClassPath(URL f) throws IOException {
   701             return BaseHTTPLauncher.this.compileFromClassPath(f, this);
   702         }
   703         public URL get(String resource, int skip) throws IOException {
   704             if (!resource.endsWith(".class")) {
   705                 return getResource(resource, skip);
   706             }
   707             URL u = null;
   708             for (ClassLoader l : loaders) {
   709                 Enumeration<URL> en = l.getResources(resource);
   710                 while (en.hasMoreElements()) {
   711                     u = en.nextElement();
   712                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   713                         return u;
   714                     }
   715                 }
   716             }
   717             if (u != null) {
   718                 if (u.toExternalForm().contains("rt.jar")) {
   719                     LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
   720                     return null;
   721                 }
   722                 return u;
   723             }
   724             throw new IOException("Can't find " + resource);
   725         }
   726         private URL getResource(String resource, int skip) throws IOException {
   727             for (ClassLoader l : loaders) {
   728                 Enumeration<URL> en = l.getResources(resource);
   729                 while (en.hasMoreElements()) {
   730                     final URL now = en.nextElement();
   731                     if (now.toExternalForm().contains("sisu-inject-bean")) {
   732                         // certainly we don't want this resource, as that
   733                         // module is not compiled with target 1.6, currently
   734                         continue;
   735                     }
   736                     if (now.getProtocol().equals("jar")) {
   737                         JarURLConnection juc = (JarURLConnection) now.openConnection();
   738                         if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
   739                             continue;
   740                         }
   741                     }
   742                     if (--skip < 0) {
   743                         return now;
   744                     }
   745                 }
   746             }
   747             throw new IOException("Not found (anymore of) " + resource);
   748         }
   749     }
   750 
   751     private static class Page extends HttpHandler {
   752         final String resource;
   753         private final String[] args;
   754         private final Res res;
   755 
   756         public Page(Res res, String resource, String... args) {
   757             this.res = res;
   758             this.resource = resource;
   759             this.args = args.length == 0 ? new String[] { "$0" } : args;
   760         }
   761 
   762         @Override
   763         public void service(Request request, Response response) throws Exception {
   764             String r = computePage(request);
   765             if (r.startsWith("/")) {
   766                 r = r.substring(1);
   767             }
   768             String[] replace = {};
   769             if (r.endsWith(".html")) {
   770                 response.setContentType("text/html");
   771                 LOG.info("Content type text/html");
   772                 replace = args;
   773             }
   774             if (r.endsWith(".xhtml")) {
   775                 response.setContentType("application/xhtml+xml");
   776                 LOG.info("Content type application/xhtml+xml");
   777                 replace = args;
   778             }
   779             OutputStream os = response.getOutputStream();
   780             try {
   781                 InputStream is = res.get(r, 0).openStream();
   782                 copyStream(is, os, request.getRequestURL().toString(), replace);
   783             } catch (IOException ex) {
   784                 response.setDetailMessage(ex.getLocalizedMessage());
   785                 response.setError();
   786                 response.setStatus(404);
   787             }
   788         }
   789 
   790         protected String computePage(Request request) {
   791             String r = resource;
   792             if (r == null) {
   793                 r = request.getHttpHandlerPath();
   794             }
   795             return r;
   796         }
   797     }
   798 
   799     private static class SubTree extends Page {
   800 
   801         public SubTree(Res res, String resource, String... args) {
   802             super(res, resource, args);
   803         }
   804 
   805         @Override
   806         protected String computePage(Request request) {
   807             return resource + request.getHttpHandlerPath();
   808         }
   809 
   810 
   811     }
   812 
   813     private class VMAndPages extends StaticHttpHandler {
   814         private String vmResource;
   815 
   816         public VMAndPages() {
   817             super((String[]) null);
   818         }
   819 
   820         @Override
   821         public void service(Request request, Response response) throws Exception {
   822             if ("true".equals(request.getParameter("exit"))) {
   823                 LOG.info("Exit request received. Shutting down!");
   824                 shutdown();
   825             }
   826             if (request.getRequestURI().equals(vmResource)) {
   827                 response.setCharacterEncoding("UTF-8");
   828                 response.setContentType("text/javascript");
   829                 StringBuilder sb = new StringBuilder();
   830                 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   831                 response.getWriter().write(sb.toString());
   832             } else {
   833                 super.service(request, response);
   834             }
   835         }
   836 
   837         private void registerVM(String vmResource) {
   838             this.vmResource = vmResource;
   839         }
   840     }
   841 
   842     private static class Classes extends HttpHandler {
   843         private final Res loader;
   844 
   845         public Classes(Res loader) {
   846             this.loader = loader;
   847         }
   848 
   849         @Override
   850         public void service(Request request, Response response) throws Exception {
   851             String res = request.getHttpHandlerPath();
   852             if (res.startsWith("/")) {
   853                 res = res.substring(1);
   854             }
   855             String skip = request.getParameter("skip");
   856             int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
   857             URL url = loader.get(res, skipCnt);
   858             if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
   859                 response.setCharacterEncoding("UTF-8");
   860                 if (url.getProtocol().equals("jar")) {
   861                     JarURLConnection juc = (JarURLConnection) url.openConnection();
   862                     Object s = null;
   863                     try {
   864                         s = loader.compileJar(juc.getJarFileURL());
   865                     } catch (IOException iOException) {
   866                         throw new IOException("Can't compile " + url.toExternalForm(), iOException);
   867                     }
   868                     if (s instanceof String) {
   869                         Writer w = response.getWriter();
   870                         w.append((String)s);
   871                         w.close();
   872                         return;
   873                     }
   874                     if (s instanceof InputStream) {
   875                         copyStream((InputStream) s, response.getOutputStream(), null);
   876                         return;
   877                     }
   878                 }
   879                 if (url.getProtocol().equals("file")) {
   880                     final String filePart = url.getFile();
   881                     if (filePart.endsWith(res)) {
   882                         url = new URL(
   883                             url.getProtocol(),
   884                             url.getHost(),
   885                             url.getPort(),
   886                             filePart.substring(0, filePart.length() - res.length())
   887                         );
   888                     }
   889                     String s = loader.compileFromClassPath(url);
   890                     if (s != null) {
   891                         Writer w = response.getWriter();
   892                         w.append(s);
   893                         w.close();
   894                         return;
   895                     }
   896                 }
   897             } catch (IOException ex) {
   898                 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
   899             }
   900             InputStream is = null;
   901             try {
   902                 if (url == null) {
   903                     throw new IOException("Resource not found");
   904                 }
   905                 is = url.openStream();
   906                 response.setContentType("text/javascript");
   907                 Writer w = response.getWriter();
   908                 w.append("([");
   909                 for (int i = 0;; i++) {
   910                     int b = is.read();
   911                     if (b == -1) {
   912                         break;
   913                     }
   914                     if (i > 0) {
   915                         w.append(", ");
   916                     }
   917                     if (i % 20 == 0) {
   918                         w.write("\n");
   919                     }
   920                     if (b > 127) {
   921                         b = b - 256;
   922                     }
   923                     w.append(Integer.toString(b));
   924                 }
   925                 w.append("\n])");
   926             } catch (IOException ex) {
   927                 response.setStatus(HttpStatus.NOT_FOUND_404);
   928                 response.setError();
   929                 response.setDetailMessage(ex.getMessage());
   930             } finally {
   931                 if (is != null) {
   932                     is.close();
   933                 }
   934             }
   935         }
   936 
   937     }
   938     private static class WS extends WebSocketApplication {
   939 
   940         private final Resource r;
   941 
   942         private WS(Resource r) {
   943             this.r = r;
   944         }
   945 
   946         @Override
   947         public void onMessage(WebSocket socket, String text) {
   948             try {
   949                 r.httpContent.reset();
   950                 ByteArrayOutputStream out = new ByteArrayOutputStream();
   951                 copyStream(r.httpContent, out, null, text);
   952                 String s = new String(out.toByteArray(), "UTF-8");
   953                 socket.send(s);
   954             } catch (IOException ex) {
   955                 LOG.log(Level.WARNING, null, ex);
   956             }
   957         }
   958 
   959     }}