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