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