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.dew.Dew;
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 MethodInvocation END = new MethodInvocation(null, null);
60 private Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private BlockingQueue<MethodInvocation> 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 public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
75 loaders.add(clazz.getClassLoader());
76 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
80 } catch (InterruptedException ex) {
81 throw new IOException(ex);
86 public void setTimeout(long ms) {
90 public void addClassLoader(ClassLoader url) {
91 this.loaders.add(url);
94 public void showURL(String startpage) throws IOException {
95 if (!startpage.startsWith("/")) {
96 startpage = "/" + startpage;
98 HttpServer s = initServer();
99 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
101 launchServerAndBrwsr(s, startpage);
102 } catch (URISyntaxException | InterruptedException ex) {
103 throw new IOException(ex);
107 public static void main(String... args) throws Exception {
108 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher(null);
109 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
110 HttpServer s = l.initServer();
111 s.getServerConfiguration().addHttpHandler(new Dew(), "/dew/");
112 l.launchServerAndBrwsr(s, "/dew/");
117 public void initialize() throws IOException {
120 } catch (InterruptedException ex) {
121 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
124 } catch (Exception ex) {
125 if (ex instanceof IOException) {
126 throw (IOException)ex;
128 if (ex instanceof RuntimeException) {
129 throw (RuntimeException)ex;
131 throw new IOException(ex);
135 private HttpServer initServer() {
136 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
138 final ServerConfiguration conf = s.getServerConfiguration();
139 conf.addHttpHandler(new Page(resources,
140 "org/apidesign/bck2brwsr/launcher/console.xhtml",
141 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
143 conf.addHttpHandler(new Dew(), "/dew/");
144 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
145 conf.addHttpHandler(new VMInit(), "/vm.js");
146 conf.addHttpHandler(new Classes(resources), "/classes/");
150 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
151 wait = new CountDownLatch(1);
152 server = initServer();
153 ServerConfiguration conf = server.getServerConfiguration();
154 conf.addHttpHandler(new Page(resources,
155 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
157 conf.addHttpHandler(new HttpHandler() {
159 List<MethodInvocation> cases = new ArrayList<>();
161 public void service(Request request, Response response) throws Exception {
162 String id = request.getParameter("request");
163 String value = request.getParameter("result");
165 if (id != null && value != null) {
166 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
167 value = decodeURL(value);
168 cases.get(Integer.parseInt(id)).result(value, null);
171 MethodInvocation mi = methods.take();
173 response.getWriter().write("");
176 LOG.log(Level.INFO, "End of data reached. Exiting.");
181 final String cn = mi.className;
182 final String mn = mi.methodName;
183 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
184 response.getWriter().write("{"
185 + "className: '" + cn + "', "
186 + "methodName: '" + mn + "', "
193 this.brwsr = launchServerAndBrwsr(server, "/execute");
197 public void shutdown() throws IOException {
200 int prev = methods.size();
202 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
205 } catch (InterruptedException ex) {
206 throw new IOException(ex);
208 if (prev == methods.size()) {
211 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
217 "Timeout, but tests got from {0} to {1}. Trying again.",
218 new Object[]{prev, methods.size()}
221 stopServerAndBrwsr(server, brwsr);
224 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
231 int cnt = is.read() - '0';
232 if (cnt == 'U' - '0') {
233 os.write(baseURL.getBytes());
235 if (cnt < params.length) {
236 os.write(params[cnt].getBytes());
244 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
246 NetworkListener listener = server.getListeners().iterator().next();
247 int port = listener.getPort();
249 URI uri = new URI("http://localhost:" + port + page);
250 LOG.log(Level.INFO, "Showing {0}", uri);
252 // Desktop.getDesktop().browse(uri);
254 // } catch (UnsupportedOperationException ex)
256 // File dir = File.createTempFile("chrome", ".dir");
260 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
262 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
263 // final Process process = Runtime.getRuntime().exec(cmd);
264 // return new Object[] { process, dir };
267 String cmdName = cmd == null ? "xdg-open" : cmd;
269 cmdName, uri.toString()
271 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
272 final Process process = Runtime.getRuntime().exec(cmdArr);
273 return new Object[] { process, null };
277 private static String decodeURL(String s) {
279 int pos = s.indexOf('%');
283 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
284 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
288 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
292 Process process = (Process)brwsr[0];
295 InputStream stdout = process.getInputStream();
296 InputStream stderr = process.getErrorStream();
297 drain("StdOut", stdout);
298 drain("StdErr", stderr);
302 res = process.waitFor();
303 } catch (InterruptedException ex) {
304 throw new IOException(ex);
306 LOG.log(Level.INFO, "Exit code: {0}", res);
308 deleteTree((File)brwsr[1]);
311 private static void drain(String name, InputStream is) throws IOException {
312 int av = is.available();
314 StringBuilder sb = new StringBuilder();
315 sb.append("v== ").append(name).append(" ==v\n");
317 sb.append((char)is.read());
319 sb.append("\n^== ").append(name).append(" ==^");
320 LOG.log(Level.INFO, sb.toString());
324 private void deleteTree(File file) {
328 File[] arr = file.listFiles();
338 public void close() throws IOException {
342 private class Res implements Bck2Brwsr.Resources {
344 public InputStream get(String resource) throws IOException {
345 for (ClassLoader l : loaders) {
347 Enumeration<URL> en = l.getResources(resource);
348 while (en.hasMoreElements()) {
349 u = en.nextElement();
352 return u.openStream();
355 throw new IOException("Can't find " + resource);
359 private static class Page extends HttpHandler {
360 private final String resource;
361 private final String[] args;
362 private final Res res;
364 public Page(Res res, String resource, String... args) {
366 this.resource = resource;
371 public void service(Request request, Response response) throws Exception {
374 r = request.getHttpHandlerPath();
375 if (r.startsWith("/")) {
379 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
380 response.setContentType("text/html");
382 OutputStream os = response.getOutputStream();
383 try (InputStream is = res.get(r)) {
384 copyStream(is, os, request.getRequestURL().toString(), args);
385 } catch (IOException ex) {
386 response.setDetailMessage(ex.getLocalizedMessage());
388 response.setStatus(404);
393 private static class VM extends HttpHandler {
394 private final Res loader;
396 public VM(Res loader) {
397 this.loader = loader;
401 public void service(Request request, Response response) throws Exception {
402 response.setCharacterEncoding("UTF-8");
403 response.setContentType("text/javascript");
404 Bck2Brwsr.generate(response.getWriter(), loader);
407 private static class VMInit extends HttpHandler {
412 public void service(Request request, Response response) throws Exception {
413 response.setCharacterEncoding("UTF-8");
414 response.setContentType("text/javascript");
415 response.getWriter().append(
416 "function ldCls(res) {\n"
417 + " var request = new XMLHttpRequest();\n"
418 + " request.open('GET', '/classes/' + res, false);\n"
419 + " request.send();\n"
420 + " var arr = eval('(' + request.responseText + ')');\n"
423 + "var vm = new bck2brwsr(ldCls);\n");
427 private static class Classes extends HttpHandler {
428 private final Res loader;
430 public Classes(Res loader) {
431 this.loader = loader;
435 public void service(Request request, Response response) throws Exception {
436 String res = request.getHttpHandlerPath();
437 if (res.startsWith("/")) {
438 res = res.substring(1);
440 try (InputStream is = loader.get(res)) {
441 response.setContentType("text/javascript");
442 Writer w = response.getWriter();
444 for (int i = 0;; i++) {
458 w.append(Integer.toString(b));
461 } catch (IOException ex) {
463 response.setDetailMessage(ex.getMessage());