launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 23 Dec 2012 18:24:18 +0100
branchlauncher
changeset 371 bafc670aa10d
parent 370 ed48023d1d85
child 372 3485327d3080
permissions -rw-r--r--
Separating initialization and method execution on HTTP launcher as well
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@365
    20
import java.io.File;
jaroslav@331
    21
import java.io.IOException;
jaroslav@323
    22
import java.io.InputStream;
jaroslav@356
    23
import java.io.InterruptedIOException;
jaroslav@323
    24
import java.io.OutputStream;
jaroslav@323
    25
import java.io.Writer;
jaroslav@323
    26
import java.net.URI;
jaroslav@348
    27
import java.net.URISyntaxException;
jaroslav@323
    28
import java.net.URL;
jaroslav@348
    29
import java.util.ArrayList;
jaroslav@361
    30
import java.util.Arrays;
jaroslav@323
    31
import java.util.Enumeration;
jaroslav@348
    32
import java.util.LinkedHashSet;
jaroslav@348
    33
import java.util.List;
jaroslav@348
    34
import java.util.Set;
jaroslav@371
    35
import java.util.concurrent.BlockingQueue;
jaroslav@342
    36
import java.util.concurrent.CountDownLatch;
jaroslav@371
    37
import java.util.concurrent.LinkedBlockingQueue;
jaroslav@349
    38
import java.util.concurrent.TimeUnit;
jaroslav@362
    39
import java.util.logging.Level;
jaroslav@362
    40
import java.util.logging.Logger;
jaroslav@323
    41
import org.apidesign.vm4brwsr.Bck2Brwsr;
jaroslav@323
    42
import org.glassfish.grizzly.PortRange;
jaroslav@323
    43
import org.glassfish.grizzly.http.server.HttpHandler;
jaroslav@323
    44
import org.glassfish.grizzly.http.server.HttpServer;
jaroslav@323
    45
import org.glassfish.grizzly.http.server.NetworkListener;
jaroslav@323
    46
import org.glassfish.grizzly.http.server.Request;
jaroslav@323
    47
import org.glassfish.grizzly.http.server.Response;
jaroslav@323
    48
import org.glassfish.grizzly.http.server.ServerConfiguration;
jaroslav@323
    49
jaroslav@323
    50
/**
jaroslav@357
    51
 * Lightweight server to launch Bck2Brwsr applications and tests.
jaroslav@357
    52
 * Supports execution in native browser as well as Java's internal 
jaroslav@357
    53
 * execution engine.
jaroslav@323
    54
 */
jaroslav@323
    55
public class Bck2BrwsrLauncher {
jaroslav@362
    56
    private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
jaroslav@348
    57
    private Set<ClassLoader> loaders = new LinkedHashSet<>();
jaroslav@371
    58
    private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
jaroslav@349
    59
    private long timeOut;
jaroslav@357
    60
    private final Res resources = new Res();
jaroslav@371
    61
    private Object[] brwsr;
jaroslav@371
    62
    private HttpServer server;
jaroslav@371
    63
    private CountDownLatch wait;
jaroslav@348
    64
    
jaroslav@348
    65
    
jaroslav@371
    66
    public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
jaroslav@348
    67
        loaders.add(clazz.getClassLoader());
jaroslav@348
    68
        MethodInvocation c = new MethodInvocation(clazz.getName(), method);
jaroslav@348
    69
        methods.add(c);
jaroslav@371
    70
        try {
jaroslav@371
    71
            c.await(timeOut);
jaroslav@371
    72
        } catch (InterruptedException ex) {
jaroslav@371
    73
            throw new IOException(ex);
jaroslav@371
    74
        }
jaroslav@348
    75
        return c;
jaroslav@348
    76
    }
jaroslav@348
    77
    
jaroslav@349
    78
    public void setTimeout(long ms) {
jaroslav@349
    79
        timeOut = ms;
jaroslav@349
    80
    }
jaroslav@348
    81
    
jaroslav@357
    82
    public void addClassLoader(ClassLoader url) {
jaroslav@357
    83
        this.loaders.add(url);
jaroslav@357
    84
    }
jaroslav@356
    85
    
jaroslav@323
    86
    public static void main( String[] args ) throws Exception {
jaroslav@348
    87
        Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
jaroslav@357
    88
        l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
jaroslav@371
    89
        l.showURL("org/apidesign/bck2brwsr/launcher/console.xhtml");
jaroslav@357
    90
        System.in.read();
jaroslav@348
    91
    }
jaroslav@348
    92
jaroslav@371
    93
    public void showURL(String startpage) throws URISyntaxException, InterruptedException, IOException {
jaroslav@371
    94
        if (!startpage.startsWith("/")) {
jaroslav@371
    95
            startpage = "/" + startpage;
jaroslav@371
    96
        }
jaroslav@371
    97
        HttpServer s = initServer();
jaroslav@371
    98
        s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
jaroslav@371
    99
        launchServerAndBrwsr(s, startpage);
jaroslav@371
   100
    }
jaroslav@348
   101
jaroslav@371
   102
    public void initialize() throws IOException {
jaroslav@356
   103
        try {
jaroslav@371
   104
            executeInBrowser();
jaroslav@356
   105
        } catch (InterruptedException ex) {
jaroslav@356
   106
            final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
jaroslav@356
   107
            iio.initCause(ex);
jaroslav@356
   108
            throw iio;
jaroslav@356
   109
        } catch (Exception ex) {
jaroslav@356
   110
            if (ex instanceof IOException) {
jaroslav@356
   111
                throw (IOException)ex;
jaroslav@356
   112
            }
jaroslav@356
   113
            if (ex instanceof RuntimeException) {
jaroslav@356
   114
                throw (RuntimeException)ex;
jaroslav@356
   115
            }
jaroslav@356
   116
            throw new IOException(ex);
jaroslav@356
   117
        }
jaroslav@356
   118
    }
jaroslav@356
   119
    
jaroslav@357
   120
    private HttpServer initServer() {
jaroslav@371
   121
        HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
jaroslav@357
   122
jaroslav@371
   123
        final ServerConfiguration conf = s.getServerConfiguration();
jaroslav@357
   124
        conf.addHttpHandler(new Page(resources, 
jaroslav@357
   125
            "org/apidesign/bck2brwsr/launcher/console.xhtml",
jaroslav@332
   126
            "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
jaroslav@332
   127
        ), "/console");
jaroslav@348
   128
        conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
jaroslav@332
   129
        conf.addHttpHandler(new VMInit(), "/vm.js");
jaroslav@348
   130
        conf.addHttpHandler(new Classes(resources), "/classes/");
jaroslav@371
   131
        return s;
jaroslav@357
   132
    }
jaroslav@357
   133
    
jaroslav@357
   134
    private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
jaroslav@371
   135
        wait = new CountDownLatch(1);
jaroslav@371
   136
        server = initServer();
jaroslav@357
   137
        ServerConfiguration conf = server.getServerConfiguration();
jaroslav@357
   138
        conf.addHttpHandler(new Page(resources, 
jaroslav@357
   139
            "org/apidesign/bck2brwsr/launcher/harness.xhtml"
jaroslav@357
   140
        ), "/execute");
jaroslav@332
   141
        conf.addHttpHandler(new HttpHandler() {
jaroslav@332
   142
            int cnt;
jaroslav@371
   143
            List<MethodInvocation> cases = new ArrayList<>();
jaroslav@332
   144
            @Override
jaroslav@332
   145
            public void service(Request request, Response response) throws Exception {
jaroslav@342
   146
                String id = request.getParameter("request");
jaroslav@342
   147
                String value = request.getParameter("result");
jaroslav@364
   148
                
jaroslav@342
   149
                if (id != null && value != null) {
jaroslav@364
   150
                    LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
jaroslav@342
   151
                    value = value.replace("%20", " ");
jaroslav@371
   152
                    cases.get(Integer.parseInt(id)).result(value, null);
jaroslav@342
   153
                }
jaroslav@342
   154
                
jaroslav@371
   155
                MethodInvocation mi = methods.take();
jaroslav@371
   156
                if (mi == null) {
jaroslav@342
   157
                    response.getWriter().write("");
jaroslav@342
   158
                    wait.countDown();
jaroslav@342
   159
                    cnt = 0;
jaroslav@342
   160
                    return;
jaroslav@342
   161
                }
jaroslav@342
   162
                
jaroslav@371
   163
                cases.add(mi);
jaroslav@371
   164
                final String cn = mi.className;
jaroslav@371
   165
                final String mn = mi.methodName;
jaroslav@364
   166
                LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
jaroslav@332
   167
                response.getWriter().write("{"
jaroslav@364
   168
                    + "className: '" + cn + "', "
jaroslav@364
   169
                    + "methodName: '" + mn + "', "
jaroslav@332
   170
                    + "request: " + cnt
jaroslav@332
   171
                    + "}");
jaroslav@342
   172
                cnt++;
jaroslav@332
   173
            }
jaroslav@342
   174
        }, "/data");
jaroslav@357
   175
jaroslav@371
   176
        this.brwsr = launchServerAndBrwsr(server, "/execute");
jaroslav@371
   177
    }
jaroslav@371
   178
    
jaroslav@371
   179
    public void shutdown() throws InterruptedException, IOException {
jaroslav@363
   180
        for (;;) {
jaroslav@371
   181
            int prev = methods.size();
jaroslav@363
   182
            if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
jaroslav@363
   183
                break;
jaroslav@363
   184
            }
jaroslav@371
   185
            if (prev == methods.size()) {
jaroslav@363
   186
                LOG.log(
jaroslav@363
   187
                    Level.WARNING, 
jaroslav@363
   188
                    "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
jaroslav@371
   189
                    methods.size()
jaroslav@363
   190
                );
jaroslav@363
   191
                break;
jaroslav@363
   192
            }
jaroslav@363
   193
            LOG.log(Level.INFO, 
jaroslav@363
   194
                "Timeout, but tests got from {0} to {1}. Trying again.", 
jaroslav@371
   195
                new Object[]{prev, methods.size()}
jaroslav@363
   196
            );
jaroslav@363
   197
        }
jaroslav@365
   198
        stopServerAndBrwsr(server, brwsr);
jaroslav@323
   199
    }
jaroslav@331
   200
    
jaroslav@342
   201
    static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
jaroslav@331
   202
        for (;;) {
jaroslav@331
   203
            int ch = is.read();
jaroslav@331
   204
            if (ch == -1) {
jaroslav@331
   205
                break;
jaroslav@331
   206
            }
jaroslav@331
   207
            if (ch == '$') {
jaroslav@331
   208
                int cnt = is.read() - '0';
jaroslav@342
   209
                if (cnt == 'U' - '0') {
jaroslav@342
   210
                    os.write(baseURL.getBytes());
jaroslav@342
   211
                }
jaroslav@331
   212
                if (cnt < params.length) {
jaroslav@331
   213
                    os.write(params[cnt].getBytes());
jaroslav@331
   214
                }
jaroslav@331
   215
            } else {
jaroslav@331
   216
                os.write(ch);
jaroslav@331
   217
            }
jaroslav@331
   218
        }
jaroslav@331
   219
    }
jaroslav@356
   220
jaroslav@365
   221
    private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
jaroslav@357
   222
        server.start();
jaroslav@357
   223
        NetworkListener listener = server.getListeners().iterator().next();
jaroslav@357
   224
        int port = listener.getPort();
jaroslav@357
   225
        
jaroslav@357
   226
        URI uri = new URI("http://localhost:" + port + page);
jaroslav@362
   227
        LOG.log(Level.INFO, "Showing {0}", uri);
jaroslav@367
   228
//        try {
jaroslav@367
   229
//            Desktop.getDesktop().browse(uri);
jaroslav@367
   230
//            return null;
jaroslav@367
   231
//        } catch (UnsupportedOperationException ex)
jaroslav@367
   232
        {
jaroslav@369
   233
//            File dir = File.createTempFile("chrome", ".dir");
jaroslav@369
   234
//            dir.delete();
jaroslav@369
   235
//            dir.mkdirs();
jaroslav@369
   236
//            String[] cmd = { 
jaroslav@369
   237
//                "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
jaroslav@369
   238
//            };
jaroslav@369
   239
//            LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
jaroslav@369
   240
//            final Process process = Runtime.getRuntime().exec(cmd);
jaroslav@369
   241
//            return new Object[] { process, dir };
jaroslav@369
   242
        }
jaroslav@369
   243
        {
jaroslav@357
   244
            String[] cmd = { 
jaroslav@369
   245
                "xdg-open", uri.toString()
jaroslav@357
   246
            };
jaroslav@362
   247
            LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
jaroslav@361
   248
            final Process process = Runtime.getRuntime().exec(cmd);
jaroslav@369
   249
            return new Object[] { process, null };
jaroslav@357
   250
        }
jaroslav@361
   251
    }
jaroslav@361
   252
    
jaroslav@365
   253
    private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
jaroslav@365
   254
        Process process = (Process)brwsr[0];
jaroslav@365
   255
        
jaroslav@365
   256
        server.stop();
jaroslav@365
   257
        InputStream stdout = process.getInputStream();
jaroslav@365
   258
        InputStream stderr = process.getErrorStream();
jaroslav@365
   259
        drain("StdOut", stdout);
jaroslav@365
   260
        drain("StdErr", stderr);
jaroslav@365
   261
        process.destroy();
jaroslav@365
   262
        int res = process.waitFor();
jaroslav@365
   263
        LOG.log(Level.INFO, "Exit code: {0}", res);
jaroslav@365
   264
jaroslav@365
   265
        deleteTree((File)brwsr[1]);
jaroslav@365
   266
    }
jaroslav@365
   267
    
jaroslav@361
   268
    private static void drain(String name, InputStream is) throws IOException {
jaroslav@361
   269
        int av = is.available();
jaroslav@361
   270
        if (av > 0) {
jaroslav@362
   271
            StringBuilder sb = new StringBuilder();
jaroslav@362
   272
            sb.append("v== ").append(name).append(" ==v\n");
jaroslav@361
   273
            while (av-- > 0) {
jaroslav@362
   274
                sb.append((char)is.read());
jaroslav@361
   275
            }
jaroslav@362
   276
            sb.append("\n^== ").append(name).append(" ==^");
jaroslav@362
   277
            LOG.log(Level.INFO, sb.toString());
jaroslav@361
   278
        }
jaroslav@357
   279
    }
jaroslav@357
   280
jaroslav@365
   281
    private void deleteTree(File file) {
jaroslav@369
   282
        if (file == null) {
jaroslav@369
   283
            return;
jaroslav@369
   284
        }
jaroslav@365
   285
        File[] arr = file.listFiles();
jaroslav@365
   286
        if (arr != null) {
jaroslav@365
   287
            for (File s : arr) {
jaroslav@365
   288
                deleteTree(s);
jaroslav@365
   289
            }
jaroslav@365
   290
        }
jaroslav@365
   291
        file.delete();
jaroslav@365
   292
    }
jaroslav@365
   293
jaroslav@348
   294
    private class Res implements Bck2Brwsr.Resources {
jaroslav@348
   295
        @Override
jaroslav@348
   296
        public InputStream get(String resource) throws IOException {
jaroslav@348
   297
            for (ClassLoader l : loaders) {
jaroslav@348
   298
                URL u = null;
jaroslav@348
   299
                Enumeration<URL> en = l.getResources(resource);
jaroslav@348
   300
                while (en.hasMoreElements()) {
jaroslav@348
   301
                    u = en.nextElement();
jaroslav@348
   302
                }
jaroslav@348
   303
                if (u != null) {
jaroslav@348
   304
                    return u.openStream();
jaroslav@348
   305
                }
jaroslav@348
   306
            }
jaroslav@348
   307
            throw new IOException("Can't find " + resource);
jaroslav@348
   308
        }
jaroslav@348
   309
    }
jaroslav@330
   310
jaroslav@332
   311
    private static class Page extends HttpHandler {
jaroslav@332
   312
        private final String resource;
jaroslav@331
   313
        private final String[] args;
jaroslav@357
   314
        private final Res res;
jaroslav@331
   315
        
jaroslav@357
   316
        public Page(Res res, String resource, String... args) {
jaroslav@357
   317
            this.res = res;
jaroslav@332
   318
            this.resource = resource;
jaroslav@331
   319
            this.args = args;
jaroslav@330
   320
        }
jaroslav@330
   321
jaroslav@330
   322
        @Override
jaroslav@330
   323
        public void service(Request request, Response response) throws Exception {
jaroslav@357
   324
            String r = resource;
jaroslav@357
   325
            if (r == null) {
jaroslav@357
   326
                r = request.getHttpHandlerPath();
jaroslav@357
   327
                if (r.startsWith("/")) {
jaroslav@357
   328
                    r = r.substring(1);
jaroslav@357
   329
                }
jaroslav@357
   330
            }
jaroslav@357
   331
            if (r.endsWith(".html") || r.endsWith(".xhtml")) {
jaroslav@357
   332
                response.setContentType("text/html");
jaroslav@357
   333
            }
jaroslav@330
   334
            OutputStream os = response.getOutputStream();
jaroslav@357
   335
            try (InputStream is = res.get(r)) {
jaroslav@357
   336
                copyStream(is, os, request.getRequestURL().toString(), args);
jaroslav@357
   337
            } catch (IOException ex) {
jaroslav@357
   338
                response.setDetailMessage(ex.getLocalizedMessage());
jaroslav@357
   339
                response.setError();
jaroslav@357
   340
                response.setStatus(404);
jaroslav@357
   341
            }
jaroslav@330
   342
        }
jaroslav@330
   343
    }
jaroslav@330
   344
jaroslav@330
   345
    private static class VM extends HttpHandler {
jaroslav@348
   346
        private final Res loader;
jaroslav@330
   347
jaroslav@348
   348
        public VM(Res loader) {
jaroslav@330
   349
            this.loader = loader;
jaroslav@330
   350
        }
jaroslav@330
   351
jaroslav@330
   352
        @Override
jaroslav@330
   353
        public void service(Request request, Response response) throws Exception {
jaroslav@330
   354
            response.setCharacterEncoding("UTF-8");
jaroslav@330
   355
            response.setContentType("text/javascript");
jaroslav@330
   356
            Bck2Brwsr.generate(response.getWriter(), loader);
jaroslav@330
   357
        }
jaroslav@330
   358
    }
jaroslav@332
   359
    private static class VMInit extends HttpHandler {
jaroslav@332
   360
        public VMInit() {
jaroslav@332
   361
        }
jaroslav@332
   362
jaroslav@332
   363
        @Override
jaroslav@332
   364
        public void service(Request request, Response response) throws Exception {
jaroslav@332
   365
            response.setCharacterEncoding("UTF-8");
jaroslav@332
   366
            response.setContentType("text/javascript");
jaroslav@332
   367
            response.getWriter().append(
jaroslav@332
   368
                "function ldCls(res) {\n"
jaroslav@332
   369
                + "  var request = new XMLHttpRequest();\n"
jaroslav@357
   370
                + "  request.open('GET', '/classes/' + res, false);\n"
jaroslav@332
   371
                + "  request.send();\n"
jaroslav@332
   372
                + "  var arr = eval('(' + request.responseText + ')');\n"
jaroslav@332
   373
                + "  return arr;\n"
jaroslav@332
   374
                + "}\n"
jaroslav@332
   375
                + "var vm = new bck2brwsr(ldCls);\n");
jaroslav@332
   376
        }
jaroslav@332
   377
    }
jaroslav@330
   378
jaroslav@330
   379
    private static class Classes extends HttpHandler {
jaroslav@348
   380
        private final Res loader;
jaroslav@330
   381
jaroslav@348
   382
        public Classes(Res loader) {
jaroslav@330
   383
            this.loader = loader;
jaroslav@330
   384
        }
jaroslav@330
   385
jaroslav@330
   386
        @Override
jaroslav@330
   387
        public void service(Request request, Response response) throws Exception {
jaroslav@330
   388
            String res = request.getHttpHandlerPath();
jaroslav@330
   389
            if (res.startsWith("/")) {
jaroslav@330
   390
                res = res.substring(1);
jaroslav@330
   391
            }
jaroslav@348
   392
            try (InputStream is = loader.get(res)) {
jaroslav@348
   393
                response.setContentType("text/javascript");
jaroslav@348
   394
                Writer w = response.getWriter();
jaroslav@348
   395
                w.append("[");
jaroslav@348
   396
                for (int i = 0;; i++) {
jaroslav@348
   397
                    int b = is.read();
jaroslav@348
   398
                    if (b == -1) {
jaroslav@348
   399
                        break;
jaroslav@348
   400
                    }
jaroslav@348
   401
                    if (i > 0) {
jaroslav@348
   402
                        w.append(", ");
jaroslav@348
   403
                    }
jaroslav@348
   404
                    if (i % 20 == 0) {
jaroslav@348
   405
                        w.write("\n");
jaroslav@348
   406
                    }
jaroslav@348
   407
                    if (b > 127) {
jaroslav@348
   408
                        b = b - 256;
jaroslav@348
   409
                    }
jaroslav@348
   410
                    w.append(Integer.toString(b));
jaroslav@348
   411
                }
jaroslav@348
   412
                w.append("\n]");
jaroslav@348
   413
            } catch (IOException ex) {
jaroslav@348
   414
                response.setError();
jaroslav@348
   415
                response.setDetailMessage(ex.getMessage());
jaroslav@330
   416
            }
jaroslav@330
   417
        }
jaroslav@330
   418
    }
jaroslav@323
   419
}