Support relaunching of test cases. Just reload the initial browser page and the test cases will be executed again. Useful when setting breakpoints.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.bck2brwsr.launcher;
20 import java.io.Closeable;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InterruptedIOException;
25 import java.io.OutputStream;
26 import java.io.Writer;
28 import java.net.URISyntaxException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Enumeration;
33 import java.util.LinkedHashSet;
34 import java.util.List;
36 import java.util.concurrent.BlockingQueue;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.LinkedBlockingQueue;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
43 import org.apidesign.vm4brwsr.Bck2Brwsr;
44 import org.glassfish.grizzly.PortRange;
45 import org.glassfish.grizzly.http.server.HttpHandler;
46 import org.glassfish.grizzly.http.server.HttpServer;
47 import org.glassfish.grizzly.http.server.NetworkListener;
48 import org.glassfish.grizzly.http.server.Request;
49 import org.glassfish.grizzly.http.server.Response;
50 import org.glassfish.grizzly.http.server.ServerConfiguration;
53 * Lightweight server to launch Bck2Brwsr applications and tests.
54 * Supports execution in native browser as well as Java's internal
57 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
58 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
59 private static final InvocationContext END = new InvocationContext(null, null, null);
60 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
63 private final Res resources = new Res();
64 private final String cmd;
65 private Object[] brwsr;
66 private HttpServer server;
67 private CountDownLatch wait;
69 public Bck2BrwsrLauncher(String cmd) {
74 InvocationContext runMethod(InvocationContext c) throws IOException {
75 loaders.add(c.clazz.getClassLoader());
79 } catch (InterruptedException ex) {
80 throw new IOException(ex);
85 public void setTimeout(long ms) {
89 public void addClassLoader(ClassLoader url) {
90 this.loaders.add(url);
93 public void showURL(String startpage) throws IOException {
94 if (!startpage.startsWith("/")) {
95 startpage = "/" + startpage;
97 HttpServer s = initServer(".", true);
98 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
100 launchServerAndBrwsr(s, startpage);
101 } catch (URISyntaxException | InterruptedException ex) {
102 throw new IOException(ex);
106 void showDirectory(File dir, String startpage) throws IOException {
107 if (!startpage.startsWith("/")) {
108 startpage = "/" + startpage;
110 HttpServer s = initServer(dir.getPath(), false);
112 launchServerAndBrwsr(s, startpage);
113 } catch (URISyntaxException | InterruptedException ex) {
114 throw new IOException(ex);
119 public void initialize() throws IOException {
122 } catch (InterruptedException ex) {
123 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
126 } catch (Exception ex) {
127 if (ex instanceof IOException) {
128 throw (IOException)ex;
130 if (ex instanceof RuntimeException) {
131 throw (RuntimeException)ex;
133 throw new IOException(ex);
137 private HttpServer initServer(String path, boolean addClasses) throws IOException {
138 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
140 final ServerConfiguration conf = s.getServerConfiguration();
142 conf.addHttpHandler(new VM(resources), "/vm.js");
143 conf.addHttpHandler(new Classes(resources), "/classes/");
148 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
149 wait = new CountDownLatch(1);
150 server = initServer(".", true);
151 final ServerConfiguration conf = server.getServerConfiguration();
153 class DynamicResourceHandler extends HttpHandler {
154 private final InvocationContext ic;
155 public DynamicResourceHandler(InvocationContext ic) {
156 if (ic == null || ic.resources.isEmpty()) {
157 throw new NullPointerException();
160 for (Resource r : ic.resources) {
161 conf.addHttpHandler(this, r.httpPath);
165 public void close() {
166 conf.removeHttpHandler(this);
170 public void service(Request request, Response response) throws Exception {
171 for (Resource r : ic.resources) {
172 if (r.httpPath.equals(request.getRequestURI())) {
173 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
174 response.setContentType(r.httpType);
175 copyStream(r.httpContent, response.getOutputStream(), null);
181 conf.addHttpHandler(new Page(resources,
182 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
185 conf.addHttpHandler(new HttpHandler() {
187 List<InvocationContext> cases = new ArrayList<>();
188 DynamicResourceHandler prev;
190 public void service(Request request, Response response) throws Exception {
191 String id = request.getParameter("request");
192 String value = request.getParameter("result");
195 InvocationContext mi = null;
198 if (id != null && value != null) {
199 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
200 value = decodeURL(value);
201 int indx = Integer.parseInt(id);
202 cases.get(indx).result(value, null);
203 if (++indx < cases.size()) {
204 mi = cases.get(indx);
205 LOG.log(Level.INFO, "Re-executing case {0}", indx);
209 if (!cases.isEmpty()) {
210 LOG.info("Re-executing test cases");
226 response.getWriter().write("");
229 LOG.log(Level.INFO, "End of data reached. Exiting.");
233 if (!mi.resources.isEmpty()) {
234 prev = new DynamicResourceHandler(mi);
238 final String cn = mi.clazz.getName();
239 final String mn = mi.methodName;
240 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
241 response.getWriter().write("{"
242 + "className: '" + cn + "', "
243 + "methodName: '" + mn + "', "
244 + "request: " + caseNmbr
246 if (mi.html != null) {
247 response.getWriter().write(", html: '");
248 response.getWriter().write(encodeJSON(mi.html));
249 response.getWriter().write("'");
251 response.getWriter().write("}");
255 this.brwsr = launchServerAndBrwsr(server, "/execute");
258 private static String encodeJSON(String in) {
259 StringBuilder sb = new StringBuilder();
260 for (int i = 0; i < in.length(); i++) {
261 char ch = in.charAt(i);
262 if (ch < 32 || ch == '\'' || ch == '"') {
264 String hs = "0000" + Integer.toHexString(ch);
265 hs = hs.substring(hs.length() - 4);
271 return sb.toString();
275 public void shutdown() throws IOException {
278 int prev = methods.size();
280 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
283 } catch (InterruptedException ex) {
284 throw new IOException(ex);
286 if (prev == methods.size()) {
289 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
295 "Timeout, but tests got from {0} to {1}. Trying again.",
296 new Object[]{prev, methods.size()}
299 stopServerAndBrwsr(server, brwsr);
302 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
308 if (ch == '$' && params.length > 0) {
309 int cnt = is.read() - '0';
310 if (cnt == 'U' - '0') {
311 os.write(baseURL.getBytes());
313 if (cnt >= 0 && cnt < params.length) {
314 os.write(params[cnt].getBytes());
322 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
324 NetworkListener listener = server.getListeners().iterator().next();
325 int port = listener.getPort();
327 URI uri = new URI("http://localhost:" + port + page);
328 LOG.log(Level.INFO, "Showing {0}", uri);
331 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
332 System.getProperty("java.vm.name"),
333 System.getProperty("java.vm.vendor"),
334 System.getProperty("java.vm.version"),
336 java.awt.Desktop.getDesktop().browse(uri);
337 LOG.log(Level.INFO, "Desktop.browse successfully finished");
339 } catch (UnsupportedOperationException ex) {
340 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
341 LOG.log(Level.FINE, null, ex);
345 String cmdName = cmd == null ? "xdg-open" : cmd;
347 cmdName, uri.toString()
349 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
350 final Process process = Runtime.getRuntime().exec(cmdArr);
351 return new Object[] { process, null };
355 private static String decodeURL(String s) {
357 int pos = s.indexOf('%');
361 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
362 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
366 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
370 Process process = (Process)brwsr[0];
373 InputStream stdout = process.getInputStream();
374 InputStream stderr = process.getErrorStream();
375 drain("StdOut", stdout);
376 drain("StdErr", stderr);
380 res = process.waitFor();
381 } catch (InterruptedException ex) {
382 throw new IOException(ex);
384 LOG.log(Level.INFO, "Exit code: {0}", res);
386 deleteTree((File)brwsr[1]);
389 private static void drain(String name, InputStream is) throws IOException {
390 int av = is.available();
392 StringBuilder sb = new StringBuilder();
393 sb.append("v== ").append(name).append(" ==v\n");
395 sb.append((char)is.read());
397 sb.append("\n^== ").append(name).append(" ==^");
398 LOG.log(Level.INFO, sb.toString());
402 private void deleteTree(File file) {
406 File[] arr = file.listFiles();
416 public void close() throws IOException {
420 private class Res implements Bck2Brwsr.Resources {
422 public InputStream get(String resource) throws IOException {
423 for (ClassLoader l : loaders) {
425 Enumeration<URL> en = l.getResources(resource);
426 while (en.hasMoreElements()) {
427 u = en.nextElement();
430 return u.openStream();
433 throw new IOException("Can't find " + resource);
437 private static class Page extends HttpHandler {
438 private final String resource;
439 private final String[] args;
440 private final Res res;
442 public Page(Res res, String resource, String... args) {
444 this.resource = resource;
445 this.args = args.length == 0 ? new String[] { "$0" } : args;
449 public void service(Request request, Response response) throws Exception {
452 r = request.getHttpHandlerPath();
453 if (r.startsWith("/")) {
457 String[] replace = {};
458 if (r.endsWith(".html")) {
459 response.setContentType("text/html");
460 LOG.info("Content type text/html");
463 if (r.endsWith(".xhtml")) {
464 response.setContentType("application/xhtml+xml");
465 LOG.info("Content type application/xhtml+xml");
468 OutputStream os = response.getOutputStream();
469 try (InputStream is = res.get(r)) {
470 copyStream(is, os, request.getRequestURL().toString(), replace);
471 } catch (IOException ex) {
472 response.setDetailMessage(ex.getLocalizedMessage());
474 response.setStatus(404);
479 private static class VM extends HttpHandler {
480 private final String bck2brwsr;
482 public VM(Res loader) throws IOException {
483 StringBuilder sb = new StringBuilder();
484 Bck2Brwsr.generate(sb, loader);
486 "function ldCls(res) {\n"
487 + " var request = new XMLHttpRequest();\n"
488 + " request.open('GET', '/classes/' + res, false);\n"
489 + " request.send();\n"
490 + " var arr = eval('(' + request.responseText + ')');\n"
493 + "var vm = new bck2brwsr(ldCls);\n"
495 this.bck2brwsr = sb.toString();
499 public void service(Request request, Response response) throws Exception {
500 response.setCharacterEncoding("UTF-8");
501 response.setContentType("text/javascript");
502 response.getWriter().write(bck2brwsr);
506 private static class Classes extends HttpHandler {
507 private final Res loader;
509 public Classes(Res loader) {
510 this.loader = loader;
514 public void service(Request request, Response response) throws Exception {
515 String res = request.getHttpHandlerPath();
516 if (res.startsWith("/")) {
517 res = res.substring(1);
519 try (InputStream is = loader.get(res)) {
520 response.setContentType("text/javascript");
521 Writer w = response.getWriter();
523 for (int i = 0;; i++) {
537 w.append(Integer.toString(b));
540 } catch (IOException ex) {
542 response.setDetailMessage(ex.getMessage());