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