launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 05 Feb 2013 08:48:23 +0100
branchemul
changeset 667 5866e89ef568
parent 626 f08eb4df84c1
child 709 722c51330e75
permissions -rw-r--r--
Test can specify multiple HTTP resources
jaroslav@323
     1
/**
jaroslav@323
     2
 * Back 2 Browser Bytecode Translator
jaroslav@323
     3
 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@323
     4
 *
jaroslav@323
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@323
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@323
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@323
     8
 *
jaroslav@323
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@323
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@323
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@323
    12
 * GNU General Public License for more details.
jaroslav@323
    13
 *
jaroslav@323
    14
 * You should have received a copy of the GNU General Public License
jaroslav@323
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@323
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@323
    17
 */
jaroslav@323
    18
package org.apidesign.bck2brwsr.launcher;
jaroslav@323
    19
jaroslav@382
    20
import java.io.Closeable;
jaroslav@365
    21
import java.io.File;
jaroslav@331
    22
import java.io.IOException;
jaroslav@323
    23
import java.io.InputStream;
jaroslav@356
    24
import java.io.InterruptedIOException;
jaroslav@323
    25
import java.io.OutputStream;
jaroslav@323
    26
import java.io.Writer;
jaroslav@323
    27
import java.net.URI;
jaroslav@348
    28
import java.net.URISyntaxException;
jaroslav@323
    29
import java.net.URL;
jaroslav@348
    30
import java.util.ArrayList;
jaroslav@361
    31
import java.util.Arrays;
jaroslav@323
    32
import java.util.Enumeration;
jaroslav@348
    33
import java.util.LinkedHashSet;
jaroslav@348
    34
import java.util.List;
jaroslav@348
    35
import java.util.Set;
jaroslav@371
    36
import java.util.concurrent.BlockingQueue;
jaroslav@342
    37
import java.util.concurrent.CountDownLatch;
jaroslav@371
    38
import java.util.concurrent.LinkedBlockingQueue;
jaroslav@349
    39
import java.util.concurrent.TimeUnit;
jaroslav@362
    40
import java.util.logging.Level;
jaroslav@362
    41
import java.util.logging.Logger;
jaroslav@667
    42
import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
jaroslav@323
    43
import org.apidesign.vm4brwsr.Bck2Brwsr;
jaroslav@323
    44
import org.glassfish.grizzly.PortRange;
jaroslav@323
    45
import org.glassfish.grizzly.http.server.HttpHandler;
jaroslav@323
    46
import org.glassfish.grizzly.http.server.HttpServer;
jaroslav@323
    47
import org.glassfish.grizzly.http.server.NetworkListener;
jaroslav@323
    48
import org.glassfish.grizzly.http.server.Request;
jaroslav@323
    49
import org.glassfish.grizzly.http.server.Response;
jaroslav@323
    50
import org.glassfish.grizzly.http.server.ServerConfiguration;
jaroslav@323
    51
jaroslav@323
    52
/**
jaroslav@357
    53
 * Lightweight server to launch Bck2Brwsr applications and tests.
jaroslav@357
    54
 * Supports execution in native browser as well as Java's internal 
jaroslav@357
    55
 * execution engine.
jaroslav@323
    56
 */
jaroslav@382
    57
final class Bck2BrwsrLauncher extends Launcher implements Closeable {
jaroslav@362
    58
    private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
jaroslav@622
    59
    private static final InvocationContext END = new InvocationContext(null, null, null);
jaroslav@622
    60
    private final Set<ClassLoader> loaders = new LinkedHashSet<>();
jaroslav@622
    61
    private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
jaroslav@349
    62
    private long timeOut;
jaroslav@357
    63
    private final Res resources = new Res();
jaroslav@382
    64
    private final String cmd;
jaroslav@371
    65
    private Object[] brwsr;
jaroslav@371
    66
    private HttpServer server;
jaroslav@371
    67
    private CountDownLatch wait;
jaroslav@613
    68
    
jaroslav@382
    69
    public Bck2BrwsrLauncher(String cmd) {
jaroslav@382
    70
        this.cmd = cmd;
jaroslav@382
    71
    }
jaroslav@348
    72
    
jaroslav@382
    73
    @Override
jaroslav@622
    74
    InvocationContext runMethod(InvocationContext c) throws IOException {
jaroslav@622
    75
        loaders.add(c.clazz.getClassLoader());
jaroslav@348
    76
        methods.add(c);
jaroslav@371
    77
        try {
jaroslav@371
    78
            c.await(timeOut);
jaroslav@371
    79
        } catch (InterruptedException ex) {
jaroslav@371
    80
            throw new IOException(ex);
jaroslav@371
    81
        }
jaroslav@348
    82
        return c;
jaroslav@348
    83
    }
jaroslav@348
    84
    
jaroslav@349
    85
    public void setTimeout(long ms) {
jaroslav@349
    86
        timeOut = ms;
jaroslav@349
    87
    }
jaroslav@348
    88
    
jaroslav@357
    89
    public void addClassLoader(ClassLoader url) {
jaroslav@357
    90
        this.loaders.add(url);
jaroslav@357
    91
    }
jaroslav@348
    92
jaroslav@382
    93
    public void showURL(String startpage) throws IOException {
jaroslav@371
    94
        if (!startpage.startsWith("/")) {
jaroslav@371
    95
            startpage = "/" + startpage;
jaroslav@371
    96
        }
jaroslav@613
    97
        HttpServer s = initServer(".", true);
jaroslav@371
    98
        s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
jaroslav@382
    99
        try {
jaroslav@382
   100
            launchServerAndBrwsr(s, startpage);
jaroslav@382
   101
        } catch (URISyntaxException | InterruptedException ex) {
jaroslav@382
   102
            throw new IOException(ex);
jaroslav@382
   103
        }
jaroslav@371
   104
    }
jaroslav@348
   105
jaroslav@613
   106
    void showDirectory(File dir, String startpage) throws IOException {
jaroslav@613
   107
        if (!startpage.startsWith("/")) {
jaroslav@613
   108
            startpage = "/" + startpage;
jaroslav@613
   109
        }
jaroslav@613
   110
        HttpServer s = initServer(dir.getPath(), false);
jaroslav@613
   111
        try {
jaroslav@613
   112
            launchServerAndBrwsr(s, startpage);
jaroslav@613
   113
        } catch (URISyntaxException | InterruptedException ex) {
jaroslav@613
   114
            throw new IOException(ex);
jaroslav@613
   115
        }
jaroslav@613
   116
    }
jaroslav@613
   117
jaroslav@382
   118
    @Override
jaroslav@371
   119
    public void initialize() throws IOException {
jaroslav@356
   120
        try {
jaroslav@371
   121
            executeInBrowser();
jaroslav@356
   122
        } catch (InterruptedException ex) {
jaroslav@356
   123
            final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
jaroslav@356
   124
            iio.initCause(ex);
jaroslav@356
   125
            throw iio;
jaroslav@356
   126
        } catch (Exception ex) {
jaroslav@356
   127
            if (ex instanceof IOException) {
jaroslav@356
   128
                throw (IOException)ex;
jaroslav@356
   129
            }
jaroslav@356
   130
            if (ex instanceof RuntimeException) {
jaroslav@356
   131
                throw (RuntimeException)ex;
jaroslav@356
   132
            }
jaroslav@356
   133
            throw new IOException(ex);
jaroslav@356
   134
        }
jaroslav@356
   135
    }
jaroslav@356
   136
    
jaroslav@613
   137
    private HttpServer initServer(String path, boolean addClasses) throws IOException {
jaroslav@613
   138
        HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
jaroslav@357
   139
jaroslav@371
   140
        final ServerConfiguration conf = s.getServerConfiguration();
jaroslav@613
   141
        if (addClasses) {
jaroslav@613
   142
            conf.addHttpHandler(new VM(resources), "/vm.js");
jaroslav@613
   143
            conf.addHttpHandler(new Classes(resources), "/classes/");
jaroslav@613
   144
        }
jaroslav@371
   145
        return s;
jaroslav@357
   146
    }
jaroslav@357
   147
    
jaroslav@357
   148
    private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
jaroslav@371
   149
        wait = new CountDownLatch(1);
jaroslav@613
   150
        server = initServer(".", true);
jaroslav@623
   151
        final ServerConfiguration conf = server.getServerConfiguration();
jaroslav@623
   152
        
jaroslav@623
   153
        class DynamicResourceHandler extends HttpHandler {
jaroslav@623
   154
            private final InvocationContext ic;
jaroslav@623
   155
            public DynamicResourceHandler(InvocationContext ic) {
jaroslav@667
   156
                if (ic == null || ic.resources.isEmpty()) {
jaroslav@623
   157
                    throw new NullPointerException();
jaroslav@623
   158
                }
jaroslav@623
   159
                this.ic = ic;
jaroslav@667
   160
                for (Resource r : ic.resources) {
jaroslav@667
   161
                    conf.addHttpHandler(this, r.httpPath);
jaroslav@667
   162
                }
jaroslav@623
   163
            }
jaroslav@623
   164
jaroslav@623
   165
            public void close() {
jaroslav@623
   166
                conf.removeHttpHandler(this);
jaroslav@623
   167
            }
jaroslav@623
   168
            
jaroslav@623
   169
            @Override
jaroslav@623
   170
            public void service(Request request, Response response) throws Exception {
jaroslav@667
   171
                for (Resource r : ic.resources) {
jaroslav@667
   172
                    if (r.httpPath.equals(request.getRequestURI())) {
jaroslav@667
   173
                        LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
jaroslav@667
   174
                        response.setContentType(r.httpType);
jaroslav@667
   175
                        copyStream(r.httpContent, response.getOutputStream(), null);
jaroslav@667
   176
                    }
jaroslav@623
   177
                }
jaroslav@623
   178
            }
jaroslav@623
   179
        }
jaroslav@623
   180
        
jaroslav@357
   181
        conf.addHttpHandler(new Page(resources, 
jaroslav@357
   182
            "org/apidesign/bck2brwsr/launcher/harness.xhtml"
jaroslav@357
   183
        ), "/execute");
jaroslav@623
   184
        
jaroslav@332
   185
        conf.addHttpHandler(new HttpHandler() {
jaroslav@332
   186
            int cnt;
jaroslav@622
   187
            List<InvocationContext> cases = new ArrayList<>();
jaroslav@623
   188
            DynamicResourceHandler prev;
jaroslav@332
   189
            @Override
jaroslav@332
   190
            public void service(Request request, Response response) throws Exception {
jaroslav@342
   191
                String id = request.getParameter("request");
jaroslav@342
   192
                String value = request.getParameter("result");
jaroslav@364
   193
                
jaroslav@342
   194
                if (id != null && value != null) {
jaroslav@364
   195
                    LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
jaroslav@381
   196
                    value = decodeURL(value);
jaroslav@371
   197
                    cases.get(Integer.parseInt(id)).result(value, null);
jaroslav@342
   198
                }
jaroslav@342
   199
                
jaroslav@623
   200
                if (prev != null) {
jaroslav@623
   201
                    prev.close();
jaroslav@623
   202
                    prev = null;
jaroslav@623
   203
                }
jaroslav@623
   204
                
jaroslav@622
   205
                InvocationContext mi = methods.take();
jaroslav@372
   206
                if (mi == END) {
jaroslav@342
   207
                    response.getWriter().write("");
jaroslav@342
   208
                    wait.countDown();
jaroslav@342
   209
                    cnt = 0;
jaroslav@372
   210
                    LOG.log(Level.INFO, "End of data reached. Exiting.");
jaroslav@342
   211
                    return;
jaroslav@342
   212
                }
jaroslav@342
   213
                
jaroslav@667
   214
                if (!mi.resources.isEmpty()) {
jaroslav@623
   215
                    prev = new DynamicResourceHandler(mi);
jaroslav@623
   216
                }
jaroslav@623
   217
                
jaroslav@371
   218
                cases.add(mi);
jaroslav@622
   219
                final String cn = mi.clazz.getName();
jaroslav@371
   220
                final String mn = mi.methodName;
jaroslav@364
   221
                LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
jaroslav@332
   222
                response.getWriter().write("{"
jaroslav@364
   223
                    + "className: '" + cn + "', "
jaroslav@364
   224
                    + "methodName: '" + mn + "', "
jaroslav@332
   225
                    + "request: " + cnt
jaroslav@526
   226
                );
jaroslav@526
   227
                if (mi.html != null) {
jaroslav@526
   228
                    response.getWriter().write(", html: '");
jaroslav@526
   229
                    response.getWriter().write(encodeJSON(mi.html));
jaroslav@526
   230
                    response.getWriter().write("'");
jaroslav@526
   231
                }
jaroslav@526
   232
                response.getWriter().write("}");
jaroslav@342
   233
                cnt++;
jaroslav@332
   234
            }
jaroslav@342
   235
        }, "/data");
jaroslav@357
   236
jaroslav@371
   237
        this.brwsr = launchServerAndBrwsr(server, "/execute");
jaroslav@371
   238
    }
jaroslav@371
   239
    
jaroslav@526
   240
    private static String encodeJSON(String in) {
jaroslav@526
   241
        StringBuilder sb = new StringBuilder();
jaroslav@526
   242
        for (int i = 0; i < in.length(); i++) {
jaroslav@526
   243
            char ch = in.charAt(i);
jaroslav@526
   244
            if (ch < 32 || ch == '\'' || ch == '"') {
jaroslav@526
   245
                sb.append("\\u");
jaroslav@526
   246
                String hs = "0000" + Integer.toHexString(ch);
jaroslav@526
   247
                hs = hs.substring(hs.length() - 4);
jaroslav@526
   248
                sb.append(hs);
jaroslav@526
   249
            } else {
jaroslav@526
   250
                sb.append(ch);
jaroslav@526
   251
            }
jaroslav@526
   252
        }
jaroslav@526
   253
        return sb.toString();
jaroslav@526
   254
    }
jaroslav@526
   255
    
jaroslav@382
   256
    @Override
jaroslav@382
   257
    public void shutdown() throws IOException {
jaroslav@372
   258
        methods.offer(END);
jaroslav@363
   259
        for (;;) {
jaroslav@371
   260
            int prev = methods.size();
jaroslav@382
   261
            try {
jaroslav@389
   262
                if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
jaroslav@382
   263
                    break;
jaroslav@382
   264
                }
jaroslav@382
   265
            } catch (InterruptedException ex) {
jaroslav@382
   266
                throw new IOException(ex);
jaroslav@363
   267
            }
jaroslav@371
   268
            if (prev == methods.size()) {
jaroslav@363
   269
                LOG.log(
jaroslav@363
   270
                    Level.WARNING, 
jaroslav@363
   271
                    "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
jaroslav@371
   272
                    methods.size()
jaroslav@363
   273
                );
jaroslav@363
   274
                break;
jaroslav@363
   275
            }
jaroslav@363
   276
            LOG.log(Level.INFO, 
jaroslav@363
   277
                "Timeout, but tests got from {0} to {1}. Trying again.", 
jaroslav@371
   278
                new Object[]{prev, methods.size()}
jaroslav@363
   279
            );
jaroslav@363
   280
        }
jaroslav@365
   281
        stopServerAndBrwsr(server, brwsr);
jaroslav@323
   282
    }
jaroslav@331
   283
    
jaroslav@342
   284
    static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
jaroslav@331
   285
        for (;;) {
jaroslav@331
   286
            int ch = is.read();
jaroslav@331
   287
            if (ch == -1) {
jaroslav@331
   288
                break;
jaroslav@331
   289
            }
jaroslav@523
   290
            if (ch == '$' && params.length > 0) {
jaroslav@331
   291
                int cnt = is.read() - '0';
jaroslav@342
   292
                if (cnt == 'U' - '0') {
jaroslav@342
   293
                    os.write(baseURL.getBytes());
jaroslav@342
   294
                }
jaroslav@523
   295
                if (cnt >= 0 && cnt < params.length) {
jaroslav@331
   296
                    os.write(params[cnt].getBytes());
jaroslav@331
   297
                }
jaroslav@331
   298
            } else {
jaroslav@331
   299
                os.write(ch);
jaroslav@331
   300
            }
jaroslav@331
   301
        }
jaroslav@331
   302
    }
jaroslav@356
   303
jaroslav@365
   304
    private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
jaroslav@357
   305
        server.start();
jaroslav@357
   306
        NetworkListener listener = server.getListeners().iterator().next();
jaroslav@357
   307
        int port = listener.getPort();
jaroslav@357
   308
        
jaroslav@357
   309
        URI uri = new URI("http://localhost:" + port + page);
jaroslav@362
   310
        LOG.log(Level.INFO, "Showing {0}", uri);
jaroslav@433
   311
        if (cmd == null) {
jaroslav@433
   312
            try {
jaroslav@536
   313
                LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
jaroslav@536
   314
                    System.getProperty("java.vm.name"),
jaroslav@536
   315
                    System.getProperty("java.vm.vendor"),
jaroslav@536
   316
                    System.getProperty("java.vm.version"),
jaroslav@536
   317
                });
jaroslav@433
   318
                java.awt.Desktop.getDesktop().browse(uri);
jaroslav@433
   319
                LOG.log(Level.INFO, "Desktop.browse successfully finished");
jaroslav@433
   320
                return null;
jaroslav@433
   321
            } catch (UnsupportedOperationException ex) {
jaroslav@518
   322
                LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
jaroslav@518
   323
                LOG.log(Level.FINE, null, ex);
jaroslav@433
   324
            }
jaroslav@369
   325
        }
jaroslav@369
   326
        {
jaroslav@382
   327
            String cmdName = cmd == null ? "xdg-open" : cmd;
jaroslav@382
   328
            String[] cmdArr = { 
jaroslav@382
   329
                cmdName, uri.toString()
jaroslav@357
   330
            };
jaroslav@382
   331
            LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
jaroslav@382
   332
            final Process process = Runtime.getRuntime().exec(cmdArr);
jaroslav@369
   333
            return new Object[] { process, null };
jaroslav@357
   334
        }
jaroslav@361
   335
    }
jaroslav@361
   336
    
jaroslav@381
   337
    private static String decodeURL(String s) {
jaroslav@381
   338
        for (;;) {
jaroslav@381
   339
            int pos = s.indexOf('%');
jaroslav@381
   340
            if (pos == -1) {
jaroslav@381
   341
                return s;
jaroslav@381
   342
            }
jaroslav@381
   343
            int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
jaroslav@381
   344
            s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
jaroslav@381
   345
        }
jaroslav@381
   346
    }
jaroslav@381
   347
    
jaroslav@382
   348
    private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
jaroslav@389
   349
        if (brwsr == null) {
jaroslav@389
   350
            return;
jaroslav@389
   351
        }
jaroslav@365
   352
        Process process = (Process)brwsr[0];
jaroslav@365
   353
        
jaroslav@365
   354
        server.stop();
jaroslav@365
   355
        InputStream stdout = process.getInputStream();
jaroslav@365
   356
        InputStream stderr = process.getErrorStream();
jaroslav@365
   357
        drain("StdOut", stdout);
jaroslav@365
   358
        drain("StdErr", stderr);
jaroslav@365
   359
        process.destroy();
jaroslav@382
   360
        int res;
jaroslav@382
   361
        try {
jaroslav@382
   362
            res = process.waitFor();
jaroslav@382
   363
        } catch (InterruptedException ex) {
jaroslav@382
   364
            throw new IOException(ex);
jaroslav@382
   365
        }
jaroslav@365
   366
        LOG.log(Level.INFO, "Exit code: {0}", res);
jaroslav@365
   367
jaroslav@365
   368
        deleteTree((File)brwsr[1]);
jaroslav@365
   369
    }
jaroslav@365
   370
    
jaroslav@361
   371
    private static void drain(String name, InputStream is) throws IOException {
jaroslav@361
   372
        int av = is.available();
jaroslav@361
   373
        if (av > 0) {
jaroslav@362
   374
            StringBuilder sb = new StringBuilder();
jaroslav@362
   375
            sb.append("v== ").append(name).append(" ==v\n");
jaroslav@361
   376
            while (av-- > 0) {
jaroslav@362
   377
                sb.append((char)is.read());
jaroslav@361
   378
            }
jaroslav@362
   379
            sb.append("\n^== ").append(name).append(" ==^");
jaroslav@362
   380
            LOG.log(Level.INFO, sb.toString());
jaroslav@361
   381
        }
jaroslav@357
   382
    }
jaroslav@357
   383
jaroslav@365
   384
    private void deleteTree(File file) {
jaroslav@369
   385
        if (file == null) {
jaroslav@369
   386
            return;
jaroslav@369
   387
        }
jaroslav@365
   388
        File[] arr = file.listFiles();
jaroslav@365
   389
        if (arr != null) {
jaroslav@365
   390
            for (File s : arr) {
jaroslav@365
   391
                deleteTree(s);
jaroslav@365
   392
            }
jaroslav@365
   393
        }
jaroslav@365
   394
        file.delete();
jaroslav@365
   395
    }
jaroslav@365
   396
jaroslav@382
   397
    @Override
jaroslav@382
   398
    public void close() throws IOException {
jaroslav@382
   399
        shutdown();
jaroslav@382
   400
    }
jaroslav@382
   401
jaroslav@348
   402
    private class Res implements Bck2Brwsr.Resources {
jaroslav@348
   403
        @Override
jaroslav@348
   404
        public InputStream get(String resource) throws IOException {
jaroslav@348
   405
            for (ClassLoader l : loaders) {
jaroslav@348
   406
                URL u = null;
jaroslav@348
   407
                Enumeration<URL> en = l.getResources(resource);
jaroslav@348
   408
                while (en.hasMoreElements()) {
jaroslav@348
   409
                    u = en.nextElement();
jaroslav@348
   410
                }
jaroslav@348
   411
                if (u != null) {
jaroslav@348
   412
                    return u.openStream();
jaroslav@348
   413
                }
jaroslav@348
   414
            }
jaroslav@348
   415
            throw new IOException("Can't find " + resource);
jaroslav@348
   416
        }
jaroslav@348
   417
    }
jaroslav@330
   418
jaroslav@332
   419
    private static class Page extends HttpHandler {
jaroslav@332
   420
        private final String resource;
jaroslav@331
   421
        private final String[] args;
jaroslav@357
   422
        private final Res res;
jaroslav@331
   423
        
jaroslav@357
   424
        public Page(Res res, String resource, String... args) {
jaroslav@357
   425
            this.res = res;
jaroslav@332
   426
            this.resource = resource;
jaroslav@526
   427
            this.args = args.length == 0 ? new String[] { "$0" } : args;
jaroslav@330
   428
        }
jaroslav@330
   429
jaroslav@330
   430
        @Override
jaroslav@330
   431
        public void service(Request request, Response response) throws Exception {
jaroslav@357
   432
            String r = resource;
jaroslav@357
   433
            if (r == null) {
jaroslav@357
   434
                r = request.getHttpHandlerPath();
jaroslav@357
   435
                if (r.startsWith("/")) {
jaroslav@357
   436
                    r = r.substring(1);
jaroslav@357
   437
                }
jaroslav@357
   438
            }
jaroslav@523
   439
            String[] replace = {};
jaroslav@433
   440
            if (r.endsWith(".html")) {
jaroslav@357
   441
                response.setContentType("text/html");
jaroslav@433
   442
                LOG.info("Content type text/html");
jaroslav@523
   443
                replace = args;
jaroslav@433
   444
            }
jaroslav@433
   445
            if (r.endsWith(".xhtml")) {
jaroslav@433
   446
                response.setContentType("application/xhtml+xml");
jaroslav@433
   447
                LOG.info("Content type application/xhtml+xml");
jaroslav@523
   448
                replace = args;
jaroslav@357
   449
            }
jaroslav@330
   450
            OutputStream os = response.getOutputStream();
jaroslav@357
   451
            try (InputStream is = res.get(r)) {
jaroslav@523
   452
                copyStream(is, os, request.getRequestURL().toString(), replace);
jaroslav@357
   453
            } catch (IOException ex) {
jaroslav@357
   454
                response.setDetailMessage(ex.getLocalizedMessage());
jaroslav@357
   455
                response.setError();
jaroslav@357
   456
                response.setStatus(404);
jaroslav@357
   457
            }
jaroslav@330
   458
        }
jaroslav@330
   459
    }
jaroslav@330
   460
jaroslav@330
   461
    private static class VM extends HttpHandler {
jaroslav@580
   462
        private final String bck2brwsr;
jaroslav@330
   463
jaroslav@580
   464
        public VM(Res loader) throws IOException {
jaroslav@580
   465
            StringBuilder sb = new StringBuilder();
jaroslav@580
   466
            Bck2Brwsr.generate(sb, loader);
jaroslav@583
   467
            sb.append(
jaroslav@583
   468
                "function ldCls(res) {\n"
jaroslav@583
   469
                + "  var request = new XMLHttpRequest();\n"
jaroslav@583
   470
                + "  request.open('GET', '/classes/' + res, false);\n"
jaroslav@583
   471
                + "  request.send();\n"
jaroslav@583
   472
                + "  var arr = eval('(' + request.responseText + ')');\n"
jaroslav@583
   473
                + "  return arr;\n"
jaroslav@583
   474
                + "}\n"
jaroslav@583
   475
                + "var vm = new bck2brwsr(ldCls);\n"
jaroslav@583
   476
            );
jaroslav@580
   477
            this.bck2brwsr = sb.toString();
jaroslav@330
   478
        }
jaroslav@330
   479
jaroslav@330
   480
        @Override
jaroslav@330
   481
        public void service(Request request, Response response) throws Exception {
jaroslav@330
   482
            response.setCharacterEncoding("UTF-8");
jaroslav@330
   483
            response.setContentType("text/javascript");
jaroslav@580
   484
            response.getWriter().write(bck2brwsr);
jaroslav@330
   485
        }
jaroslav@330
   486
    }
jaroslav@330
   487
jaroslav@330
   488
    private static class Classes extends HttpHandler {
jaroslav@348
   489
        private final Res loader;
jaroslav@330
   490
jaroslav@348
   491
        public Classes(Res loader) {
jaroslav@330
   492
            this.loader = loader;
jaroslav@330
   493
        }
jaroslav@330
   494
jaroslav@330
   495
        @Override
jaroslav@330
   496
        public void service(Request request, Response response) throws Exception {
jaroslav@330
   497
            String res = request.getHttpHandlerPath();
jaroslav@330
   498
            if (res.startsWith("/")) {
jaroslav@330
   499
                res = res.substring(1);
jaroslav@330
   500
            }
jaroslav@348
   501
            try (InputStream is = loader.get(res)) {
jaroslav@348
   502
                response.setContentType("text/javascript");
jaroslav@348
   503
                Writer w = response.getWriter();
jaroslav@348
   504
                w.append("[");
jaroslav@348
   505
                for (int i = 0;; i++) {
jaroslav@348
   506
                    int b = is.read();
jaroslav@348
   507
                    if (b == -1) {
jaroslav@348
   508
                        break;
jaroslav@348
   509
                    }
jaroslav@348
   510
                    if (i > 0) {
jaroslav@348
   511
                        w.append(", ");
jaroslav@348
   512
                    }
jaroslav@348
   513
                    if (i % 20 == 0) {
jaroslav@348
   514
                        w.write("\n");
jaroslav@348
   515
                    }
jaroslav@348
   516
                    if (b > 127) {
jaroslav@348
   517
                        b = b - 256;
jaroslav@348
   518
                    }
jaroslav@348
   519
                    w.append(Integer.toString(b));
jaroslav@348
   520
                }
jaroslav@348
   521
                w.append("\n]");
jaroslav@348
   522
            } catch (IOException ex) {
jaroslav@348
   523
                response.setError();
jaroslav@348
   524
                response.setDetailMessage(ex.getMessage());
jaroslav@330
   525
            }
jaroslav@330
   526
        }
jaroslav@330
   527
    }
jaroslav@323
   528
}