1.1 --- a/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java Thu Feb 14 12:06:16 2013 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,523 +0,0 @@
1.4 -/**
1.5 - * Back 2 Browser Bytecode Translator
1.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
1.7 - *
1.8 - * This program is free software: you can redistribute it and/or modify
1.9 - * it under the terms of the GNU General Public License as published by
1.10 - * the Free Software Foundation, version 2 of the License.
1.11 - *
1.12 - * This program is distributed in the hope that it will be useful,
1.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
1.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1.15 - * GNU General Public License for more details.
1.16 - *
1.17 - * You should have received a copy of the GNU General Public License
1.18 - * along with this program. Look for COPYING file in the top folder.
1.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
1.20 - */
1.21 -package org.apidesign.bck2brwsr.launcher;
1.22 -
1.23 -import java.io.Closeable;
1.24 -import java.io.File;
1.25 -import java.io.IOException;
1.26 -import java.io.InputStream;
1.27 -import java.io.InterruptedIOException;
1.28 -import java.io.OutputStream;
1.29 -import java.io.Writer;
1.30 -import java.net.URI;
1.31 -import java.net.URISyntaxException;
1.32 -import java.net.URL;
1.33 -import java.util.ArrayList;
1.34 -import java.util.Arrays;
1.35 -import java.util.Enumeration;
1.36 -import java.util.LinkedHashSet;
1.37 -import java.util.List;
1.38 -import java.util.Set;
1.39 -import java.util.concurrent.BlockingQueue;
1.40 -import java.util.concurrent.CountDownLatch;
1.41 -import java.util.concurrent.LinkedBlockingQueue;
1.42 -import java.util.concurrent.TimeUnit;
1.43 -import java.util.logging.Level;
1.44 -import java.util.logging.Logger;
1.45 -import org.apidesign.vm4brwsr.Bck2Brwsr;
1.46 -import org.glassfish.grizzly.PortRange;
1.47 -import org.glassfish.grizzly.http.server.HttpHandler;
1.48 -import org.glassfish.grizzly.http.server.HttpServer;
1.49 -import org.glassfish.grizzly.http.server.NetworkListener;
1.50 -import org.glassfish.grizzly.http.server.Request;
1.51 -import org.glassfish.grizzly.http.server.Response;
1.52 -import org.glassfish.grizzly.http.server.ServerConfiguration;
1.53 -
1.54 -/**
1.55 - * Lightweight server to launch Bck2Brwsr applications and tests.
1.56 - * Supports execution in native browser as well as Java's internal
1.57 - * execution engine.
1.58 - */
1.59 -final class Bck2BrwsrLauncher extends Launcher implements Closeable {
1.60 - private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
1.61 - private static final InvocationContext END = new InvocationContext(null, null, null);
1.62 - private final Set<ClassLoader> loaders = new LinkedHashSet<>();
1.63 - private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
1.64 - private long timeOut;
1.65 - private final Res resources = new Res();
1.66 - private final String cmd;
1.67 - private Object[] brwsr;
1.68 - private HttpServer server;
1.69 - private CountDownLatch wait;
1.70 -
1.71 - public Bck2BrwsrLauncher(String cmd) {
1.72 - this.cmd = cmd;
1.73 - }
1.74 -
1.75 - @Override
1.76 - InvocationContext runMethod(InvocationContext c) throws IOException {
1.77 - loaders.add(c.clazz.getClassLoader());
1.78 - methods.add(c);
1.79 - try {
1.80 - c.await(timeOut);
1.81 - } catch (InterruptedException ex) {
1.82 - throw new IOException(ex);
1.83 - }
1.84 - return c;
1.85 - }
1.86 -
1.87 - public void setTimeout(long ms) {
1.88 - timeOut = ms;
1.89 - }
1.90 -
1.91 - public void addClassLoader(ClassLoader url) {
1.92 - this.loaders.add(url);
1.93 - }
1.94 -
1.95 - public void showURL(String startpage) throws IOException {
1.96 - if (!startpage.startsWith("/")) {
1.97 - startpage = "/" + startpage;
1.98 - }
1.99 - HttpServer s = initServer(".", true);
1.100 - s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
1.101 - try {
1.102 - launchServerAndBrwsr(s, startpage);
1.103 - } catch (URISyntaxException | InterruptedException ex) {
1.104 - throw new IOException(ex);
1.105 - }
1.106 - }
1.107 -
1.108 - void showDirectory(File dir, String startpage) throws IOException {
1.109 - if (!startpage.startsWith("/")) {
1.110 - startpage = "/" + startpage;
1.111 - }
1.112 - HttpServer s = initServer(dir.getPath(), false);
1.113 - try {
1.114 - launchServerAndBrwsr(s, startpage);
1.115 - } catch (URISyntaxException | InterruptedException ex) {
1.116 - throw new IOException(ex);
1.117 - }
1.118 - }
1.119 -
1.120 - @Override
1.121 - public void initialize() throws IOException {
1.122 - try {
1.123 - executeInBrowser();
1.124 - } catch (InterruptedException ex) {
1.125 - final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
1.126 - iio.initCause(ex);
1.127 - throw iio;
1.128 - } catch (Exception ex) {
1.129 - if (ex instanceof IOException) {
1.130 - throw (IOException)ex;
1.131 - }
1.132 - if (ex instanceof RuntimeException) {
1.133 - throw (RuntimeException)ex;
1.134 - }
1.135 - throw new IOException(ex);
1.136 - }
1.137 - }
1.138 -
1.139 - private HttpServer initServer(String path, boolean addClasses) throws IOException {
1.140 - HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
1.141 -
1.142 - final ServerConfiguration conf = s.getServerConfiguration();
1.143 - if (addClasses) {
1.144 - conf.addHttpHandler(new VM(resources), "/vm.js");
1.145 - conf.addHttpHandler(new Classes(resources), "/classes/");
1.146 - }
1.147 - return s;
1.148 - }
1.149 -
1.150 - private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
1.151 - wait = new CountDownLatch(1);
1.152 - server = initServer(".", true);
1.153 - final ServerConfiguration conf = server.getServerConfiguration();
1.154 -
1.155 - class DynamicResourceHandler extends HttpHandler {
1.156 - private final InvocationContext ic;
1.157 - public DynamicResourceHandler(InvocationContext ic) {
1.158 - if (ic == null || ic.httpPath == null) {
1.159 - throw new NullPointerException();
1.160 - }
1.161 - this.ic = ic;
1.162 - conf.addHttpHandler(this, ic.httpPath);
1.163 - }
1.164 -
1.165 - public void close() {
1.166 - conf.removeHttpHandler(this);
1.167 - }
1.168 -
1.169 - @Override
1.170 - public void service(Request request, Response response) throws Exception {
1.171 - if (ic.httpPath.equals(request.getRequestURI())) {
1.172 - LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
1.173 - response.setContentType(ic.httpType);
1.174 - copyStream(ic.httpContent, response.getOutputStream(), null);
1.175 - }
1.176 - }
1.177 - }
1.178 -
1.179 - conf.addHttpHandler(new Page(resources,
1.180 - "org/apidesign/bck2brwsr/launcher/harness.xhtml"
1.181 - ), "/execute");
1.182 -
1.183 - conf.addHttpHandler(new HttpHandler() {
1.184 - int cnt;
1.185 - List<InvocationContext> cases = new ArrayList<>();
1.186 - DynamicResourceHandler prev;
1.187 - @Override
1.188 - public void service(Request request, Response response) throws Exception {
1.189 - String id = request.getParameter("request");
1.190 - String value = request.getParameter("result");
1.191 -
1.192 - if (id != null && value != null) {
1.193 - LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
1.194 - value = decodeURL(value);
1.195 - cases.get(Integer.parseInt(id)).result(value, null);
1.196 - }
1.197 -
1.198 - if (prev != null) {
1.199 - prev.close();
1.200 - prev = null;
1.201 - }
1.202 -
1.203 - InvocationContext mi = methods.take();
1.204 - if (mi == END) {
1.205 - response.getWriter().write("");
1.206 - wait.countDown();
1.207 - cnt = 0;
1.208 - LOG.log(Level.INFO, "End of data reached. Exiting.");
1.209 - return;
1.210 - }
1.211 -
1.212 - if (mi.httpPath != null) {
1.213 - prev = new DynamicResourceHandler(mi);
1.214 - }
1.215 -
1.216 - cases.add(mi);
1.217 - final String cn = mi.clazz.getName();
1.218 - final String mn = mi.methodName;
1.219 - LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
1.220 - response.getWriter().write("{"
1.221 - + "className: '" + cn + "', "
1.222 - + "methodName: '" + mn + "', "
1.223 - + "request: " + cnt
1.224 - );
1.225 - if (mi.html != null) {
1.226 - response.getWriter().write(", html: '");
1.227 - response.getWriter().write(encodeJSON(mi.html));
1.228 - response.getWriter().write("'");
1.229 - }
1.230 - response.getWriter().write("}");
1.231 - cnt++;
1.232 - }
1.233 - }, "/data");
1.234 -
1.235 - this.brwsr = launchServerAndBrwsr(server, "/execute");
1.236 - }
1.237 -
1.238 - private static String encodeJSON(String in) {
1.239 - StringBuilder sb = new StringBuilder();
1.240 - for (int i = 0; i < in.length(); i++) {
1.241 - char ch = in.charAt(i);
1.242 - if (ch < 32 || ch == '\'' || ch == '"') {
1.243 - sb.append("\\u");
1.244 - String hs = "0000" + Integer.toHexString(ch);
1.245 - hs = hs.substring(hs.length() - 4);
1.246 - sb.append(hs);
1.247 - } else {
1.248 - sb.append(ch);
1.249 - }
1.250 - }
1.251 - return sb.toString();
1.252 - }
1.253 -
1.254 - @Override
1.255 - public void shutdown() throws IOException {
1.256 - methods.offer(END);
1.257 - for (;;) {
1.258 - int prev = methods.size();
1.259 - try {
1.260 - if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
1.261 - break;
1.262 - }
1.263 - } catch (InterruptedException ex) {
1.264 - throw new IOException(ex);
1.265 - }
1.266 - if (prev == methods.size()) {
1.267 - LOG.log(
1.268 - Level.WARNING,
1.269 - "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
1.270 - methods.size()
1.271 - );
1.272 - break;
1.273 - }
1.274 - LOG.log(Level.INFO,
1.275 - "Timeout, but tests got from {0} to {1}. Trying again.",
1.276 - new Object[]{prev, methods.size()}
1.277 - );
1.278 - }
1.279 - stopServerAndBrwsr(server, brwsr);
1.280 - }
1.281 -
1.282 - static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
1.283 - for (;;) {
1.284 - int ch = is.read();
1.285 - if (ch == -1) {
1.286 - break;
1.287 - }
1.288 - if (ch == '$' && params.length > 0) {
1.289 - int cnt = is.read() - '0';
1.290 - if (cnt == 'U' - '0') {
1.291 - os.write(baseURL.getBytes("UTF-8"));
1.292 - }
1.293 - if (cnt >= 0 && cnt < params.length) {
1.294 - os.write(params[cnt].getBytes("UTF-8"));
1.295 - }
1.296 - } else {
1.297 - os.write(ch);
1.298 - }
1.299 - }
1.300 - }
1.301 -
1.302 - private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
1.303 - server.start();
1.304 - NetworkListener listener = server.getListeners().iterator().next();
1.305 - int port = listener.getPort();
1.306 -
1.307 - URI uri = new URI("http://localhost:" + port + page);
1.308 - LOG.log(Level.INFO, "Showing {0}", uri);
1.309 - if (cmd == null) {
1.310 - try {
1.311 - LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
1.312 - System.getProperty("java.vm.name"),
1.313 - System.getProperty("java.vm.vendor"),
1.314 - System.getProperty("java.vm.version"),
1.315 - });
1.316 - java.awt.Desktop.getDesktop().browse(uri);
1.317 - LOG.log(Level.INFO, "Desktop.browse successfully finished");
1.318 - return null;
1.319 - } catch (UnsupportedOperationException ex) {
1.320 - LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
1.321 - LOG.log(Level.FINE, null, ex);
1.322 - }
1.323 - }
1.324 - {
1.325 - String cmdName = cmd == null ? "xdg-open" : cmd;
1.326 - String[] cmdArr = {
1.327 - cmdName, uri.toString()
1.328 - };
1.329 - LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
1.330 - final Process process = Runtime.getRuntime().exec(cmdArr);
1.331 - return new Object[] { process, null };
1.332 - }
1.333 - }
1.334 -
1.335 - private static String decodeURL(String s) {
1.336 - for (;;) {
1.337 - int pos = s.indexOf('%');
1.338 - if (pos == -1) {
1.339 - return s;
1.340 - }
1.341 - int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
1.342 - s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
1.343 - }
1.344 - }
1.345 -
1.346 - private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
1.347 - if (brwsr == null) {
1.348 - return;
1.349 - }
1.350 - Process process = (Process)brwsr[0];
1.351 -
1.352 - server.stop();
1.353 - InputStream stdout = process.getInputStream();
1.354 - InputStream stderr = process.getErrorStream();
1.355 - drain("StdOut", stdout);
1.356 - drain("StdErr", stderr);
1.357 - process.destroy();
1.358 - int res;
1.359 - try {
1.360 - res = process.waitFor();
1.361 - } catch (InterruptedException ex) {
1.362 - throw new IOException(ex);
1.363 - }
1.364 - LOG.log(Level.INFO, "Exit code: {0}", res);
1.365 -
1.366 - deleteTree((File)brwsr[1]);
1.367 - }
1.368 -
1.369 - private static void drain(String name, InputStream is) throws IOException {
1.370 - int av = is.available();
1.371 - if (av > 0) {
1.372 - StringBuilder sb = new StringBuilder();
1.373 - sb.append("v== ").append(name).append(" ==v\n");
1.374 - while (av-- > 0) {
1.375 - sb.append((char)is.read());
1.376 - }
1.377 - sb.append("\n^== ").append(name).append(" ==^");
1.378 - LOG.log(Level.INFO, sb.toString());
1.379 - }
1.380 - }
1.381 -
1.382 - private void deleteTree(File file) {
1.383 - if (file == null) {
1.384 - return;
1.385 - }
1.386 - File[] arr = file.listFiles();
1.387 - if (arr != null) {
1.388 - for (File s : arr) {
1.389 - deleteTree(s);
1.390 - }
1.391 - }
1.392 - file.delete();
1.393 - }
1.394 -
1.395 - @Override
1.396 - public void close() throws IOException {
1.397 - shutdown();
1.398 - }
1.399 -
1.400 - private class Res implements Bck2Brwsr.Resources {
1.401 - @Override
1.402 - public InputStream get(String resource) throws IOException {
1.403 - for (ClassLoader l : loaders) {
1.404 - URL u = null;
1.405 - Enumeration<URL> en = l.getResources(resource);
1.406 - while (en.hasMoreElements()) {
1.407 - u = en.nextElement();
1.408 - }
1.409 - if (u != null) {
1.410 - return u.openStream();
1.411 - }
1.412 - }
1.413 - throw new IOException("Can't find " + resource);
1.414 - }
1.415 - }
1.416 -
1.417 - private static class Page extends HttpHandler {
1.418 - private final String resource;
1.419 - private final String[] args;
1.420 - private final Res res;
1.421 -
1.422 - public Page(Res res, String resource, String... args) {
1.423 - this.res = res;
1.424 - this.resource = resource;
1.425 - this.args = args.length == 0 ? new String[] { "$0" } : args;
1.426 - }
1.427 -
1.428 - @Override
1.429 - public void service(Request request, Response response) throws Exception {
1.430 - String r = resource;
1.431 - if (r == null) {
1.432 - r = request.getHttpHandlerPath();
1.433 - if (r.startsWith("/")) {
1.434 - r = r.substring(1);
1.435 - }
1.436 - }
1.437 - String[] replace = {};
1.438 - if (r.endsWith(".html")) {
1.439 - response.setContentType("text/html");
1.440 - LOG.info("Content type text/html");
1.441 - replace = args;
1.442 - }
1.443 - if (r.endsWith(".xhtml")) {
1.444 - response.setContentType("application/xhtml+xml");
1.445 - LOG.info("Content type application/xhtml+xml");
1.446 - replace = args;
1.447 - }
1.448 - OutputStream os = response.getOutputStream();
1.449 - try (InputStream is = res.get(r)) {
1.450 - copyStream(is, os, request.getRequestURL().toString(), replace);
1.451 - } catch (IOException ex) {
1.452 - response.setDetailMessage(ex.getLocalizedMessage());
1.453 - response.setError();
1.454 - response.setStatus(404);
1.455 - }
1.456 - }
1.457 - }
1.458 -
1.459 - private static class VM extends HttpHandler {
1.460 - private final String bck2brwsr;
1.461 -
1.462 - public VM(Res loader) throws IOException {
1.463 - StringBuilder sb = new StringBuilder();
1.464 - Bck2Brwsr.generate(sb, loader);
1.465 - sb.append(
1.466 - "function ldCls(res) {\n"
1.467 - + " var request = new XMLHttpRequest();\n"
1.468 - + " request.open('GET', '/classes/' + res, false);\n"
1.469 - + " request.send();\n"
1.470 - + " var arr = eval('(' + request.responseText + ')');\n"
1.471 - + " return arr;\n"
1.472 - + "}\n"
1.473 - + "var vm = new bck2brwsr(ldCls);\n"
1.474 - );
1.475 - this.bck2brwsr = sb.toString();
1.476 - }
1.477 -
1.478 - @Override
1.479 - public void service(Request request, Response response) throws Exception {
1.480 - response.setCharacterEncoding("UTF-8");
1.481 - response.setContentType("text/javascript");
1.482 - response.getWriter().write(bck2brwsr);
1.483 - }
1.484 - }
1.485 -
1.486 - private static class Classes extends HttpHandler {
1.487 - private final Res loader;
1.488 -
1.489 - public Classes(Res loader) {
1.490 - this.loader = loader;
1.491 - }
1.492 -
1.493 - @Override
1.494 - public void service(Request request, Response response) throws Exception {
1.495 - String res = request.getHttpHandlerPath();
1.496 - if (res.startsWith("/")) {
1.497 - res = res.substring(1);
1.498 - }
1.499 - try (InputStream is = loader.get(res)) {
1.500 - response.setContentType("text/javascript");
1.501 - Writer w = response.getWriter();
1.502 - w.append("[");
1.503 - for (int i = 0;; i++) {
1.504 - int b = is.read();
1.505 - if (b == -1) {
1.506 - break;
1.507 - }
1.508 - if (i > 0) {
1.509 - w.append(", ");
1.510 - }
1.511 - if (i % 20 == 0) {
1.512 - w.write("\n");
1.513 - }
1.514 - if (b > 127) {
1.515 - b = b - 256;
1.516 - }
1.517 - w.append(Integer.toString(b));
1.518 - }
1.519 - w.append("\n]");
1.520 - } catch (IOException ex) {
1.521 - response.setError();
1.522 - response.setDetailMessage(ex.getMessage());
1.523 - }
1.524 - }
1.525 - }
1.526 -}