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