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