launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Jan 2016 04:36:23 +0100
changeset 1860 4ce38f21f4cd
parent 1850 23babc7d5bb8
child 1908 4f4554f69892
permissions -rw-r--r--
JavaScript in a browser can be at most three times slower than HotSpot when computing five or ten thousands of prime numbers
     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                 if (mi == END) {
   381                     response.getWriter().write("");
   382                     wait.countDown();
   383                     cnt = 0;
   384                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   385                     return;
   386                 }
   387                 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
   388                 if (prev != null) {
   389                     prev.close(newRH);
   390                 }
   391                 prev = newRH;
   392                 conf.addHttpHandler(prev, "/dynamic");
   393 
   394                 cases.add(mi);
   395                 final String cn = mi.clazz.getName();
   396                 final String mn = mi.methodName;
   397                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   398                 response.getWriter().write("{"
   399                     + "className: '" + cn + "', "
   400                     + "methodName: '" + mn + "', "
   401                     + "request: " + caseNmbr
   402                 );
   403                 if (mi.html != null) {
   404                     response.getWriter().write(", html: '");
   405                     response.getWriter().write(encodeJSON(mi.html));
   406                     response.getWriter().write("'");
   407                 }
   408                 response.getWriter().write("}");
   409             }
   410         }, "/data");
   411 
   412         this.brwsr = launchServerAndBrwsr(server, "/execute");
   413     }
   414 
   415     private static String encodeJSON(String in) {
   416         StringBuilder sb = new StringBuilder();
   417         for (int i = 0; i < in.length(); i++) {
   418             char ch = in.charAt(i);
   419             if (ch < 32 || ch == '\'' || ch == '"') {
   420                 sb.append("\\u");
   421                 String hs = "0000" + Integer.toHexString(ch);
   422                 hs = hs.substring(hs.length() - 4);
   423                 sb.append(hs);
   424             } else {
   425                 sb.append(ch);
   426             }
   427         }
   428         return sb.toString();
   429     }
   430 
   431     @Override
   432     public void shutdown() throws IOException {
   433         synchronized (this) {
   434             if (flushing != null) {
   435                 flushing.interrupt();
   436                 flushing = null;
   437             }
   438         }
   439         methods.offer(END);
   440         for (;;) {
   441             int prev = methods.size();
   442             try {
   443                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   444                     break;
   445                 }
   446             } catch (InterruptedException ex) {
   447                 throw new IOException(ex);
   448             }
   449             if (prev == methods.size()) {
   450                 LOG.log(
   451                     Level.WARNING,
   452                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
   453                     methods.size()
   454                 );
   455                 break;
   456             }
   457             LOG.log(Level.INFO,
   458                 "Timeout, but tests got from {0} to {1}. Trying again.",
   459                 new Object[]{prev, methods.size()}
   460             );
   461         }
   462         stopServerAndBrwsr(server, brwsr);
   463     }
   464 
   465     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   466         for (;;) {
   467             int ch = is.read();
   468             if (ch == -1) {
   469                 break;
   470             }
   471             if (ch == '$' && params.length > 0) {
   472                 int cnt = is.read() - '0';
   473                 if (baseURL != null && cnt == 'U' - '0') {
   474                     os.write(baseURL.getBytes("UTF-8"));
   475                 } else {
   476                     if (cnt >= 0 && cnt < params.length) {
   477                         os.write(params[cnt].getBytes("UTF-8"));
   478                     } else {
   479                         os.write('$');
   480                         os.write(cnt + '0');
   481                     }
   482                 }
   483             } else {
   484                 os.write(ch);
   485             }
   486         }
   487     }
   488 
   489     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   490         server.start();
   491         URI uri = pageURL("http", server, page);
   492         return showBrwsr(uri);
   493     }
   494     private static String toUTF8(String value) throws UnsupportedEncodingException {
   495         byte[] arr = new byte[value.length()];
   496         for (int i = 0; i < arr.length; i++) {
   497             arr[i] = (byte)value.charAt(i);
   498         }
   499         return new String(arr, "UTF-8");
   500     }
   501 
   502     private static String decodeURL(String s) {
   503         for (;;) {
   504             int pos = s.indexOf('%');
   505             if (pos == -1) {
   506                 return s;
   507             }
   508             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   509             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   510         }
   511     }
   512 
   513     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   514         if (brwsr == null) {
   515             return;
   516         }
   517         Process process = (Process)brwsr[0];
   518 
   519         server.stop();
   520         InputStream stdout = process.getInputStream();
   521         InputStream stderr = process.getErrorStream();
   522         drain("StdOut", stdout);
   523         drain("StdErr", stderr);
   524         process.destroy();
   525         int res;
   526         try {
   527             res = process.waitFor();
   528         } catch (InterruptedException ex) {
   529             throw new IOException(ex);
   530         }
   531         LOG.log(Level.INFO, "Exit code: {0}", res);
   532 
   533         deleteTree((File)brwsr[1]);
   534     }
   535 
   536     private static void drain(String name, InputStream is) throws IOException {
   537         int av = is.available();
   538         if (av > 0) {
   539             StringBuilder sb = new StringBuilder();
   540             sb.append("v== ").append(name).append(" ==v\n");
   541             while (av-- > 0) {
   542                 sb.append((char)is.read());
   543             }
   544             sb.append("\n^== ").append(name).append(" ==^");
   545             LOG.log(Level.INFO, sb.toString());
   546         }
   547     }
   548 
   549     private void deleteTree(File file) {
   550         if (file == null) {
   551             return;
   552         }
   553         File[] arr = file.listFiles();
   554         if (arr != null) {
   555             for (File s : arr) {
   556                 deleteTree(s);
   557             }
   558         }
   559         file.delete();
   560     }
   561 
   562     @Override
   563     public HttpServer call() throws Exception {
   564         return server;
   565     }
   566 
   567     @Override
   568     public synchronized void flush() throws IOException {
   569         flushing = Thread.currentThread();
   570         while (flushing == Thread.currentThread()) {
   571             try {
   572                 wait();
   573             } catch (InterruptedException ex) {
   574                 LOG.log(Level.FINE, null, ex);
   575             }
   576         }
   577     }
   578 
   579     @Override
   580     public void close() throws IOException {
   581         shutdown();
   582     }
   583 
   584     protected Object[] showBrwsr(URI uri) throws IOException {
   585         LOG.log(Level.INFO, "Showing {0}", uri);
   586         if (cmd == null) {
   587             try {
   588                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   589                     System.getProperty("java.vm.name"),
   590                     System.getProperty("java.vm.vendor"),
   591                     System.getProperty("java.vm.version"),
   592                 });
   593                 java.awt.Desktop.getDesktop().browse(uri);
   594                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   595                 return null;
   596             } catch (UnsupportedOperationException ex) {
   597                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   598                 LOG.log(Level.FINE, null, ex);
   599             } catch (IOException ex) {
   600                 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
   601                 LOG.log(Level.FINE, null, ex);
   602             }
   603         }
   604         {
   605             String cmdName = cmd == null ? "xdg-open" : cmd;
   606             String[] cmdArr = {
   607                 cmdName, uri.toString()
   608             };
   609             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   610             final Process process = Runtime.getRuntime().exec(cmdArr);
   611             return new Object[] { process, null };
   612         }
   613     }
   614 
   615     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   616     abstract String harnessResource();
   617     Object compileJar(URL jar, URL precompiled) throws IOException {
   618         return null;
   619     }
   620     String compileFromClassPath(URL f, Res loader) throws IOException {
   621         return null;
   622     }
   623 
   624     private static URI pageURL(String protocol, HttpServer server, final String page) {
   625         NetworkListener listener = server.getListeners().iterator().next();
   626         int port = listener.getPort();
   627         try {
   628             return new URI(protocol + "://localhost:" + port + page);
   629         } catch (URISyntaxException ex) {
   630             throw new IllegalStateException(ex);
   631         }
   632     }
   633 
   634     final class Res {
   635         private final Set<URL> ignore = new HashSet<URL>();
   636 
   637         Object compileJar(URL jarURL) throws IOException {
   638             List<String[]> libraries = new ArrayList<String[]>();
   639             for (ClassLoader loader : loaders) {
   640                 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
   641                 while (en.hasMoreElements()) {
   642                     URL e = en.nextElement();
   643                     Manifest mf = new Manifest(e.openStream());
   644                     for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
   645                         String key = entrySet.getKey();
   646                         Attributes attr = entrySet.getValue();
   647 
   648                         final String a = attr.getValue("Bck2BrwsrArtifactId");
   649                         final String g = attr.getValue("Bck2BrwsrGroupId");
   650                         final String v = attr.getValue("Bck2BrwsrVersion");
   651                         final String d = attr.getValue("Bck2BrwsrDebug");
   652 
   653                         if (g != null && a != null && v != null && "true".equals(d)) {
   654                             libraries.add(new String[] {
   655                                 a, g, v, key
   656                             });
   657                         }
   658                     }
   659                 }
   660             }
   661             URL precompiled = null;
   662             for (ClassLoader loader : loaders) {
   663                 for (String[] lib : libraries) {
   664                     final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
   665                     URL props = loader.getResource(res);
   666                     if (props != null) {
   667                         URLConnection c = props.openConnection();
   668                         Properties load = new Properties();
   669                         final InputStream is = c.getInputStream();
   670                         load.load(is);
   671                         is.close();
   672                         if (lib[2].equals(load.getProperty("version"))) {
   673                             if (c instanceof JarURLConnection) {
   674                                 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
   675                                 if (definedInURL.equals(jarURL)) {
   676                                     precompiled = loader.getResource(lib[3]);
   677                                 }
   678                             }
   679                         }
   680                     }
   681                 }
   682             }
   683             Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
   684             ignore.add(jarURL);
   685             return ret;
   686         }
   687         String compileFromClassPath(URL f) throws IOException {
   688             return BaseHTTPLauncher.this.compileFromClassPath(f, this);
   689         }
   690         public URL get(String resource, int skip) throws IOException {
   691             if (!resource.endsWith(".class")) {
   692                 return getResource(resource, skip);
   693             }
   694             URL u = null;
   695             for (ClassLoader l : loaders) {
   696                 Enumeration<URL> en = l.getResources(resource);
   697                 while (en.hasMoreElements()) {
   698                     u = en.nextElement();
   699                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   700                         return u;
   701                     }
   702                 }
   703             }
   704             if (u != null) {
   705                 if (u.toExternalForm().contains("rt.jar")) {
   706                     LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
   707                     return null;
   708                 }
   709                 return u;
   710             }
   711             throw new IOException("Can't find " + resource);
   712         }
   713         private URL getResource(String resource, int skip) throws IOException {
   714             for (ClassLoader l : loaders) {
   715                 Enumeration<URL> en = l.getResources(resource);
   716                 while (en.hasMoreElements()) {
   717                     final URL now = en.nextElement();
   718                     if (now.toExternalForm().contains("sisu-inject-bean")) {
   719                         // certainly we don't want this resource, as that
   720                         // module is not compiled with target 1.6, currently
   721                         continue;
   722                     }
   723                     if (now.getProtocol().equals("jar")) {
   724                         JarURLConnection juc = (JarURLConnection) now.openConnection();
   725                         if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
   726                             continue;
   727                         }
   728                     }
   729                     if (--skip < 0) {
   730                         return now;
   731                     }
   732                 }
   733             }
   734             throw new IOException("Not found (anymore of) " + resource);
   735         }
   736     }
   737 
   738     private static class Page extends HttpHandler {
   739         final String resource;
   740         private final String[] args;
   741         private final Res res;
   742 
   743         public Page(Res res, String resource, String... args) {
   744             this.res = res;
   745             this.resource = resource;
   746             this.args = args.length == 0 ? new String[] { "$0" } : args;
   747         }
   748 
   749         @Override
   750         public void service(Request request, Response response) throws Exception {
   751             String r = computePage(request);
   752             if (r.startsWith("/")) {
   753                 r = r.substring(1);
   754             }
   755             String[] replace = {};
   756             if (r.endsWith(".html")) {
   757                 response.setContentType("text/html");
   758                 LOG.info("Content type text/html");
   759                 replace = args;
   760             }
   761             if (r.endsWith(".xhtml")) {
   762                 response.setContentType("application/xhtml+xml");
   763                 LOG.info("Content type application/xhtml+xml");
   764                 replace = args;
   765             }
   766             OutputStream os = response.getOutputStream();
   767             try {
   768                 InputStream is = res.get(r, 0).openStream();
   769                 copyStream(is, os, request.getRequestURL().toString(), replace);
   770             } catch (IOException ex) {
   771                 response.setDetailMessage(ex.getLocalizedMessage());
   772                 response.setError();
   773                 response.setStatus(404);
   774             }
   775         }
   776 
   777         protected String computePage(Request request) {
   778             String r = resource;
   779             if (r == null) {
   780                 r = request.getHttpHandlerPath();
   781             }
   782             return r;
   783         }
   784     }
   785 
   786     private static class SubTree extends Page {
   787 
   788         public SubTree(Res res, String resource, String... args) {
   789             super(res, resource, args);
   790         }
   791 
   792         @Override
   793         protected String computePage(Request request) {
   794             return resource + request.getHttpHandlerPath();
   795         }
   796 
   797 
   798     }
   799 
   800     private class VMAndPages extends StaticHttpHandler {
   801         private String vmResource;
   802 
   803         public VMAndPages() {
   804             super((String[]) null);
   805         }
   806 
   807         @Override
   808         public void service(Request request, Response response) throws Exception {
   809             if ("true".equals(request.getParameter("exit"))) {
   810                 LOG.info("Exit request received. Shutting down!");
   811                 shutdown();
   812             }
   813             if (request.getRequestURI().equals(vmResource)) {
   814                 response.setCharacterEncoding("UTF-8");
   815                 response.setContentType("text/javascript");
   816                 StringBuilder sb = new StringBuilder();
   817                 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   818                 response.getWriter().write(sb.toString());
   819             } else {
   820                 super.service(request, response);
   821             }
   822         }
   823 
   824         private void registerVM(String vmResource) {
   825             this.vmResource = vmResource;
   826         }
   827     }
   828 
   829     private static class Classes extends HttpHandler {
   830         private final Res loader;
   831 
   832         public Classes(Res loader) {
   833             this.loader = loader;
   834         }
   835 
   836         @Override
   837         public void service(Request request, Response response) throws Exception {
   838             String res = request.getHttpHandlerPath();
   839             if (res.startsWith("/")) {
   840                 res = res.substring(1);
   841             }
   842             String skip = request.getParameter("skip");
   843             int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
   844             URL url = loader.get(res, skipCnt);
   845             if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
   846                 response.setCharacterEncoding("UTF-8");
   847                 if (url.getProtocol().equals("jar")) {
   848                     JarURLConnection juc = (JarURLConnection) url.openConnection();
   849                     Object s = null;
   850                     try {
   851                         s = loader.compileJar(juc.getJarFileURL());
   852                     } catch (IOException iOException) {
   853                         throw new IOException("Can't compile " + url.toExternalForm(), iOException);
   854                     }
   855                     if (s instanceof String) {
   856                         Writer w = response.getWriter();
   857                         w.append((String)s);
   858                         w.close();
   859                         return;
   860                     }
   861                     if (s instanceof InputStream) {
   862                         copyStream((InputStream) s, response.getOutputStream(), null);
   863                         return;
   864                     }
   865                 }
   866                 if (url.getProtocol().equals("file")) {
   867                     final String filePart = url.getFile();
   868                     if (filePart.endsWith(res)) {
   869                         url = new URL(
   870                             url.getProtocol(),
   871                             url.getHost(),
   872                             url.getPort(),
   873                             filePart.substring(0, filePart.length() - res.length())
   874                         );
   875                     }
   876                     String s = loader.compileFromClassPath(url);
   877                     if (s != null) {
   878                         Writer w = response.getWriter();
   879                         w.append(s);
   880                         w.close();
   881                         return;
   882                     }
   883                 }
   884             } catch (IOException ex) {
   885                 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
   886             }
   887             InputStream is = null;
   888             try {
   889                 if (url == null) {
   890                     throw new IOException("Resource not found");
   891                 }
   892                 is = url.openStream();
   893                 response.setContentType("text/javascript");
   894                 Writer w = response.getWriter();
   895                 w.append("([");
   896                 for (int i = 0;; i++) {
   897                     int b = is.read();
   898                     if (b == -1) {
   899                         break;
   900                     }
   901                     if (i > 0) {
   902                         w.append(", ");
   903                     }
   904                     if (i % 20 == 0) {
   905                         w.write("\n");
   906                     }
   907                     if (b > 127) {
   908                         b = b - 256;
   909                     }
   910                     w.append(Integer.toString(b));
   911                 }
   912                 w.append("\n])");
   913             } catch (IOException ex) {
   914                 response.setStatus(HttpStatus.NOT_FOUND_404);
   915                 response.setError();
   916                 response.setDetailMessage(ex.getMessage());
   917             } finally {
   918                 if (is != null) {
   919                     is.close();
   920                 }
   921             }
   922         }
   923 
   924     }
   925     private static class WS extends WebSocketApplication {
   926 
   927         private final Resource r;
   928 
   929         private WS(Resource r) {
   930             this.r = r;
   931         }
   932 
   933         @Override
   934         public void onMessage(WebSocket socket, String text) {
   935             try {
   936                 r.httpContent.reset();
   937                 ByteArrayOutputStream out = new ByteArrayOutputStream();
   938                 copyStream(r.httpContent, out, null, text);
   939                 String s = new String(out.toByteArray(), "UTF-8");
   940                 socket.send(s);
   941             } catch (IOException ex) {
   942                 LOG.log(Level.WARNING, null, ex);
   943             }
   944         }
   945 
   946     }}