launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 03 Jun 2014 16:05:21 +0200
branchclosure
changeset 1614 8eba262bd8cd
parent 1599 36746c46716a
child 1615 80e39583b35d
permissions -rw-r--r--
Directly derive the parent root folder based on resource name rather than going through classpath
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.launcher;
    19 
    20 import java.io.ByteArrayInputStream;
    21 import java.io.ByteArrayOutputStream;
    22 import java.io.Closeable;
    23 import java.io.File;
    24 import java.io.IOException;
    25 import java.io.InputStream;
    26 import java.io.InterruptedIOException;
    27 import java.io.OutputStream;
    28 import java.io.Reader;
    29 import java.io.UnsupportedEncodingException;
    30 import java.io.Writer;
    31 import java.net.JarURLConnection;
    32 import java.net.URI;
    33 import java.net.URISyntaxException;
    34 import java.net.URL;
    35 import java.util.ArrayList;
    36 import java.util.Arrays;
    37 import java.util.Enumeration;
    38 import java.util.HashSet;
    39 import java.util.LinkedHashSet;
    40 import java.util.List;
    41 import java.util.Set;
    42 import java.util.concurrent.BlockingQueue;
    43 import java.util.concurrent.Callable;
    44 import java.util.concurrent.CountDownLatch;
    45 import java.util.concurrent.LinkedBlockingQueue;
    46 import java.util.concurrent.TimeUnit;
    47 import java.util.jar.JarFile;
    48 import java.util.logging.Level;
    49 import java.util.logging.Logger;
    50 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
    51 import org.glassfish.grizzly.PortRange;
    52 import org.glassfish.grizzly.http.server.HttpHandler;
    53 import org.glassfish.grizzly.http.server.HttpServer;
    54 import org.glassfish.grizzly.http.server.NetworkListener;
    55 import org.glassfish.grizzly.http.server.Request;
    56 import org.glassfish.grizzly.http.server.Response;
    57 import org.glassfish.grizzly.http.server.ServerConfiguration;
    58 import org.glassfish.grizzly.http.server.StaticHttpHandler;
    59 import org.glassfish.grizzly.http.util.HttpStatus;
    60 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
    61 import org.glassfish.grizzly.websockets.WebSocket;
    62 import org.glassfish.grizzly.websockets.WebSocketAddOn;
    63 import org.glassfish.grizzly.websockets.WebSocketApplication;
    64 import org.glassfish.grizzly.websockets.WebSocketEngine;
    65 
    66 /**
    67  * Lightweight server to launch Bck2Brwsr applications and tests.
    68  * Supports execution in native browser as well as Java's internal 
    69  * execution engine.
    70  */
    71 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
    72     static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
    73     private static final InvocationContext END = new InvocationContext(null, null, null);
    74     private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
    75     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
    76     private long timeOut;
    77     private final Res resources = new Res();
    78     private final String cmd;
    79     private Object[] brwsr;
    80     private HttpServer server;
    81     private CountDownLatch wait;
    82     
    83     public BaseHTTPLauncher(String cmd) {
    84         this.cmd = cmd;
    85         addClassLoader(BaseHTTPLauncher.class.getClassLoader());
    86         setTimeout(180000);
    87     }
    88     
    89     @Override
    90     InvocationContext runMethod(InvocationContext c) throws IOException {
    91         loaders.add(c.clazz.getClassLoader());
    92         methods.add(c);
    93         try {
    94             c.await(timeOut);
    95         } catch (InterruptedException ex) {
    96             throw new IOException(ex);
    97         }
    98         return c;
    99     }
   100     
   101     public void setTimeout(long ms) {
   102         timeOut = ms;
   103     }
   104     
   105     public void addClassLoader(ClassLoader url) {
   106         this.loaders.add(url);
   107     }
   108     
   109     ClassLoader[] loaders() {
   110         return loaders.toArray(new ClassLoader[loaders.size()]);
   111     }
   112 
   113     public void showURL(String startpage) throws IOException {
   114         if (!startpage.startsWith("/")) {
   115             startpage = "/" + startpage;
   116         }
   117         HttpServer s = initServer(".", true, "");
   118         int last = startpage.lastIndexOf('/');
   119         String prefix = startpage.substring(0, last);
   120         String simpleName = startpage.substring(last);
   121         s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
   122         server = s;
   123         try {
   124             launchServerAndBrwsr(s, simpleName);
   125         } catch (Exception ex) {
   126             throw new IOException(ex);
   127         }
   128     }
   129 
   130     void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
   131         if (!startpage.startsWith("/")) {
   132             startpage = "/" + startpage;
   133         }
   134         String prefix = "";
   135         int last = startpage.lastIndexOf('/');
   136         if (last >= 0) {
   137             prefix = startpage.substring(0, last);
   138         }
   139         HttpServer s = initServer(dir.getPath(), addClasses, prefix);
   140         try {
   141             launchServerAndBrwsr(s, startpage);
   142         } catch (Exception ex) {
   143             throw new IOException(ex);
   144         }
   145     }
   146 
   147     @Override
   148     public void initialize() throws IOException {
   149         try {
   150             executeInBrowser();
   151         } catch (InterruptedException ex) {
   152             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   153             iio.initCause(ex);
   154             throw iio;
   155         } catch (Exception ex) {
   156             if (ex instanceof IOException) {
   157                 throw (IOException)ex;
   158             }
   159             if (ex instanceof RuntimeException) {
   160                 throw (RuntimeException)ex;
   161             }
   162             throw new IOException(ex);
   163         }
   164     }
   165     
   166     private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
   167         HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
   168         /*
   169         ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
   170             setPoolName("Fx/Bck2 Brwsr").
   171             setCorePoolSize(3).
   172             setMaxPoolSize(5);
   173         ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
   174             setPoolName("Kernel Fx/Bck2").
   175             setCorePoolSize(3).
   176             setMaxPoolSize(3);
   177         for (NetworkListener nl : s.getListeners()) {
   178             nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
   179             nl.getTransport().setKernelThreadPoolConfig(oneKernel);
   180         }
   181 */        
   182         final ServerConfiguration conf = s.getServerConfiguration();
   183         VMAndPages vm = new VMAndPages();
   184         conf.addHttpHandler(vm, "/");
   185         if (vmPrefix != null) {
   186             vm.registerVM(vmPrefix + "/bck2brwsr.js");
   187         }
   188         if (path != null) {
   189             vm.addDocRoot(path);
   190         }
   191         if (addClasses) {
   192             conf.addHttpHandler(new Classes(resources), "/classes/");
   193         }
   194         final WebSocketAddOn addon = new WebSocketAddOn();
   195         for (NetworkListener listener : s.getListeners()) {
   196             listener.registerAddOn(addon);
   197         }
   198         return s;
   199     }
   200     
   201     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   202         wait = new CountDownLatch(1);
   203         server = initServer(".", true, "");
   204         final ServerConfiguration conf = server.getServerConfiguration();
   205         
   206         class DynamicResourceHandler extends HttpHandler {
   207             private final InvocationContext ic;
   208             private int resourcesCount;
   209             DynamicResourceHandler delegate;
   210             public DynamicResourceHandler(InvocationContext ic) {
   211                 this.ic = ic;
   212                 for (Resource r : ic.resources) {
   213                     conf.addHttpHandler(this, r.httpPath);
   214                 }
   215             }
   216 
   217             public void close(DynamicResourceHandler del) {
   218                 conf.removeHttpHandler(this);
   219                 delegate = del;
   220             }
   221             
   222             @Override
   223             public void service(Request request, Response response) throws Exception {
   224                 if (delegate != null) {
   225                     delegate.service(request, response);
   226                     return;
   227                 }
   228                 
   229                 if ("/dynamic".equals(request.getRequestURI())) {
   230                     boolean webSocket = false;
   231                     String mimeType = request.getParameter("mimeType");
   232                     List<String> params = new ArrayList<String>();
   233                     for (int i = 0; ; i++) {
   234                         String p = request.getParameter("param" + i);
   235                         if (p == null) {
   236                             break;
   237                         }
   238                         params.add(p);
   239                         if ("protocol:ws".equals(p)) {
   240                             webSocket = true;
   241                             continue;
   242                         }                    }
   243                     final String cnt = request.getParameter("content");
   244                     String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   245                     ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   246                     URI url;
   247                     final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   248                     if (webSocket) {
   249                         url = registerWebSocket(res);
   250                     } else {
   251                         url = registerResource(res);
   252                     }
   253                     response.getWriter().write(url.toString());
   254                     response.getWriter().write("\n");
   255                     return;
   256                 }
   257                 
   258                 for (Resource r : ic.resources) {
   259                     if (r.httpPath.equals(request.getRequestURI())) {
   260                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   261                         response.setContentType(r.httpType);
   262                         r.httpContent.reset();
   263                         String[] params = null;
   264                         if (r.parameters.length != 0) {
   265                             params = new String[r.parameters.length];
   266                             for (int i = 0; i < r.parameters.length; i++) {
   267                                 params[i] = request.getParameter(r.parameters[i]);
   268                                 if (params[i] == null) {
   269                                     if ("http.method".equals(r.parameters[i])) {
   270                                         params[i] = request.getMethod().toString();
   271                                     } else if ("http.requestBody".equals(r.parameters[i])) {
   272                                         Reader rdr = request.getReader();
   273                                         StringBuilder sb = new StringBuilder();
   274                                         for (;;) {
   275                                             int ch = rdr.read();
   276                                             if (ch == -1) {
   277                                                 break;
   278                                             }
   279                                             sb.append((char)ch);
   280                                         }
   281                                         params[i] = sb.toString();
   282                                     }
   283                                 }
   284                                 if (params[i] == null) {
   285                                     params[i] = "null";
   286                                 }
   287                             }
   288                         }
   289                         
   290                         copyStream(r.httpContent, response.getOutputStream(), null, params);
   291                     }
   292                 }
   293             }
   294             
   295             private URI registerWebSocket(Resource r) {
   296                 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   297                 return pageURL("ws", server, r.httpPath);
   298             }
   299 
   300             private URI registerResource(Resource r) {
   301                 if (!ic.resources.contains(r)) {
   302                     ic.resources.add(r);
   303                     conf.addHttpHandler(this, r.httpPath);
   304                 }
   305                 return pageURL("http", server, r.httpPath);
   306             }
   307         }
   308         
   309         conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
   310         
   311         conf.addHttpHandler(new HttpHandler() {
   312             int cnt;
   313             List<InvocationContext> cases = new ArrayList<InvocationContext>();
   314             DynamicResourceHandler prev;
   315             @Override
   316             public void service(Request request, Response response) throws Exception {
   317                 String id = request.getParameter("request");
   318                 String value = request.getParameter("result");
   319                 if (value != null && value.indexOf((char)0xC5) != -1) {
   320                     value = toUTF8(value);
   321                 }
   322                 
   323                 
   324                 InvocationContext mi = null;
   325                 int caseNmbr = -1;
   326                 
   327                 if (id != null && value != null) {
   328                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   329                     value = decodeURL(value);
   330                     int indx = Integer.parseInt(id);
   331                     cases.get(indx).result(value, null);
   332                     if (++indx < cases.size()) {
   333                         mi = cases.get(indx);
   334                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   335                         caseNmbr = indx;
   336                     }
   337                 } else {
   338                     if (!cases.isEmpty()) {
   339                         LOG.info("Re-executing test cases");
   340                         mi = cases.get(0);
   341                         caseNmbr = 0;
   342                     }
   343                 }
   344                 
   345                 if (mi == null) {
   346                     mi = methods.take();
   347                     caseNmbr = cnt++;
   348                 }
   349                 if (mi == END) {
   350                     response.getWriter().write("");
   351                     wait.countDown();
   352                     cnt = 0;
   353                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   354                     return;
   355                 }
   356                 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
   357                 if (prev != null) {
   358                     prev.close(newRH);
   359                 }
   360                 prev = newRH;
   361                 conf.addHttpHandler(prev, "/dynamic");
   362                 
   363                 cases.add(mi);
   364                 final String cn = mi.clazz.getName();
   365                 final String mn = mi.methodName;
   366                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   367                 response.getWriter().write("{"
   368                     + "className: '" + cn + "', "
   369                     + "methodName: '" + mn + "', "
   370                     + "request: " + caseNmbr
   371                 );
   372                 if (mi.html != null) {
   373                     response.getWriter().write(", html: '");
   374                     response.getWriter().write(encodeJSON(mi.html));
   375                     response.getWriter().write("'");
   376                 }
   377                 response.getWriter().write("}");
   378             }
   379         }, "/data");
   380 
   381         this.brwsr = launchServerAndBrwsr(server, "/execute");
   382     }
   383     
   384     private static String encodeJSON(String in) {
   385         StringBuilder sb = new StringBuilder();
   386         for (int i = 0; i < in.length(); i++) {
   387             char ch = in.charAt(i);
   388             if (ch < 32 || ch == '\'' || ch == '"') {
   389                 sb.append("\\u");
   390                 String hs = "0000" + Integer.toHexString(ch);
   391                 hs = hs.substring(hs.length() - 4);
   392                 sb.append(hs);
   393             } else {
   394                 sb.append(ch);
   395             }
   396         }
   397         return sb.toString();
   398     }
   399     
   400     @Override
   401     public void shutdown() throws IOException {
   402         methods.offer(END);
   403         for (;;) {
   404             int prev = methods.size();
   405             try {
   406                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   407                     break;
   408                 }
   409             } catch (InterruptedException ex) {
   410                 throw new IOException(ex);
   411             }
   412             if (prev == methods.size()) {
   413                 LOG.log(
   414                     Level.WARNING, 
   415                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   416                     methods.size()
   417                 );
   418                 break;
   419             }
   420             LOG.log(Level.INFO, 
   421                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   422                 new Object[]{prev, methods.size()}
   423             );
   424         }
   425         stopServerAndBrwsr(server, brwsr);
   426     }
   427     
   428     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   429         for (;;) {
   430             int ch = is.read();
   431             if (ch == -1) {
   432                 break;
   433             }
   434             if (ch == '$' && params.length > 0) {
   435                 int cnt = is.read() - '0';
   436                 if (baseURL != null && cnt == 'U' - '0') {
   437                     os.write(baseURL.getBytes("UTF-8"));
   438                 } else {
   439                     if (cnt >= 0 && cnt < params.length) {
   440                         os.write(params[cnt].getBytes("UTF-8"));
   441                     } else {
   442                         os.write('$');
   443                         os.write(cnt + '0');
   444                     }
   445                 }
   446             } else {
   447                 os.write(ch);
   448             }
   449         }
   450     }
   451 
   452     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   453         server.start();
   454         URI uri = pageURL("http", server, page);
   455         return showBrwsr(uri);
   456     }
   457     private static String toUTF8(String value) throws UnsupportedEncodingException {
   458         byte[] arr = new byte[value.length()];
   459         for (int i = 0; i < arr.length; i++) {
   460             arr[i] = (byte)value.charAt(i);
   461         }
   462         return new String(arr, "UTF-8");
   463     }
   464     
   465     private static String decodeURL(String s) {
   466         for (;;) {
   467             int pos = s.indexOf('%');
   468             if (pos == -1) {
   469                 return s;
   470             }
   471             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   472             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   473         }
   474     }
   475     
   476     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   477         if (brwsr == null) {
   478             return;
   479         }
   480         Process process = (Process)brwsr[0];
   481         
   482         server.stop();
   483         InputStream stdout = process.getInputStream();
   484         InputStream stderr = process.getErrorStream();
   485         drain("StdOut", stdout);
   486         drain("StdErr", stderr);
   487         process.destroy();
   488         int res;
   489         try {
   490             res = process.waitFor();
   491         } catch (InterruptedException ex) {
   492             throw new IOException(ex);
   493         }
   494         LOG.log(Level.INFO, "Exit code: {0}", res);
   495 
   496         deleteTree((File)brwsr[1]);
   497     }
   498     
   499     private static void drain(String name, InputStream is) throws IOException {
   500         int av = is.available();
   501         if (av > 0) {
   502             StringBuilder sb = new StringBuilder();
   503             sb.append("v== ").append(name).append(" ==v\n");
   504             while (av-- > 0) {
   505                 sb.append((char)is.read());
   506             }
   507             sb.append("\n^== ").append(name).append(" ==^");
   508             LOG.log(Level.INFO, sb.toString());
   509         }
   510     }
   511 
   512     private void deleteTree(File file) {
   513         if (file == null) {
   514             return;
   515         }
   516         File[] arr = file.listFiles();
   517         if (arr != null) {
   518             for (File s : arr) {
   519                 deleteTree(s);
   520             }
   521         }
   522         file.delete();
   523     }
   524 
   525     @Override
   526     public HttpServer call() throws Exception {
   527         return server;
   528     }
   529     
   530     @Override
   531     public void close() throws IOException {
   532         shutdown();
   533     }
   534 
   535     protected Object[] showBrwsr(URI uri) throws IOException {
   536         LOG.log(Level.INFO, "Showing {0}", uri);
   537         if (cmd == null) {
   538             try {
   539                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   540                     System.getProperty("java.vm.name"),
   541                     System.getProperty("java.vm.vendor"),
   542                     System.getProperty("java.vm.version"),
   543                 });
   544                 java.awt.Desktop.getDesktop().browse(uri);
   545                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   546                 return null;
   547             } catch (UnsupportedOperationException ex) {
   548                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   549                 LOG.log(Level.FINE, null, ex);
   550             }
   551         }
   552         {
   553             String cmdName = cmd == null ? "xdg-open" : cmd;
   554             String[] cmdArr = { 
   555                 cmdName, uri.toString()
   556             };
   557             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   558             final Process process = Runtime.getRuntime().exec(cmdArr);
   559             return new Object[] { process, null };
   560         }
   561     }
   562 
   563     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   564     abstract String harnessResource();
   565     String compileJar(URL jar) throws IOException {
   566         return null;
   567     }
   568     String compileFromClassPath(URL f, Res loader) throws IOException {
   569         return null;
   570     }
   571 
   572     private static URI pageURL(String protocol, HttpServer server, final String page) {
   573         NetworkListener listener = server.getListeners().iterator().next();
   574         int port = listener.getPort();
   575         try {
   576             return new URI(protocol + "://localhost:" + port + page);
   577         } catch (URISyntaxException ex) {
   578             throw new IllegalStateException(ex);
   579         }
   580     }
   581 
   582     final class Res {
   583         private final Set<URL> ignore = new HashSet<URL>();
   584         
   585         String compileJar(URL jarURL) throws IOException {
   586             String ret = BaseHTTPLauncher.this.compileJar(jarURL);
   587             ignore.add(jarURL);
   588             return ret;
   589         }
   590         String compileFromClassPath(URL f) throws IOException {
   591             return BaseHTTPLauncher.this.compileFromClassPath(f, this);
   592         }
   593         public URL get(String resource, int skip) throws IOException {
   594             if (!resource.endsWith(".class")) {
   595                 return getResource(resource, skip);
   596             }
   597             URL u = null;
   598             for (ClassLoader l : loaders) {
   599                 Enumeration<URL> en = l.getResources(resource);
   600                 while (en.hasMoreElements()) {
   601                     u = en.nextElement();
   602                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   603                         return u;
   604                     }
   605                 }
   606             }
   607             if (u != null) {
   608                 if (u.toExternalForm().contains("rt.jar")) {
   609                     LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
   610                     return null;
   611                 }
   612                 return u;
   613             }
   614             throw new IOException("Can't find " + resource);
   615         }
   616         private URL getResource(String resource, int skip) throws IOException {
   617             for (ClassLoader l : loaders) {
   618                 Enumeration<URL> en = l.getResources(resource);
   619                 while (en.hasMoreElements()) {
   620                     final URL now = en.nextElement();
   621                     if (now.toExternalForm().contains("sisu-inject-bean")) {
   622                         // certainly we don't want this resource, as that
   623                         // module is not compiled with target 1.6, currently
   624                         continue;
   625                     }
   626                     if (now.getProtocol().equals("jar")) {
   627                         JarURLConnection juc = (JarURLConnection) now.openConnection();
   628                         if (ignore.contains(juc.getJarFileURL())) {
   629                             continue;
   630                         }
   631                     }
   632                     if (--skip < 0) {
   633                         return now;
   634                     }
   635                 }
   636             }
   637             throw new IOException("Not found (anymore of) " + resource);
   638         }
   639     }
   640 
   641     private static class Page extends HttpHandler {
   642         final String resource;
   643         private final String[] args;
   644         private final Res res;
   645         
   646         public Page(Res res, String resource, String... args) {
   647             this.res = res;
   648             this.resource = resource;
   649             this.args = args.length == 0 ? new String[] { "$0" } : args;
   650         }
   651 
   652         @Override
   653         public void service(Request request, Response response) throws Exception {
   654             String r = computePage(request);
   655             if (r.startsWith("/")) {
   656                 r = r.substring(1);
   657             }
   658             String[] replace = {};
   659             if (r.endsWith(".html")) {
   660                 response.setContentType("text/html");
   661                 LOG.info("Content type text/html");
   662                 replace = args;
   663             }
   664             if (r.endsWith(".xhtml")) {
   665                 response.setContentType("application/xhtml+xml");
   666                 LOG.info("Content type application/xhtml+xml");
   667                 replace = args;
   668             }
   669             OutputStream os = response.getOutputStream();
   670             try { 
   671                 InputStream is = res.get(r, 0).openStream();
   672                 copyStream(is, os, request.getRequestURL().toString(), replace);
   673             } catch (IOException ex) {
   674                 response.setDetailMessage(ex.getLocalizedMessage());
   675                 response.setError();
   676                 response.setStatus(404);
   677             }
   678         }
   679 
   680         protected String computePage(Request request) {
   681             String r = resource;
   682             if (r == null) {
   683                 r = request.getHttpHandlerPath();
   684             }
   685             return r;
   686         }
   687     }
   688     
   689     private static class SubTree extends Page {
   690 
   691         public SubTree(Res res, String resource, String... args) {
   692             super(res, resource, args);
   693         }
   694 
   695         @Override
   696         protected String computePage(Request request) {
   697             return resource + request.getHttpHandlerPath();
   698         }
   699         
   700         
   701     }
   702 
   703     private class VMAndPages extends StaticHttpHandler {
   704         private String vmResource;
   705         
   706         public VMAndPages() {
   707             super((String[]) null);
   708         }
   709         
   710         @Override
   711         public void service(Request request, Response response) throws Exception {
   712             if (request.getRequestURI().equals(vmResource)) {
   713                 response.setCharacterEncoding("UTF-8");
   714                 response.setContentType("text/javascript");
   715                 StringBuilder sb = new StringBuilder();
   716                 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   717                 response.getWriter().write(sb.toString());
   718             } else {
   719                 super.service(request, response);
   720             }
   721         }
   722 
   723         private void registerVM(String vmResource) {
   724             this.vmResource = vmResource;
   725         }
   726     }
   727 
   728     private static class Classes extends HttpHandler {
   729         private final Res loader;
   730 
   731         public Classes(Res loader) {
   732             this.loader = loader;
   733         }
   734 
   735         @Override
   736         public void service(Request request, Response response) throws Exception {
   737             String res = request.getHttpHandlerPath();
   738             if (res.startsWith("/")) {
   739                 res = res.substring(1);
   740             }
   741             String skip = request.getParameter("skip");
   742             int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
   743             URL url = loader.get(res, skipCnt);
   744             if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
   745                 response.setCharacterEncoding("UTF-8");
   746                 if (url.getProtocol().equals("jar")) {
   747                     JarURLConnection juc = (JarURLConnection) url.openConnection();
   748                     String s = loader.compileJar(juc.getJarFileURL());
   749                     if (s != null) {
   750                         Writer w = response.getWriter();
   751                         w.append(s);
   752                         w.close();
   753                         return;
   754                     }
   755                 }
   756                 if (url.getProtocol().equals("file")) {
   757                     final String filePart = url.getFile();
   758                     if (filePart.endsWith(res)) {
   759                         url = new URL(
   760                             url.getProtocol(), 
   761                             url.getHost(), 
   762                             url.getPort(), 
   763                             filePart.substring(0, filePart.length() - res.length())
   764                         );
   765                     }
   766                     String s = loader.compileFromClassPath(url);
   767                     if (s != null) {
   768                         Writer w = response.getWriter();
   769                         w.append(s);
   770                         w.close();
   771                         return;
   772                     }
   773                 }
   774             } catch (IOException ex) {
   775                 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
   776             }
   777             InputStream is = null;
   778             try {
   779                 if (url == null) {
   780                     throw new IOException("Resource not found");
   781                 }
   782                 is = url.openStream();
   783                 response.setContentType("text/javascript");
   784                 Writer w = response.getWriter();
   785                 w.append("([");
   786                 for (int i = 0;; i++) {
   787                     int b = is.read();
   788                     if (b == -1) {
   789                         break;
   790                     }
   791                     if (i > 0) {
   792                         w.append(", ");
   793                     }
   794                     if (i % 20 == 0) {
   795                         w.write("\n");
   796                     }
   797                     if (b > 127) {
   798                         b = b - 256;
   799                     }
   800                     w.append(Integer.toString(b));
   801                 }
   802                 w.append("\n])");
   803             } catch (IOException ex) {
   804                 response.setStatus(HttpStatus.NOT_FOUND_404);
   805                 response.setError();
   806                 response.setDetailMessage(ex.getMessage());
   807             } finally {
   808                 if (is != null) {
   809                     is.close();
   810                 }
   811             }
   812         }
   813 
   814     }
   815     private static class WS extends WebSocketApplication {
   816 
   817         private final Resource r;
   818 
   819         private WS(Resource r) {
   820             this.r = r;
   821         }
   822 
   823         @Override
   824         public void onMessage(WebSocket socket, String text) {
   825             try {
   826                 r.httpContent.reset();
   827                 ByteArrayOutputStream out = new ByteArrayOutputStream();
   828                 copyStream(r.httpContent, out, null, text);
   829                 String s = new String(out.toByteArray(), "UTF-8");
   830                 socket.send(s);
   831             } catch (IOException ex) {
   832                 LOG.log(Level.WARNING, null, ex);
   833             }
   834         }
   835 
   836     }}