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