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