rt/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
Need to merge in default branch: It contains automatic conversion of boxed types to primitive values which is needed by Knockout to display elements of arrays properly.
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.UnsupportedEncodingException;
27 import java.io.Writer;
29 import java.net.URISyntaxException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Enumeration;
34 import java.util.LinkedHashSet;
35 import java.util.List;
37 import java.util.concurrent.BlockingQueue;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.LinkedBlockingQueue;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
43 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
44 import org.apidesign.vm4brwsr.Bck2Brwsr;
45 import org.glassfish.grizzly.PortRange;
46 import org.glassfish.grizzly.http.server.HttpHandler;
47 import org.glassfish.grizzly.http.server.HttpServer;
48 import org.glassfish.grizzly.http.server.NetworkListener;
49 import org.glassfish.grizzly.http.server.Request;
50 import org.glassfish.grizzly.http.server.Response;
51 import org.glassfish.grizzly.http.server.ServerConfiguration;
52 import org.glassfish.grizzly.http.util.HttpStatus;
55 * Lightweight server to launch Bck2Brwsr applications and tests.
56 * Supports execution in native browser as well as Java's internal
59 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
60 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
61 private static final InvocationContext END = new InvocationContext(null, null, null);
62 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
63 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
65 private final Res resources = new Res();
66 private final String cmd;
67 private Object[] brwsr;
68 private HttpServer server;
69 private CountDownLatch wait;
71 public Bck2BrwsrLauncher(String cmd) {
76 InvocationContext runMethod(InvocationContext c) throws IOException {
77 loaders.add(c.clazz.getClassLoader());
81 } catch (InterruptedException ex) {
82 throw new IOException(ex);
87 public void setTimeout(long ms) {
91 public void addClassLoader(ClassLoader url) {
92 this.loaders.add(url);
95 public void showURL(String startpage) throws IOException {
96 if (!startpage.startsWith("/")) {
97 startpage = "/" + startpage;
99 HttpServer s = initServer(".", true);
100 int last = startpage.lastIndexOf('/');
101 String simpleName = startpage.substring(last);
102 s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), simpleName);
103 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
105 launchServerAndBrwsr(s, simpleName);
106 } catch (URISyntaxException | InterruptedException ex) {
107 throw new IOException(ex);
111 void showDirectory(File dir, String startpage) throws IOException {
112 if (!startpage.startsWith("/")) {
113 startpage = "/" + startpage;
115 HttpServer s = initServer(dir.getPath(), false);
117 launchServerAndBrwsr(s, startpage);
118 } catch (URISyntaxException | InterruptedException ex) {
119 throw new IOException(ex);
124 public void initialize() throws IOException {
127 } catch (InterruptedException ex) {
128 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
131 } catch (Exception ex) {
132 if (ex instanceof IOException) {
133 throw (IOException)ex;
135 if (ex instanceof RuntimeException) {
136 throw (RuntimeException)ex;
138 throw new IOException(ex);
142 private HttpServer initServer(String path, boolean addClasses) throws IOException {
143 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
145 final ServerConfiguration conf = s.getServerConfiguration();
147 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
148 conf.addHttpHandler(new Classes(resources), "/classes/");
153 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
154 wait = new CountDownLatch(1);
155 server = initServer(".", true);
156 final ServerConfiguration conf = server.getServerConfiguration();
158 class DynamicResourceHandler extends HttpHandler {
159 private final InvocationContext ic;
160 public DynamicResourceHandler(InvocationContext ic) {
161 if (ic == null || ic.resources.isEmpty()) {
162 throw new NullPointerException();
165 for (Resource r : ic.resources) {
166 conf.addHttpHandler(this, r.httpPath);
170 public void close() {
171 conf.removeHttpHandler(this);
175 public void service(Request request, Response response) throws Exception {
176 for (Resource r : ic.resources) {
177 if (r.httpPath.equals(request.getRequestURI())) {
178 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
179 response.setContentType(r.httpType);
180 copyStream(r.httpContent, response.getOutputStream(), null);
186 conf.addHttpHandler(new Page(resources,
187 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
190 conf.addHttpHandler(new HttpHandler() {
192 List<InvocationContext> cases = new ArrayList<>();
193 DynamicResourceHandler prev;
195 public void service(Request request, Response response) throws Exception {
196 String id = request.getParameter("request");
197 String value = request.getParameter("result");
198 if (value != null && value.indexOf((char)0xC5) != -1) {
199 value = toUTF8(value);
203 InvocationContext mi = null;
206 if (id != null && value != null) {
207 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
208 value = decodeURL(value);
209 int indx = Integer.parseInt(id);
210 cases.get(indx).result(value, null);
211 if (++indx < cases.size()) {
212 mi = cases.get(indx);
213 LOG.log(Level.INFO, "Re-executing case {0}", indx);
217 if (!cases.isEmpty()) {
218 LOG.info("Re-executing test cases");
234 response.getWriter().write("");
237 LOG.log(Level.INFO, "End of data reached. Exiting.");
241 if (!mi.resources.isEmpty()) {
242 prev = new DynamicResourceHandler(mi);
246 final String cn = mi.clazz.getName();
247 final String mn = mi.methodName;
248 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
249 response.getWriter().write("{"
250 + "className: '" + cn + "', "
251 + "methodName: '" + mn + "', "
252 + "request: " + caseNmbr
254 if (mi.html != null) {
255 response.getWriter().write(", html: '");
256 response.getWriter().write(encodeJSON(mi.html));
257 response.getWriter().write("'");
259 response.getWriter().write("}");
263 this.brwsr = launchServerAndBrwsr(server, "/execute");
266 private static String encodeJSON(String in) {
267 StringBuilder sb = new StringBuilder();
268 for (int i = 0; i < in.length(); i++) {
269 char ch = in.charAt(i);
270 if (ch < 32 || ch == '\'' || ch == '"') {
272 String hs = "0000" + Integer.toHexString(ch);
273 hs = hs.substring(hs.length() - 4);
279 return sb.toString();
283 public void shutdown() throws IOException {
286 int prev = methods.size();
288 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
291 } catch (InterruptedException ex) {
292 throw new IOException(ex);
294 if (prev == methods.size()) {
297 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
303 "Timeout, but tests got from {0} to {1}. Trying again.",
304 new Object[]{prev, methods.size()}
307 stopServerAndBrwsr(server, brwsr);
310 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
316 if (ch == '$' && params.length > 0) {
317 int cnt = is.read() - '0';
318 if (cnt == 'U' - '0') {
319 os.write(baseURL.getBytes("UTF-8"));
321 if (cnt >= 0 && cnt < params.length) {
322 os.write(params[cnt].getBytes("UTF-8"));
334 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
336 NetworkListener listener = server.getListeners().iterator().next();
337 int port = listener.getPort();
339 URI uri = new URI("http://localhost:" + port + page);
340 LOG.log(Level.INFO, "Showing {0}", uri);
343 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
344 System.getProperty("java.vm.name"),
345 System.getProperty("java.vm.vendor"),
346 System.getProperty("java.vm.version"),
348 java.awt.Desktop.getDesktop().browse(uri);
349 LOG.log(Level.INFO, "Desktop.browse successfully finished");
351 } catch (UnsupportedOperationException ex) {
352 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
353 LOG.log(Level.FINE, null, ex);
357 String cmdName = cmd == null ? "xdg-open" : cmd;
359 cmdName, uri.toString()
361 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
362 final Process process = Runtime.getRuntime().exec(cmdArr);
363 return new Object[] { process, null };
366 private static String toUTF8(String value) throws UnsupportedEncodingException {
367 byte[] arr = new byte[value.length()];
368 for (int i = 0; i < arr.length; i++) {
369 arr[i] = (byte)value.charAt(i);
371 return new String(arr, "UTF-8");
374 private static String decodeURL(String s) {
376 int pos = s.indexOf('%');
380 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
381 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
385 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
389 Process process = (Process)brwsr[0];
392 InputStream stdout = process.getInputStream();
393 InputStream stderr = process.getErrorStream();
394 drain("StdOut", stdout);
395 drain("StdErr", stderr);
399 res = process.waitFor();
400 } catch (InterruptedException ex) {
401 throw new IOException(ex);
403 LOG.log(Level.INFO, "Exit code: {0}", res);
405 deleteTree((File)brwsr[1]);
408 private static void drain(String name, InputStream is) throws IOException {
409 int av = is.available();
411 StringBuilder sb = new StringBuilder();
412 sb.append("v== ").append(name).append(" ==v\n");
414 sb.append((char)is.read());
416 sb.append("\n^== ").append(name).append(" ==^");
417 LOG.log(Level.INFO, sb.toString());
421 private void deleteTree(File file) {
425 File[] arr = file.listFiles();
435 public void close() throws IOException {
439 private class Res implements Bck2Brwsr.Resources {
441 public InputStream get(String resource) throws IOException {
442 for (ClassLoader l : loaders) {
444 Enumeration<URL> en = l.getResources(resource);
445 while (en.hasMoreElements()) {
446 u = en.nextElement();
449 return u.openStream();
452 throw new IOException("Can't find " + resource);
456 private static class Page extends HttpHandler {
457 private final String resource;
458 private final String[] args;
459 private final Res res;
461 public Page(Res res, String resource, String... args) {
463 this.resource = resource;
464 this.args = args.length == 0 ? new String[] { "$0" } : args;
468 public void service(Request request, Response response) throws Exception {
471 r = request.getHttpHandlerPath();
473 if (r.startsWith("/")) {
476 String[] replace = {};
477 if (r.endsWith(".html")) {
478 response.setContentType("text/html");
479 LOG.info("Content type text/html");
482 if (r.endsWith(".xhtml")) {
483 response.setContentType("application/xhtml+xml");
484 LOG.info("Content type application/xhtml+xml");
487 OutputStream os = response.getOutputStream();
488 try (InputStream is = res.get(r)) {
489 copyStream(is, os, request.getRequestURL().toString(), replace);
490 } catch (IOException ex) {
491 response.setDetailMessage(ex.getLocalizedMessage());
493 response.setStatus(404);
498 private static class VM extends HttpHandler {
499 private final String bck2brwsr;
501 public VM(Res loader) throws IOException {
502 StringBuilder sb = new StringBuilder();
503 Bck2Brwsr.generate(sb, loader);
505 "(function WrapperVM(global) {"
506 + " function ldCls(res) {\n"
507 + " var request = new XMLHttpRequest();\n"
508 + " request.open('GET', '/classes/' + res, false);\n"
509 + " request.send();\n"
510 + " if (request.status !== 200) return null;\n"
511 + " var arr = eval('(' + request.responseText + ')');\n"
514 + " var prevvm = global.bck2brwsr;\n"
515 + " global.bck2brwsr = function() {\n"
516 + " var args = Array.prototype.slice.apply(arguments);\n"
517 + " args.unshift(ldCls);\n"
518 + " return prevvm.apply(null, args);\n"
522 this.bck2brwsr = sb.toString();
526 public void service(Request request, Response response) throws Exception {
527 response.setCharacterEncoding("UTF-8");
528 response.setContentType("text/javascript");
529 response.getWriter().write(bck2brwsr);
533 private static class Classes extends HttpHandler {
534 private final Res loader;
536 public Classes(Res loader) {
537 this.loader = loader;
541 public void service(Request request, Response response) throws Exception {
542 String res = request.getHttpHandlerPath();
543 if (res.startsWith("/")) {
544 res = res.substring(1);
546 try (InputStream is = loader.get(res)) {
547 response.setContentType("text/javascript");
548 Writer w = response.getWriter();
550 for (int i = 0;; i++) {
564 w.append(Integer.toString(b));
567 } catch (IOException ex) {
568 response.setStatus(HttpStatus.NOT_FOUND_404);
570 response.setDetailMessage(ex.getMessage());