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 MethodInvocation END = new MethodInvocation(null, null);
59 private Set<ClassLoader> loaders = new LinkedHashSet<>();
60 private BlockingQueue<MethodInvocation> 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 public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
74 loaders.add(clazz.getClassLoader());
75 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
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();
98 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
100 launchServerAndBrwsr(s, startpage);
101 } catch (URISyntaxException | InterruptedException ex) {
102 throw new IOException(ex);
107 public void initialize() throws IOException {
110 } catch (InterruptedException ex) {
111 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
114 } catch (Exception ex) {
115 if (ex instanceof IOException) {
116 throw (IOException)ex;
118 if (ex instanceof RuntimeException) {
119 throw (RuntimeException)ex;
121 throw new IOException(ex);
125 private HttpServer initServer() {
126 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
128 final ServerConfiguration conf = s.getServerConfiguration();
129 conf.addHttpHandler(new Page(resources,
130 "org/apidesign/bck2brwsr/launcher/console.xhtml",
131 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
133 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
134 conf.addHttpHandler(new VMInit(), "/vm.js");
135 conf.addHttpHandler(new Classes(resources), "/classes/");
139 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
140 wait = new CountDownLatch(1);
141 server = initServer();
142 ServerConfiguration conf = server.getServerConfiguration();
143 conf.addHttpHandler(new Page(resources,
144 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
146 conf.addHttpHandler(new HttpHandler() {
148 List<MethodInvocation> cases = new ArrayList<>();
150 public void service(Request request, Response response) throws Exception {
151 String id = request.getParameter("request");
152 String value = request.getParameter("result");
154 if (id != null && value != null) {
155 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
156 value = decodeURL(value);
157 cases.get(Integer.parseInt(id)).result(value, null);
160 MethodInvocation mi = methods.take();
162 response.getWriter().write("");
165 LOG.log(Level.INFO, "End of data reached. Exiting.");
170 final String cn = mi.className;
171 final String mn = mi.methodName;
172 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
173 response.getWriter().write("{"
174 + "className: '" + cn + "', "
175 + "methodName: '" + mn + "', "
182 this.brwsr = launchServerAndBrwsr(server, "/execute");
186 public void shutdown() throws IOException {
189 int prev = methods.size();
191 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
194 } catch (InterruptedException ex) {
195 throw new IOException(ex);
197 if (prev == methods.size()) {
200 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
206 "Timeout, but tests got from {0} to {1}. Trying again.",
207 new Object[]{prev, methods.size()}
210 stopServerAndBrwsr(server, brwsr);
213 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
220 int cnt = is.read() - '0';
221 if (cnt == 'U' - '0') {
222 os.write(baseURL.getBytes());
224 if (cnt < params.length) {
225 os.write(params[cnt].getBytes());
233 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
235 NetworkListener listener = server.getListeners().iterator().next();
236 int port = listener.getPort();
238 URI uri = new URI("http://localhost:" + port + page);
239 LOG.log(Level.INFO, "Showing {0}", uri);
242 java.awt.Desktop.getDesktop().browse(uri);
243 LOG.log(Level.INFO, "Desktop.browse successfully finished");
245 } catch (UnsupportedOperationException ex) {
246 LOG.log(Level.INFO, "Desktop.browse not supported", ex);
250 String cmdName = cmd == null ? "xdg-open" : cmd;
252 cmdName, uri.toString()
254 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
255 final Process process = Runtime.getRuntime().exec(cmdArr);
256 return new Object[] { process, null };
260 private static String decodeURL(String s) {
262 int pos = s.indexOf('%');
266 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
267 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
271 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
275 Process process = (Process)brwsr[0];
278 InputStream stdout = process.getInputStream();
279 InputStream stderr = process.getErrorStream();
280 drain("StdOut", stdout);
281 drain("StdErr", stderr);
285 res = process.waitFor();
286 } catch (InterruptedException ex) {
287 throw new IOException(ex);
289 LOG.log(Level.INFO, "Exit code: {0}", res);
291 deleteTree((File)brwsr[1]);
294 private static void drain(String name, InputStream is) throws IOException {
295 int av = is.available();
297 StringBuilder sb = new StringBuilder();
298 sb.append("v== ").append(name).append(" ==v\n");
300 sb.append((char)is.read());
302 sb.append("\n^== ").append(name).append(" ==^");
303 LOG.log(Level.INFO, sb.toString());
307 private void deleteTree(File file) {
311 File[] arr = file.listFiles();
321 public void close() throws IOException {
325 private class Res implements Bck2Brwsr.Resources {
327 public InputStream get(String resource) throws IOException {
328 for (ClassLoader l : loaders) {
330 Enumeration<URL> en = l.getResources(resource);
331 while (en.hasMoreElements()) {
332 u = en.nextElement();
335 return u.openStream();
338 throw new IOException("Can't find " + resource);
342 private static class Page extends HttpHandler {
343 private final String resource;
344 private final String[] args;
345 private final Res res;
347 public Page(Res res, String resource, String... args) {
349 this.resource = resource;
354 public void service(Request request, Response response) throws Exception {
357 r = request.getHttpHandlerPath();
358 if (r.startsWith("/")) {
362 if (r.endsWith(".html")) {
363 response.setContentType("text/html");
364 LOG.info("Content type text/html");
366 if (r.endsWith(".xhtml")) {
367 response.setContentType("application/xhtml+xml");
368 LOG.info("Content type application/xhtml+xml");
370 OutputStream os = response.getOutputStream();
371 try (InputStream is = res.get(r)) {
372 copyStream(is, os, request.getRequestURL().toString(), args);
373 } catch (IOException ex) {
374 response.setDetailMessage(ex.getLocalizedMessage());
376 response.setStatus(404);
381 private static class VM extends HttpHandler {
382 private final Res loader;
384 public VM(Res loader) {
385 this.loader = loader;
389 public void service(Request request, Response response) throws Exception {
390 response.setCharacterEncoding("UTF-8");
391 response.setContentType("text/javascript");
392 Bck2Brwsr.generate(response.getWriter(), loader);
395 private static class VMInit extends HttpHandler {
400 public void service(Request request, Response response) throws Exception {
401 response.setCharacterEncoding("UTF-8");
402 response.setContentType("text/javascript");
403 response.getWriter().append(
404 "function ldCls(res) {\n"
405 + " var request = new XMLHttpRequest();\n"
406 + " request.open('GET', '/classes/' + res, false);\n"
407 + " request.send();\n"
408 + " var arr = eval('(' + request.responseText + ')');\n"
411 + "var vm = new bck2brwsr(ldCls);\n");
415 private static class Classes extends HttpHandler {
416 private final Res loader;
418 public Classes(Res loader) {
419 this.loader = loader;
423 public void service(Request request, Response response) throws Exception {
424 String res = request.getHttpHandlerPath();
425 if (res.startsWith("/")) {
426 res = res.substring(1);
428 try (InputStream is = loader.get(res)) {
429 response.setContentType("text/javascript");
430 Writer w = response.getWriter();
432 for (int i = 0;; i++) {
446 w.append(Integer.toString(b));
449 } catch (IOException ex) {
451 response.setDetailMessage(ex.getMessage());