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