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