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 final ServerConfiguration conf = server.getServerConfiguration();
152 class DynamicResourceHandler extends HttpHandler {
153 private final InvocationContext ic;
154 public DynamicResourceHandler(InvocationContext ic) {
155 if (ic == null || ic.httpPath == null) {
156 throw new NullPointerException();
159 conf.addHttpHandler(this, ic.httpPath);
162 public void close() {
163 conf.removeHttpHandler(this);
167 public void service(Request request, Response response) throws Exception {
168 if (ic.httpPath.equals(request.getRequestURI())) {
169 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
170 response.setContentType(ic.httpType);
171 copyStream(ic.httpContent, response.getOutputStream(), null);
176 conf.addHttpHandler(new Page(resources,
177 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
180 conf.addHttpHandler(new HttpHandler() {
182 List<InvocationContext> cases = new ArrayList<>();
183 DynamicResourceHandler prev;
185 public void service(Request request, Response response) throws Exception {
186 String id = request.getParameter("request");
187 String value = request.getParameter("result");
189 if (id != null && value != null) {
190 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
191 value = decodeURL(value);
192 cases.get(Integer.parseInt(id)).result(value, null);
200 InvocationContext mi = methods.take();
202 response.getWriter().write("");
205 LOG.log(Level.INFO, "End of data reached. Exiting.");
209 if (mi.httpPath != null) {
210 prev = new DynamicResourceHandler(mi);
214 final String cn = mi.clazz.getName();
215 final String mn = mi.methodName;
216 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
217 response.getWriter().write("{"
218 + "className: '" + cn + "', "
219 + "methodName: '" + mn + "', "
222 if (mi.html != null) {
223 response.getWriter().write(", html: '");
224 response.getWriter().write(encodeJSON(mi.html));
225 response.getWriter().write("'");
227 response.getWriter().write("}");
232 this.brwsr = launchServerAndBrwsr(server, "/execute");
235 private static String encodeJSON(String in) {
236 StringBuilder sb = new StringBuilder();
237 for (int i = 0; i < in.length(); i++) {
238 char ch = in.charAt(i);
239 if (ch < 32 || ch == '\'' || ch == '"') {
241 String hs = "0000" + Integer.toHexString(ch);
242 hs = hs.substring(hs.length() - 4);
248 return sb.toString();
252 public void shutdown() throws IOException {
255 int prev = methods.size();
257 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
260 } catch (InterruptedException ex) {
261 throw new IOException(ex);
263 if (prev == methods.size()) {
266 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
272 "Timeout, but tests got from {0} to {1}. Trying again.",
273 new Object[]{prev, methods.size()}
276 stopServerAndBrwsr(server, brwsr);
279 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
285 if (ch == '$' && params.length > 0) {
286 int cnt = is.read() - '0';
287 if (cnt == 'U' - '0') {
288 os.write(baseURL.getBytes("UTF-8"));
290 if (cnt >= 0 && cnt < params.length) {
291 os.write(params[cnt].getBytes("UTF-8"));
299 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
301 NetworkListener listener = server.getListeners().iterator().next();
302 int port = listener.getPort();
304 URI uri = new URI("http://localhost:" + port + page);
305 LOG.log(Level.INFO, "Showing {0}", uri);
308 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
309 System.getProperty("java.vm.name"),
310 System.getProperty("java.vm.vendor"),
311 System.getProperty("java.vm.version"),
313 java.awt.Desktop.getDesktop().browse(uri);
314 LOG.log(Level.INFO, "Desktop.browse successfully finished");
316 } catch (UnsupportedOperationException ex) {
317 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
318 LOG.log(Level.FINE, null, ex);
322 String cmdName = cmd == null ? "xdg-open" : cmd;
324 cmdName, uri.toString()
326 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
327 final Process process = Runtime.getRuntime().exec(cmdArr);
328 return new Object[] { process, null };
332 private static String decodeURL(String s) {
334 int pos = s.indexOf('%');
338 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
339 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
343 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
347 Process process = (Process)brwsr[0];
350 InputStream stdout = process.getInputStream();
351 InputStream stderr = process.getErrorStream();
352 drain("StdOut", stdout);
353 drain("StdErr", stderr);
357 res = process.waitFor();
358 } catch (InterruptedException ex) {
359 throw new IOException(ex);
361 LOG.log(Level.INFO, "Exit code: {0}", res);
363 deleteTree((File)brwsr[1]);
366 private static void drain(String name, InputStream is) throws IOException {
367 int av = is.available();
369 StringBuilder sb = new StringBuilder();
370 sb.append("v== ").append(name).append(" ==v\n");
372 sb.append((char)is.read());
374 sb.append("\n^== ").append(name).append(" ==^");
375 LOG.log(Level.INFO, sb.toString());
379 private void deleteTree(File file) {
383 File[] arr = file.listFiles();
393 public void close() throws IOException {
397 private class Res implements Bck2Brwsr.Resources {
399 public InputStream get(String resource) throws IOException {
400 for (ClassLoader l : loaders) {
402 Enumeration<URL> en = l.getResources(resource);
403 while (en.hasMoreElements()) {
404 u = en.nextElement();
407 return u.openStream();
410 throw new IOException("Can't find " + resource);
414 private static class Page extends HttpHandler {
415 private final String resource;
416 private final String[] args;
417 private final Res res;
419 public Page(Res res, String resource, String... args) {
421 this.resource = resource;
422 this.args = args.length == 0 ? new String[] { "$0" } : args;
426 public void service(Request request, Response response) throws Exception {
429 r = request.getHttpHandlerPath();
430 if (r.startsWith("/")) {
434 String[] replace = {};
435 if (r.endsWith(".html")) {
436 response.setContentType("text/html");
437 LOG.info("Content type text/html");
440 if (r.endsWith(".xhtml")) {
441 response.setContentType("application/xhtml+xml");
442 LOG.info("Content type application/xhtml+xml");
445 OutputStream os = response.getOutputStream();
446 try (InputStream is = res.get(r)) {
447 copyStream(is, os, request.getRequestURL().toString(), replace);
448 } catch (IOException ex) {
449 response.setDetailMessage(ex.getLocalizedMessage());
451 response.setStatus(404);
456 private static class VM extends HttpHandler {
457 private final String bck2brwsr;
459 public VM(Res loader) throws IOException {
460 StringBuilder sb = new StringBuilder();
461 Bck2Brwsr.generate(sb, loader);
463 "function ldCls(res) {\n"
464 + " var request = new XMLHttpRequest();\n"
465 + " request.open('GET', '/classes/' + res, false);\n"
466 + " request.send();\n"
467 + " var arr = eval('(' + request.responseText + ')');\n"
470 + "var vm = new bck2brwsr(ldCls);\n"
472 this.bck2brwsr = sb.toString();
476 public void service(Request request, Response response) throws Exception {
477 response.setCharacterEncoding("UTF-8");
478 response.setContentType("text/javascript");
479 response.getWriter().write(bck2brwsr);
483 private static class Classes extends HttpHandler {
484 private final Res loader;
486 public Classes(Res loader) {
487 this.loader = loader;
491 public void service(Request request, Response response) throws Exception {
492 String res = request.getHttpHandlerPath();
493 if (res.startsWith("/")) {
494 res = res.substring(1);
496 try (InputStream is = loader.get(res)) {
497 response.setContentType("text/javascript");
498 Writer w = response.getWriter();
500 for (int i = 0;; i++) {
514 w.append(Integer.toString(b));
517 } catch (IOException ex) {
519 response.setDetailMessage(ex.getMessage());