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 VM(resources), "/bck2brwsr.js");
144 conf.addHttpHandler(new VMInit(), "/vm.js");
145 conf.addHttpHandler(new Classes(resources), "/classes/");
149 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
150 wait = new CountDownLatch(1);
151 server = initServer();
152 ServerConfiguration conf = server.getServerConfiguration();
153 conf.addHttpHandler(new Page(resources,
154 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
156 conf.addHttpHandler(new HttpHandler() {
158 List<MethodInvocation> cases = new ArrayList<>();
160 public void service(Request request, Response response) throws Exception {
161 String id = request.getParameter("request");
162 String value = request.getParameter("result");
164 if (id != null && value != null) {
165 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
166 value = decodeURL(value);
167 cases.get(Integer.parseInt(id)).result(value, null);
170 MethodInvocation mi = methods.take();
172 response.getWriter().write("");
175 LOG.log(Level.INFO, "End of data reached. Exiting.");
180 final String cn = mi.className;
181 final String mn = mi.methodName;
182 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
183 response.getWriter().write("{"
184 + "className: '" + cn + "', "
185 + "methodName: '" + mn + "', "
192 this.brwsr = launchServerAndBrwsr(server, "/execute");
196 public void shutdown() throws IOException {
199 int prev = methods.size();
201 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
204 } catch (InterruptedException ex) {
205 throw new IOException(ex);
207 if (prev == methods.size()) {
210 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
216 "Timeout, but tests got from {0} to {1}. Trying again.",
217 new Object[]{prev, methods.size()}
220 stopServerAndBrwsr(server, brwsr);
223 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
230 int cnt = is.read() - '0';
231 if (cnt == 'U' - '0') {
232 os.write(baseURL.getBytes());
234 if (cnt < params.length) {
235 os.write(params[cnt].getBytes());
243 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
245 NetworkListener listener = server.getListeners().iterator().next();
246 int port = listener.getPort();
248 URI uri = new URI("http://localhost:" + port + page);
249 LOG.log(Level.INFO, "Showing {0}", uri);
252 java.awt.Desktop.getDesktop().browse(uri);
253 LOG.log(Level.INFO, "Desktop.browse successfully finished");
255 } catch (UnsupportedOperationException ex) {
256 LOG.log(Level.INFO, "Desktop.browse not supported", ex);
260 String cmdName = cmd == null ? "xdg-open" : cmd;
262 cmdName, uri.toString()
264 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
265 final Process process = Runtime.getRuntime().exec(cmdArr);
266 return new Object[] { process, null };
270 private static String decodeURL(String s) {
272 int pos = s.indexOf('%');
276 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
277 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
281 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
285 Process process = (Process)brwsr[0];
288 InputStream stdout = process.getInputStream();
289 InputStream stderr = process.getErrorStream();
290 drain("StdOut", stdout);
291 drain("StdErr", stderr);
295 res = process.waitFor();
296 } catch (InterruptedException ex) {
297 throw new IOException(ex);
299 LOG.log(Level.INFO, "Exit code: {0}", res);
301 deleteTree((File)brwsr[1]);
304 private static void drain(String name, InputStream is) throws IOException {
305 int av = is.available();
307 StringBuilder sb = new StringBuilder();
308 sb.append("v== ").append(name).append(" ==v\n");
310 sb.append((char)is.read());
312 sb.append("\n^== ").append(name).append(" ==^");
313 LOG.log(Level.INFO, sb.toString());
317 private void deleteTree(File file) {
321 File[] arr = file.listFiles();
331 public void close() throws IOException {
335 private class Res implements Bck2Brwsr.Resources {
337 public InputStream get(String resource) throws IOException {
338 for (ClassLoader l : loaders) {
340 Enumeration<URL> en = l.getResources(resource);
341 while (en.hasMoreElements()) {
342 u = en.nextElement();
345 return u.openStream();
348 throw new IOException("Can't find " + resource);
352 private static class Page extends HttpHandler {
353 private final String resource;
354 private final String[] args;
355 private final Res res;
357 public Page(Res res, String resource, String... args) {
359 this.resource = resource;
364 public void service(Request request, Response response) throws Exception {
367 r = request.getHttpHandlerPath();
368 if (r.startsWith("/")) {
372 if (r.endsWith(".html")) {
373 response.setContentType("text/html");
374 LOG.info("Content type text/html");
376 if (r.endsWith(".xhtml")) {
377 response.setContentType("application/xhtml+xml");
378 LOG.info("Content type application/xhtml+xml");
380 OutputStream os = response.getOutputStream();
381 try (InputStream is = res.get(r)) {
382 copyStream(is, os, request.getRequestURL().toString(), args);
383 } catch (IOException ex) {
384 response.setDetailMessage(ex.getLocalizedMessage());
386 response.setStatus(404);
391 private static class VM extends HttpHandler {
392 private final Res loader;
394 public VM(Res loader) {
395 this.loader = loader;
399 public void service(Request request, Response response) throws Exception {
400 response.setCharacterEncoding("UTF-8");
401 response.setContentType("text/javascript");
402 Bck2Brwsr.generate(response.getWriter(), loader);
405 private static class VMInit extends HttpHandler {
410 public void service(Request request, Response response) throws Exception {
411 response.setCharacterEncoding("UTF-8");
412 response.setContentType("text/javascript");
413 response.getWriter().append(
414 "function ldCls(res) {\n"
415 + " var request = new XMLHttpRequest();\n"
416 + " request.open('GET', '/classes/' + res, false);\n"
417 + " request.send();\n"
418 + " var arr = eval('(' + request.responseText + ')');\n"
421 + "var vm = new bck2brwsr(ldCls);\n");
425 private static class Classes extends HttpHandler {
426 private final Res loader;
428 public Classes(Res loader) {
429 this.loader = loader;
433 public void service(Request request, Response response) throws Exception {
434 String res = request.getHttpHandlerPath();
435 if (res.startsWith("/")) {
436 res = res.substring(1);
438 try (InputStream is = loader.get(res)) {
439 response.setContentType("text/javascript");
440 Writer w = response.getWriter();
442 for (int i = 0;; i++) {
456 w.append(Integer.toString(b));
459 } catch (IOException ex) {
461 response.setDetailMessage(ex.getMessage());