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");
194 if (id != null && value != null) {
195 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
196 value = decodeURL(value);
197 cases.get(Integer.parseInt(id)).result(value, null);
205 InvocationContext mi = methods.take();
207 response.getWriter().write("");
210 LOG.log(Level.INFO, "End of data reached. Exiting.");
214 if (!mi.resources.isEmpty()) {
215 prev = new DynamicResourceHandler(mi);
219 final String cn = mi.clazz.getName();
220 final String mn = mi.methodName;
221 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
222 response.getWriter().write("{"
223 + "className: '" + cn + "', "
224 + "methodName: '" + mn + "', "
227 if (mi.html != null) {
228 response.getWriter().write(", html: '");
229 response.getWriter().write(encodeJSON(mi.html));
230 response.getWriter().write("'");
232 response.getWriter().write("}");
237 this.brwsr = launchServerAndBrwsr(server, "/execute");
240 private static String encodeJSON(String in) {
241 StringBuilder sb = new StringBuilder();
242 for (int i = 0; i < in.length(); i++) {
243 char ch = in.charAt(i);
244 if (ch < 32 || ch == '\'' || ch == '"') {
246 String hs = "0000" + Integer.toHexString(ch);
247 hs = hs.substring(hs.length() - 4);
253 return sb.toString();
257 public void shutdown() throws IOException {
260 int prev = methods.size();
262 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
265 } catch (InterruptedException ex) {
266 throw new IOException(ex);
268 if (prev == methods.size()) {
271 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
277 "Timeout, but tests got from {0} to {1}. Trying again.",
278 new Object[]{prev, methods.size()}
281 stopServerAndBrwsr(server, brwsr);
284 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
290 if (ch == '$' && params.length > 0) {
291 int cnt = is.read() - '0';
292 if (cnt == 'U' - '0') {
293 os.write(baseURL.getBytes());
295 if (cnt >= 0 && cnt < params.length) {
296 os.write(params[cnt].getBytes());
304 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
306 NetworkListener listener = server.getListeners().iterator().next();
307 int port = listener.getPort();
309 URI uri = new URI("http://localhost:" + port + page);
310 LOG.log(Level.INFO, "Showing {0}", uri);
313 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
314 System.getProperty("java.vm.name"),
315 System.getProperty("java.vm.vendor"),
316 System.getProperty("java.vm.version"),
318 java.awt.Desktop.getDesktop().browse(uri);
319 LOG.log(Level.INFO, "Desktop.browse successfully finished");
321 } catch (UnsupportedOperationException ex) {
322 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
323 LOG.log(Level.FINE, null, ex);
327 String cmdName = cmd == null ? "xdg-open" : cmd;
329 cmdName, uri.toString()
331 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
332 final Process process = Runtime.getRuntime().exec(cmdArr);
333 return new Object[] { process, null };
337 private static String decodeURL(String s) {
339 int pos = s.indexOf('%');
343 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
344 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
348 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
352 Process process = (Process)brwsr[0];
355 InputStream stdout = process.getInputStream();
356 InputStream stderr = process.getErrorStream();
357 drain("StdOut", stdout);
358 drain("StdErr", stderr);
362 res = process.waitFor();
363 } catch (InterruptedException ex) {
364 throw new IOException(ex);
366 LOG.log(Level.INFO, "Exit code: {0}", res);
368 deleteTree((File)brwsr[1]);
371 private static void drain(String name, InputStream is) throws IOException {
372 int av = is.available();
374 StringBuilder sb = new StringBuilder();
375 sb.append("v== ").append(name).append(" ==v\n");
377 sb.append((char)is.read());
379 sb.append("\n^== ").append(name).append(" ==^");
380 LOG.log(Level.INFO, sb.toString());
384 private void deleteTree(File file) {
388 File[] arr = file.listFiles();
398 public void close() throws IOException {
402 private class Res implements Bck2Brwsr.Resources {
404 public InputStream get(String resource) throws IOException {
405 for (ClassLoader l : loaders) {
407 Enumeration<URL> en = l.getResources(resource);
408 while (en.hasMoreElements()) {
409 u = en.nextElement();
412 return u.openStream();
415 throw new IOException("Can't find " + resource);
419 private static class Page extends HttpHandler {
420 private final String resource;
421 private final String[] args;
422 private final Res res;
424 public Page(Res res, String resource, String... args) {
426 this.resource = resource;
427 this.args = args.length == 0 ? new String[] { "$0" } : args;
431 public void service(Request request, Response response) throws Exception {
434 r = request.getHttpHandlerPath();
435 if (r.startsWith("/")) {
439 String[] replace = {};
440 if (r.endsWith(".html")) {
441 response.setContentType("text/html");
442 LOG.info("Content type text/html");
445 if (r.endsWith(".xhtml")) {
446 response.setContentType("application/xhtml+xml");
447 LOG.info("Content type application/xhtml+xml");
450 OutputStream os = response.getOutputStream();
451 try (InputStream is = res.get(r)) {
452 copyStream(is, os, request.getRequestURL().toString(), replace);
453 } catch (IOException ex) {
454 response.setDetailMessage(ex.getLocalizedMessage());
456 response.setStatus(404);
461 private static class VM extends HttpHandler {
462 private final String bck2brwsr;
464 public VM(Res loader) throws IOException {
465 StringBuilder sb = new StringBuilder();
466 Bck2Brwsr.generate(sb, loader);
468 "function ldCls(res) {\n"
469 + " var request = new XMLHttpRequest();\n"
470 + " request.open('GET', '/classes/' + res, false);\n"
471 + " request.send();\n"
472 + " var arr = eval('(' + request.responseText + ')');\n"
475 + "var vm = new bck2brwsr(ldCls);\n"
477 this.bck2brwsr = sb.toString();
481 public void service(Request request, Response response) throws Exception {
482 response.setCharacterEncoding("UTF-8");
483 response.setContentType("text/javascript");
484 response.getWriter().write(bck2brwsr);
488 private static class Classes extends HttpHandler {
489 private final Res loader;
491 public Classes(Res loader) {
492 this.loader = loader;
496 public void service(Request request, Response response) throws Exception {
497 String res = request.getHttpHandlerPath();
498 if (res.startsWith("/")) {
499 res = res.substring(1);
501 try (InputStream is = loader.get(res)) {
502 response.setContentType("text/javascript");
503 Writer w = response.getWriter();
505 for (int i = 0;; i++) {
519 w.append(Integer.toString(b));
522 } catch (IOException ex) {
524 response.setDetailMessage(ex.getMessage());