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