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.vm4brwsr.Bck2Brwsr;
43 import org.glassfish.grizzly.PortRange;
44 import org.glassfish.grizzly.http.server.HttpHandler;
45 import org.glassfish.grizzly.http.server.HttpServer;
46 import org.glassfish.grizzly.http.server.NetworkListener;
47 import org.glassfish.grizzly.http.server.Request;
48 import org.glassfish.grizzly.http.server.Response;
49 import org.glassfish.grizzly.http.server.ServerConfiguration;
52 * Lightweight server to launch Bck2Brwsr applications and tests.
53 * Supports execution in native browser as well as Java's internal
56 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
57 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
58 private static final InvocationContext END = new InvocationContext(null, null, null);
59 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
60 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
62 private final Res resources = new Res();
63 private final String cmd;
64 private Object[] brwsr;
65 private HttpServer server;
66 private CountDownLatch wait;
68 public Bck2BrwsrLauncher(String cmd) {
73 InvocationContext runMethod(InvocationContext c) throws IOException {
74 loaders.add(c.clazz.getClassLoader());
78 } catch (InterruptedException ex) {
79 throw new IOException(ex);
84 public void setTimeout(long ms) {
88 public void addClassLoader(ClassLoader url) {
89 this.loaders.add(url);
92 public void showURL(String startpage) throws IOException {
93 if (!startpage.startsWith("/")) {
94 startpage = "/" + startpage;
96 HttpServer s = initServer(".", true);
97 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
99 launchServerAndBrwsr(s, startpage);
100 } catch (URISyntaxException | InterruptedException ex) {
101 throw new IOException(ex);
105 void showDirectory(File dir, String startpage) throws IOException {
106 if (!startpage.startsWith("/")) {
107 startpage = "/" + startpage;
109 HttpServer s = initServer(dir.getPath(), false);
111 launchServerAndBrwsr(s, startpage);
112 } catch (URISyntaxException | InterruptedException ex) {
113 throw new IOException(ex);
118 public void initialize() throws IOException {
121 } catch (InterruptedException ex) {
122 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
125 } catch (Exception ex) {
126 if (ex instanceof IOException) {
127 throw (IOException)ex;
129 if (ex instanceof RuntimeException) {
130 throw (RuntimeException)ex;
132 throw new IOException(ex);
136 private HttpServer initServer(String path, boolean addClasses) throws IOException {
137 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
139 final ServerConfiguration conf = s.getServerConfiguration();
141 conf.addHttpHandler(new VM(resources), "/vm.js");
142 conf.addHttpHandler(new Classes(resources), "/classes/");
147 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
148 wait = new CountDownLatch(1);
149 server = initServer(".", true);
150 ServerConfiguration conf = server.getServerConfiguration();
151 conf.addHttpHandler(new Page(resources,
152 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
154 conf.addHttpHandler(new HttpHandler() {
156 List<InvocationContext> cases = new ArrayList<>();
158 public void service(Request request, Response response) throws Exception {
159 String id = request.getParameter("request");
160 String value = request.getParameter("result");
162 if (id != null && value != null) {
163 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
164 value = decodeURL(value);
165 cases.get(Integer.parseInt(id)).result(value, null);
168 InvocationContext mi = methods.take();
170 response.getWriter().write("");
173 LOG.log(Level.INFO, "End of data reached. Exiting.");
178 final String cn = mi.clazz.getName();
179 final String mn = mi.methodName;
180 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
181 response.getWriter().write("{"
182 + "className: '" + cn + "', "
183 + "methodName: '" + mn + "', "
186 if (mi.html != null) {
187 response.getWriter().write(", html: '");
188 response.getWriter().write(encodeJSON(mi.html));
189 response.getWriter().write("'");
191 response.getWriter().write("}");
196 this.brwsr = launchServerAndBrwsr(server, "/execute");
199 private static String encodeJSON(String in) {
200 StringBuilder sb = new StringBuilder();
201 for (int i = 0; i < in.length(); i++) {
202 char ch = in.charAt(i);
203 if (ch < 32 || ch == '\'' || ch == '"') {
205 String hs = "0000" + Integer.toHexString(ch);
206 hs = hs.substring(hs.length() - 4);
212 return sb.toString();
216 public void shutdown() throws IOException {
219 int prev = methods.size();
221 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
224 } catch (InterruptedException ex) {
225 throw new IOException(ex);
227 if (prev == methods.size()) {
230 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
236 "Timeout, but tests got from {0} to {1}. Trying again.",
237 new Object[]{prev, methods.size()}
240 stopServerAndBrwsr(server, brwsr);
243 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
249 if (ch == '$' && params.length > 0) {
250 int cnt = is.read() - '0';
251 if (cnt == 'U' - '0') {
252 os.write(baseURL.getBytes());
254 if (cnt >= 0 && cnt < params.length) {
255 os.write(params[cnt].getBytes());
263 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
265 NetworkListener listener = server.getListeners().iterator().next();
266 int port = listener.getPort();
268 URI uri = new URI("http://localhost:" + port + page);
269 LOG.log(Level.INFO, "Showing {0}", uri);
272 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
273 System.getProperty("java.vm.name"),
274 System.getProperty("java.vm.vendor"),
275 System.getProperty("java.vm.version"),
277 java.awt.Desktop.getDesktop().browse(uri);
278 LOG.log(Level.INFO, "Desktop.browse successfully finished");
280 } catch (UnsupportedOperationException ex) {
281 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
282 LOG.log(Level.FINE, null, ex);
286 String cmdName = cmd == null ? "xdg-open" : cmd;
288 cmdName, uri.toString()
290 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
291 final Process process = Runtime.getRuntime().exec(cmdArr);
292 return new Object[] { process, null };
296 private static String decodeURL(String s) {
298 int pos = s.indexOf('%');
302 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
303 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
307 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
311 Process process = (Process)brwsr[0];
314 InputStream stdout = process.getInputStream();
315 InputStream stderr = process.getErrorStream();
316 drain("StdOut", stdout);
317 drain("StdErr", stderr);
321 res = process.waitFor();
322 } catch (InterruptedException ex) {
323 throw new IOException(ex);
325 LOG.log(Level.INFO, "Exit code: {0}", res);
327 deleteTree((File)brwsr[1]);
330 private static void drain(String name, InputStream is) throws IOException {
331 int av = is.available();
333 StringBuilder sb = new StringBuilder();
334 sb.append("v== ").append(name).append(" ==v\n");
336 sb.append((char)is.read());
338 sb.append("\n^== ").append(name).append(" ==^");
339 LOG.log(Level.INFO, sb.toString());
343 private void deleteTree(File file) {
347 File[] arr = file.listFiles();
357 public void close() throws IOException {
361 private class Res implements Bck2Brwsr.Resources {
363 public InputStream get(String resource) throws IOException {
364 for (ClassLoader l : loaders) {
366 Enumeration<URL> en = l.getResources(resource);
367 while (en.hasMoreElements()) {
368 u = en.nextElement();
371 return u.openStream();
374 throw new IOException("Can't find " + resource);
378 private static class Page extends HttpHandler {
379 private final String resource;
380 private final String[] args;
381 private final Res res;
383 public Page(Res res, String resource, String... args) {
385 this.resource = resource;
386 this.args = args.length == 0 ? new String[] { "$0" } : args;
390 public void service(Request request, Response response) throws Exception {
393 r = request.getHttpHandlerPath();
394 if (r.startsWith("/")) {
398 String[] replace = {};
399 if (r.endsWith(".html")) {
400 response.setContentType("text/html");
401 LOG.info("Content type text/html");
404 if (r.endsWith(".xhtml")) {
405 response.setContentType("application/xhtml+xml");
406 LOG.info("Content type application/xhtml+xml");
409 OutputStream os = response.getOutputStream();
410 try (InputStream is = res.get(r)) {
411 copyStream(is, os, request.getRequestURL().toString(), replace);
412 } catch (IOException ex) {
413 response.setDetailMessage(ex.getLocalizedMessage());
415 response.setStatus(404);
420 private static class VM extends HttpHandler {
421 private final String bck2brwsr;
423 public VM(Res loader) throws IOException {
424 StringBuilder sb = new StringBuilder();
425 Bck2Brwsr.generate(sb, loader);
427 "function ldCls(res) {\n"
428 + " var request = new XMLHttpRequest();\n"
429 + " request.open('GET', '/classes/' + res, false);\n"
430 + " request.send();\n"
431 + " var arr = eval('(' + request.responseText + ')');\n"
434 + "var vm = new bck2brwsr(ldCls);\n"
436 this.bck2brwsr = sb.toString();
440 public void service(Request request, Response response) throws Exception {
441 response.setCharacterEncoding("UTF-8");
442 response.setContentType("text/javascript");
443 response.getWriter().write(bck2brwsr);
447 private static class Classes extends HttpHandler {
448 private final Res loader;
450 public Classes(Res loader) {
451 this.loader = loader;
455 public void service(Request request, Response response) throws Exception {
456 String res = request.getHttpHandlerPath();
457 if (res.startsWith("/")) {
458 res = res.substring(1);
460 try (InputStream is = loader.get(res)) {
461 response.setContentType("text/javascript");
462 Writer w = response.getWriter();
464 for (int i = 0;; i++) {
478 w.append(Integer.toString(b));
481 } catch (IOException ex) {
483 response.setDetailMessage(ex.getMessage());