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