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