launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 08 Dec 2014 00:22:49 +0100
changeset 1746 001275142bf7
parent 1733 955520296b08
child 1751 f91eb8500d18
permissions -rw-r--r--
Can use precompiled versions even when running tests
     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.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.JarFile;
    52 import java.util.jar.Manifest;
    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.HttpStatus;
    65 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
    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         return s;
   206     }
   207     
   208     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   209         wait = new CountDownLatch(1);
   210         server = initServer(".", true, "");
   211         final ServerConfiguration conf = server.getServerConfiguration();
   212         
   213         class DynamicResourceHandler extends HttpHandler {
   214             private final InvocationContext ic;
   215             private int resourcesCount;
   216             DynamicResourceHandler delegate;
   217             public DynamicResourceHandler(InvocationContext ic) {
   218                 this.ic = ic;
   219                 for (Resource r : ic.resources) {
   220                     conf.addHttpHandler(this, r.httpPath);
   221                 }
   222             }
   223 
   224             public void close(DynamicResourceHandler del) {
   225                 conf.removeHttpHandler(this);
   226                 delegate = del;
   227             }
   228             
   229             @Override
   230             public void service(Request request, Response response) throws Exception {
   231                 if (delegate != null) {
   232                     delegate.service(request, response);
   233                     return;
   234                 }
   235                 
   236                 if ("/dynamic".equals(request.getRequestURI())) {
   237                     boolean webSocket = false;
   238                     String mimeType = request.getParameter("mimeType");
   239                     List<String> params = new ArrayList<String>();
   240                     for (int i = 0; ; i++) {
   241                         String p = request.getParameter("param" + i);
   242                         if (p == null) {
   243                             break;
   244                         }
   245                         params.add(p);
   246                         if ("protocol:ws".equals(p)) {
   247                             webSocket = true;
   248                             continue;
   249                         }                    }
   250                     final String cnt = request.getParameter("content");
   251                     String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   252                     ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   253                     URI url;
   254                     final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   255                     if (webSocket) {
   256                         url = registerWebSocket(res);
   257                     } else {
   258                         url = registerResource(res);
   259                     }
   260                     response.getWriter().write(url.toString());
   261                     response.getWriter().write("\n");
   262                     return;
   263                 }
   264                 
   265                 for (Resource r : ic.resources) {
   266                     if (r.httpPath.equals(request.getRequestURI())) {
   267                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   268                         response.setContentType(r.httpType);
   269                         r.httpContent.reset();
   270                         String[] params = null;
   271                         if (r.parameters.length != 0) {
   272                             params = new String[r.parameters.length];
   273                             for (int i = 0; i < r.parameters.length; i++) {
   274                                 params[i] = request.getParameter(r.parameters[i]);
   275                                 if (params[i] == null) {
   276                                     if ("http.method".equals(r.parameters[i])) {
   277                                         params[i] = request.getMethod().toString();
   278                                     } else if ("http.requestBody".equals(r.parameters[i])) {
   279                                         Reader rdr = request.getReader();
   280                                         StringBuilder sb = new StringBuilder();
   281                                         for (;;) {
   282                                             int ch = rdr.read();
   283                                             if (ch == -1) {
   284                                                 break;
   285                                             }
   286                                             sb.append((char)ch);
   287                                         }
   288                                         params[i] = sb.toString();
   289                                     }
   290                                 }
   291                                 if (params[i] == null) {
   292                                     params[i] = "null";
   293                                 }
   294                             }
   295                         }
   296                         
   297                         copyStream(r.httpContent, response.getOutputStream(), null, params);
   298                     }
   299                 }
   300             }
   301             
   302             private URI registerWebSocket(Resource r) {
   303                 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   304                 return pageURL("ws", server, r.httpPath);
   305             }
   306 
   307             private URI registerResource(Resource r) {
   308                 if (!ic.resources.contains(r)) {
   309                     ic.resources.add(r);
   310                     conf.addHttpHandler(this, r.httpPath);
   311                 }
   312                 return pageURL("http", server, r.httpPath);
   313             }
   314         }
   315         
   316         conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
   317         
   318         conf.addHttpHandler(new HttpHandler() {
   319             int cnt;
   320             List<InvocationContext> cases = new ArrayList<InvocationContext>();
   321             DynamicResourceHandler prev;
   322             @Override
   323             public void service(Request request, Response response) throws Exception {
   324                 String id = request.getParameter("request");
   325                 String value = request.getParameter("result");
   326                 if (value != null && value.indexOf((char)0xC5) != -1) {
   327                     value = toUTF8(value);
   328                 }
   329                 
   330                 
   331                 InvocationContext mi = null;
   332                 int caseNmbr = -1;
   333                 
   334                 if (id != null && value != null) {
   335                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   336                     value = decodeURL(value);
   337                     int indx = Integer.parseInt(id);
   338                     cases.get(indx).result(value, null);
   339                     if (++indx < cases.size()) {
   340                         mi = cases.get(indx);
   341                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   342                         caseNmbr = indx;
   343                     }
   344                 } else {
   345                     if (!cases.isEmpty()) {
   346                         LOG.info("Re-executing test cases");
   347                         mi = cases.get(0);
   348                         caseNmbr = 0;
   349                     }
   350                 }
   351                 
   352                 if (mi == null) {
   353                     mi = methods.take();
   354                     caseNmbr = cnt++;
   355                 }
   356                 if (mi == END) {
   357                     response.getWriter().write("");
   358                     wait.countDown();
   359                     cnt = 0;
   360                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   361                     return;
   362                 }
   363                 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
   364                 if (prev != null) {
   365                     prev.close(newRH);
   366                 }
   367                 prev = newRH;
   368                 conf.addHttpHandler(prev, "/dynamic");
   369                 
   370                 cases.add(mi);
   371                 final String cn = mi.clazz.getName();
   372                 final String mn = mi.methodName;
   373                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   374                 response.getWriter().write("{"
   375                     + "className: '" + cn + "', "
   376                     + "methodName: '" + mn + "', "
   377                     + "request: " + caseNmbr
   378                 );
   379                 if (mi.html != null) {
   380                     response.getWriter().write(", html: '");
   381                     response.getWriter().write(encodeJSON(mi.html));
   382                     response.getWriter().write("'");
   383                 }
   384                 response.getWriter().write("}");
   385             }
   386         }, "/data");
   387 
   388         this.brwsr = launchServerAndBrwsr(server, "/execute");
   389     }
   390     
   391     private static String encodeJSON(String in) {
   392         StringBuilder sb = new StringBuilder();
   393         for (int i = 0; i < in.length(); i++) {
   394             char ch = in.charAt(i);
   395             if (ch < 32 || ch == '\'' || ch == '"') {
   396                 sb.append("\\u");
   397                 String hs = "0000" + Integer.toHexString(ch);
   398                 hs = hs.substring(hs.length() - 4);
   399                 sb.append(hs);
   400             } else {
   401                 sb.append(ch);
   402             }
   403         }
   404         return sb.toString();
   405     }
   406     
   407     @Override
   408     public void shutdown() throws IOException {
   409         methods.offer(END);
   410         for (;;) {
   411             int prev = methods.size();
   412             try {
   413                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   414                     break;
   415                 }
   416             } catch (InterruptedException ex) {
   417                 throw new IOException(ex);
   418             }
   419             if (prev == methods.size()) {
   420                 LOG.log(
   421                     Level.WARNING, 
   422                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   423                     methods.size()
   424                 );
   425                 break;
   426             }
   427             LOG.log(Level.INFO, 
   428                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   429                 new Object[]{prev, methods.size()}
   430             );
   431         }
   432         stopServerAndBrwsr(server, brwsr);
   433     }
   434     
   435     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   436         for (;;) {
   437             int ch = is.read();
   438             if (ch == -1) {
   439                 break;
   440             }
   441             if (ch == '$' && params.length > 0) {
   442                 int cnt = is.read() - '0';
   443                 if (baseURL != null && cnt == 'U' - '0') {
   444                     os.write(baseURL.getBytes("UTF-8"));
   445                 } else {
   446                     if (cnt >= 0 && cnt < params.length) {
   447                         os.write(params[cnt].getBytes("UTF-8"));
   448                     } else {
   449                         os.write('$');
   450                         os.write(cnt + '0');
   451                     }
   452                 }
   453             } else {
   454                 os.write(ch);
   455             }
   456         }
   457     }
   458 
   459     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   460         server.start();
   461         URI uri = pageURL("http", server, page);
   462         return showBrwsr(uri);
   463     }
   464     private static String toUTF8(String value) throws UnsupportedEncodingException {
   465         byte[] arr = new byte[value.length()];
   466         for (int i = 0; i < arr.length; i++) {
   467             arr[i] = (byte)value.charAt(i);
   468         }
   469         return new String(arr, "UTF-8");
   470     }
   471     
   472     private static String decodeURL(String s) {
   473         for (;;) {
   474             int pos = s.indexOf('%');
   475             if (pos == -1) {
   476                 return s;
   477             }
   478             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   479             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   480         }
   481     }
   482     
   483     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   484         if (brwsr == null) {
   485             return;
   486         }
   487         Process process = (Process)brwsr[0];
   488         
   489         server.stop();
   490         InputStream stdout = process.getInputStream();
   491         InputStream stderr = process.getErrorStream();
   492         drain("StdOut", stdout);
   493         drain("StdErr", stderr);
   494         process.destroy();
   495         int res;
   496         try {
   497             res = process.waitFor();
   498         } catch (InterruptedException ex) {
   499             throw new IOException(ex);
   500         }
   501         LOG.log(Level.INFO, "Exit code: {0}", res);
   502 
   503         deleteTree((File)brwsr[1]);
   504     }
   505     
   506     private static void drain(String name, InputStream is) throws IOException {
   507         int av = is.available();
   508         if (av > 0) {
   509             StringBuilder sb = new StringBuilder();
   510             sb.append("v== ").append(name).append(" ==v\n");
   511             while (av-- > 0) {
   512                 sb.append((char)is.read());
   513             }
   514             sb.append("\n^== ").append(name).append(" ==^");
   515             LOG.log(Level.INFO, sb.toString());
   516         }
   517     }
   518 
   519     private void deleteTree(File file) {
   520         if (file == null) {
   521             return;
   522         }
   523         File[] arr = file.listFiles();
   524         if (arr != null) {
   525             for (File s : arr) {
   526                 deleteTree(s);
   527             }
   528         }
   529         file.delete();
   530     }
   531 
   532     @Override
   533     public HttpServer call() throws Exception {
   534         return server;
   535     }
   536     
   537     @Override
   538     public void close() throws IOException {
   539         shutdown();
   540     }
   541 
   542     protected Object[] showBrwsr(URI uri) throws IOException {
   543         LOG.log(Level.INFO, "Showing {0}", uri);
   544         if (cmd == null) {
   545             try {
   546                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   547                     System.getProperty("java.vm.name"),
   548                     System.getProperty("java.vm.vendor"),
   549                     System.getProperty("java.vm.version"),
   550                 });
   551                 java.awt.Desktop.getDesktop().browse(uri);
   552                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   553                 return null;
   554             } catch (UnsupportedOperationException ex) {
   555                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   556                 LOG.log(Level.FINE, null, ex);
   557             } catch (IOException ex) {
   558                 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
   559                 LOG.log(Level.FINE, null, ex);
   560             }
   561         }
   562         {
   563             String cmdName = cmd == null ? "xdg-open" : cmd;
   564             String[] cmdArr = { 
   565                 cmdName, uri.toString()
   566             };
   567             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   568             final Process process = Runtime.getRuntime().exec(cmdArr);
   569             return new Object[] { process, null };
   570         }
   571     }
   572 
   573     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   574     abstract String harnessResource();
   575     Object compileJar(URL jar, URL precompiled) throws IOException {
   576         return null;
   577     }
   578     String compileFromClassPath(URL f, Res loader) throws IOException {
   579         return null;
   580     }
   581 
   582     private static URI pageURL(String protocol, HttpServer server, final String page) {
   583         NetworkListener listener = server.getListeners().iterator().next();
   584         int port = listener.getPort();
   585         try {
   586             return new URI(protocol + "://localhost:" + port + page);
   587         } catch (URISyntaxException ex) {
   588             throw new IllegalStateException(ex);
   589         }
   590     }
   591 
   592     final class Res {
   593         private final Set<URL> ignore = new HashSet<URL>();
   594         
   595         Object compileJar(URL jarURL) throws IOException {
   596             List<String[]> libraries = new ArrayList<String[]>();
   597             for (ClassLoader loader : loaders) {
   598                 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
   599                 while (en.hasMoreElements()) {
   600                     URL e = en.nextElement();
   601                     Manifest mf = new Manifest(e.openStream());
   602                     for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
   603                         String key = entrySet.getKey();
   604                         Attributes attr = entrySet.getValue();
   605                         
   606                         final String a = attr.getValue("Bck2BrwsrArtifactId");
   607                         final String g = attr.getValue("Bck2BrwsrGroupId");
   608                         final String v = attr.getValue("Bck2BrwsrVersion");
   609                         final String d = attr.getValue("Bck2BrwsrDebug");
   610                         
   611                         if (g != null && a != null && v != null && "true".equals(d)) {
   612                             libraries.add(new String[] {
   613                                 a, g, v, key
   614                             });
   615                         }
   616                     }
   617                 }
   618             }
   619             URL precompiled = null;
   620             for (ClassLoader loader : loaders) {
   621                 for (String[] lib : libraries) {
   622                     final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
   623                     URL props = loader.getResource(res);
   624                     if (props != null) {
   625                         URLConnection c = props.openConnection();
   626                         Properties load = new Properties();
   627                         final InputStream is = c.getInputStream();
   628                         load.load(is);
   629                         is.close();
   630                         if (lib[2].equals(load.getProperty("version"))) {
   631                             if (c instanceof JarURLConnection) {
   632                                 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
   633                                 if (definedInURL.equals(jarURL)) {
   634                                     precompiled = loader.getResource(lib[3]);
   635                                 }
   636                             }
   637                         }
   638                     }
   639                 }
   640             }
   641             Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
   642             ignore.add(jarURL);
   643             return ret;
   644         }
   645         String compileFromClassPath(URL f) throws IOException {
   646             return BaseHTTPLauncher.this.compileFromClassPath(f, this);
   647         }
   648         public URL get(String resource, int skip) throws IOException {
   649             if (!resource.endsWith(".class")) {
   650                 return getResource(resource, skip);
   651             }
   652             URL u = null;
   653             for (ClassLoader l : loaders) {
   654                 Enumeration<URL> en = l.getResources(resource);
   655                 while (en.hasMoreElements()) {
   656                     u = en.nextElement();
   657                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   658                         return u;
   659                     }
   660                 }
   661             }
   662             if (u != null) {
   663                 if (u.toExternalForm().contains("rt.jar")) {
   664                     LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
   665                     return null;
   666                 }
   667                 return u;
   668             }
   669             throw new IOException("Can't find " + resource);
   670         }
   671         private URL getResource(String resource, int skip) throws IOException {
   672             for (ClassLoader l : loaders) {
   673                 Enumeration<URL> en = l.getResources(resource);
   674                 while (en.hasMoreElements()) {
   675                     final URL now = en.nextElement();
   676                     if (now.toExternalForm().contains("sisu-inject-bean")) {
   677                         // certainly we don't want this resource, as that
   678                         // module is not compiled with target 1.6, currently
   679                         continue;
   680                     }
   681                     if (now.getProtocol().equals("jar")) {
   682                         JarURLConnection juc = (JarURLConnection) now.openConnection();
   683                         if (ignore.contains(juc.getJarFileURL())) {
   684                             continue;
   685                         }
   686                     }
   687                     if (--skip < 0) {
   688                         return now;
   689                     }
   690                 }
   691             }
   692             throw new IOException("Not found (anymore of) " + resource);
   693         }
   694     }
   695 
   696     private static class Page extends HttpHandler {
   697         final String resource;
   698         private final String[] args;
   699         private final Res res;
   700         
   701         public Page(Res res, String resource, String... args) {
   702             this.res = res;
   703             this.resource = resource;
   704             this.args = args.length == 0 ? new String[] { "$0" } : args;
   705         }
   706 
   707         @Override
   708         public void service(Request request, Response response) throws Exception {
   709             String r = computePage(request);
   710             if (r.startsWith("/")) {
   711                 r = r.substring(1);
   712             }
   713             String[] replace = {};
   714             if (r.endsWith(".html")) {
   715                 response.setContentType("text/html");
   716                 LOG.info("Content type text/html");
   717                 replace = args;
   718             }
   719             if (r.endsWith(".xhtml")) {
   720                 response.setContentType("application/xhtml+xml");
   721                 LOG.info("Content type application/xhtml+xml");
   722                 replace = args;
   723             }
   724             OutputStream os = response.getOutputStream();
   725             try { 
   726                 InputStream is = res.get(r, 0).openStream();
   727                 copyStream(is, os, request.getRequestURL().toString(), replace);
   728             } catch (IOException ex) {
   729                 response.setDetailMessage(ex.getLocalizedMessage());
   730                 response.setError();
   731                 response.setStatus(404);
   732             }
   733         }
   734 
   735         protected String computePage(Request request) {
   736             String r = resource;
   737             if (r == null) {
   738                 r = request.getHttpHandlerPath();
   739             }
   740             return r;
   741         }
   742     }
   743     
   744     private static class SubTree extends Page {
   745 
   746         public SubTree(Res res, String resource, String... args) {
   747             super(res, resource, args);
   748         }
   749 
   750         @Override
   751         protected String computePage(Request request) {
   752             return resource + request.getHttpHandlerPath();
   753         }
   754         
   755         
   756     }
   757 
   758     private class VMAndPages extends StaticHttpHandler {
   759         private String vmResource;
   760         
   761         public VMAndPages() {
   762             super((String[]) null);
   763         }
   764         
   765         @Override
   766         public void service(Request request, Response response) throws Exception {
   767             if (request.getRequestURI().equals(vmResource)) {
   768                 response.setCharacterEncoding("UTF-8");
   769                 response.setContentType("text/javascript");
   770                 StringBuilder sb = new StringBuilder();
   771                 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   772                 response.getWriter().write(sb.toString());
   773             } else {
   774                 super.service(request, response);
   775             }
   776         }
   777 
   778         private void registerVM(String vmResource) {
   779             this.vmResource = vmResource;
   780         }
   781     }
   782 
   783     private static class Classes extends HttpHandler {
   784         private final Res loader;
   785 
   786         public Classes(Res loader) {
   787             this.loader = loader;
   788         }
   789 
   790         @Override
   791         public void service(Request request, Response response) throws Exception {
   792             String res = request.getHttpHandlerPath();
   793             if (res.startsWith("/")) {
   794                 res = res.substring(1);
   795             }
   796             String skip = request.getParameter("skip");
   797             int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
   798             URL url = loader.get(res, skipCnt);
   799             if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
   800                 response.setCharacterEncoding("UTF-8");
   801                 if (url.getProtocol().equals("jar")) {
   802                     JarURLConnection juc = (JarURLConnection) url.openConnection();
   803                     Object s = null;
   804                     try {
   805                         s = loader.compileJar(juc.getJarFileURL());
   806                     } catch (IOException iOException) {
   807                         throw new IOException("Can't compile " + url.toExternalForm(), iOException);
   808                     }
   809                     if (s instanceof String) {
   810                         Writer w = response.getWriter();
   811                         w.append((String)s);
   812                         w.close();
   813                         return;
   814                     }
   815                     if (s instanceof InputStream) {
   816                         copyStream((InputStream) s, response.getOutputStream(), null);
   817                         return;
   818                     }
   819                 }
   820                 if (url.getProtocol().equals("file")) {
   821                     final String filePart = url.getFile();
   822                     if (filePart.endsWith(res)) {
   823                         url = new URL(
   824                             url.getProtocol(), 
   825                             url.getHost(), 
   826                             url.getPort(), 
   827                             filePart.substring(0, filePart.length() - res.length())
   828                         );
   829                     }
   830                     String s = loader.compileFromClassPath(url);
   831                     if (s != null) {
   832                         Writer w = response.getWriter();
   833                         w.append(s);
   834                         w.close();
   835                         return;
   836                     }
   837                 }
   838             } catch (IOException ex) {
   839                 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
   840             }
   841             InputStream is = null;
   842             try {
   843                 if (url == null) {
   844                     throw new IOException("Resource not found");
   845                 }
   846                 is = url.openStream();
   847                 response.setContentType("text/javascript");
   848                 Writer w = response.getWriter();
   849                 w.append("([");
   850                 for (int i = 0;; i++) {
   851                     int b = is.read();
   852                     if (b == -1) {
   853                         break;
   854                     }
   855                     if (i > 0) {
   856                         w.append(", ");
   857                     }
   858                     if (i % 20 == 0) {
   859                         w.write("\n");
   860                     }
   861                     if (b > 127) {
   862                         b = b - 256;
   863                     }
   864                     w.append(Integer.toString(b));
   865                 }
   866                 w.append("\n])");
   867             } catch (IOException ex) {
   868                 response.setStatus(HttpStatus.NOT_FOUND_404);
   869                 response.setError();
   870                 response.setDetailMessage(ex.getMessage());
   871             } finally {
   872                 if (is != null) {
   873                     is.close();
   874                 }
   875             }
   876         }
   877 
   878     }
   879     private static class WS extends WebSocketApplication {
   880 
   881         private final Resource r;
   882 
   883         private WS(Resource r) {
   884             this.r = r;
   885         }
   886 
   887         @Override
   888         public void onMessage(WebSocket socket, String text) {
   889             try {
   890                 r.httpContent.reset();
   891                 ByteArrayOutputStream out = new ByteArrayOutputStream();
   892                 copyStream(r.httpContent, out, null, text);
   893                 String s = new String(out.toByteArray(), "UTF-8");
   894                 socket.send(s);
   895             } catch (IOException ex) {
   896                 LOG.log(Level.WARNING, null, ex);
   897             }
   898         }
   899 
   900     }}