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;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InterruptedIOException;
24 import java.io.OutputStream;
25 import java.io.Writer;
27 import java.net.URISyntaxException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Enumeration;
32 import java.util.LinkedHashSet;
33 import java.util.List;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.LinkedBlockingQueue;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import org.apidesign.vm4brwsr.Bck2Brwsr;
42 import org.glassfish.grizzly.PortRange;
43 import org.glassfish.grizzly.http.server.HttpHandler;
44 import org.glassfish.grizzly.http.server.HttpServer;
45 import org.glassfish.grizzly.http.server.NetworkListener;
46 import org.glassfish.grizzly.http.server.Request;
47 import org.glassfish.grizzly.http.server.Response;
48 import org.glassfish.grizzly.http.server.ServerConfiguration;
51 * Lightweight server to launch Bck2Brwsr applications and tests.
52 * Supports execution in native browser as well as Java's internal
55 public class Bck2BrwsrLauncher {
56 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
57 private Set<ClassLoader> loaders = new LinkedHashSet<>();
58 private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
60 private final Res resources = new Res();
61 private Object[] brwsr;
62 private HttpServer server;
63 private CountDownLatch wait;
66 public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
67 loaders.add(clazz.getClassLoader());
68 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
72 } catch (InterruptedException ex) {
73 throw new IOException(ex);
78 public void setTimeout(long ms) {
82 public void addClassLoader(ClassLoader url) {
83 this.loaders.add(url);
86 public static void main( String[] args ) throws Exception {
87 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
88 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
89 l.showURL("org/apidesign/bck2brwsr/launcher/console.xhtml");
93 public void showURL(String startpage) throws URISyntaxException, InterruptedException, IOException {
94 if (!startpage.startsWith("/")) {
95 startpage = "/" + startpage;
97 HttpServer s = initServer();
98 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
99 launchServerAndBrwsr(s, startpage);
102 public void initialize() throws IOException {
105 } catch (InterruptedException ex) {
106 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
109 } catch (Exception ex) {
110 if (ex instanceof IOException) {
111 throw (IOException)ex;
113 if (ex instanceof RuntimeException) {
114 throw (RuntimeException)ex;
116 throw new IOException(ex);
120 private HttpServer initServer() {
121 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
123 final ServerConfiguration conf = s.getServerConfiguration();
124 conf.addHttpHandler(new Page(resources,
125 "org/apidesign/bck2brwsr/launcher/console.xhtml",
126 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
128 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
129 conf.addHttpHandler(new VMInit(), "/vm.js");
130 conf.addHttpHandler(new Classes(resources), "/classes/");
134 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
135 wait = new CountDownLatch(1);
136 server = initServer();
137 ServerConfiguration conf = server.getServerConfiguration();
138 conf.addHttpHandler(new Page(resources,
139 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
141 conf.addHttpHandler(new HttpHandler() {
143 List<MethodInvocation> cases = new ArrayList<>();
145 public void service(Request request, Response response) throws Exception {
146 String id = request.getParameter("request");
147 String value = request.getParameter("result");
149 if (id != null && value != null) {
150 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
151 value = value.replace("%20", " ");
152 cases.get(Integer.parseInt(id)).result(value, null);
155 MethodInvocation mi = methods.take();
157 response.getWriter().write("");
164 final String cn = mi.className;
165 final String mn = mi.methodName;
166 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
167 response.getWriter().write("{"
168 + "className: '" + cn + "', "
169 + "methodName: '" + mn + "', "
176 this.brwsr = launchServerAndBrwsr(server, "/execute");
179 public void shutdown() throws InterruptedException, IOException {
181 int prev = methods.size();
182 if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
185 if (prev == methods.size()) {
188 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
194 "Timeout, but tests got from {0} to {1}. Trying again.",
195 new Object[]{prev, methods.size()}
198 stopServerAndBrwsr(server, brwsr);
201 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
208 int cnt = is.read() - '0';
209 if (cnt == 'U' - '0') {
210 os.write(baseURL.getBytes());
212 if (cnt < params.length) {
213 os.write(params[cnt].getBytes());
221 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
223 NetworkListener listener = server.getListeners().iterator().next();
224 int port = listener.getPort();
226 URI uri = new URI("http://localhost:" + port + page);
227 LOG.log(Level.INFO, "Showing {0}", uri);
229 // Desktop.getDesktop().browse(uri);
231 // } catch (UnsupportedOperationException ex)
233 // File dir = File.createTempFile("chrome", ".dir");
237 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
239 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
240 // final Process process = Runtime.getRuntime().exec(cmd);
241 // return new Object[] { process, dir };
245 "xdg-open", uri.toString()
247 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
248 final Process process = Runtime.getRuntime().exec(cmd);
249 return new Object[] { process, null };
253 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
254 Process process = (Process)brwsr[0];
257 InputStream stdout = process.getInputStream();
258 InputStream stderr = process.getErrorStream();
259 drain("StdOut", stdout);
260 drain("StdErr", stderr);
262 int res = process.waitFor();
263 LOG.log(Level.INFO, "Exit code: {0}", res);
265 deleteTree((File)brwsr[1]);
268 private static void drain(String name, InputStream is) throws IOException {
269 int av = is.available();
271 StringBuilder sb = new StringBuilder();
272 sb.append("v== ").append(name).append(" ==v\n");
274 sb.append((char)is.read());
276 sb.append("\n^== ").append(name).append(" ==^");
277 LOG.log(Level.INFO, sb.toString());
281 private void deleteTree(File file) {
285 File[] arr = file.listFiles();
294 private class Res implements Bck2Brwsr.Resources {
296 public InputStream get(String resource) throws IOException {
297 for (ClassLoader l : loaders) {
299 Enumeration<URL> en = l.getResources(resource);
300 while (en.hasMoreElements()) {
301 u = en.nextElement();
304 return u.openStream();
307 throw new IOException("Can't find " + resource);
311 private static class Page extends HttpHandler {
312 private final String resource;
313 private final String[] args;
314 private final Res res;
316 public Page(Res res, String resource, String... args) {
318 this.resource = resource;
323 public void service(Request request, Response response) throws Exception {
326 r = request.getHttpHandlerPath();
327 if (r.startsWith("/")) {
331 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
332 response.setContentType("text/html");
334 OutputStream os = response.getOutputStream();
335 try (InputStream is = res.get(r)) {
336 copyStream(is, os, request.getRequestURL().toString(), args);
337 } catch (IOException ex) {
338 response.setDetailMessage(ex.getLocalizedMessage());
340 response.setStatus(404);
345 private static class VM extends HttpHandler {
346 private final Res loader;
348 public VM(Res loader) {
349 this.loader = loader;
353 public void service(Request request, Response response) throws Exception {
354 response.setCharacterEncoding("UTF-8");
355 response.setContentType("text/javascript");
356 Bck2Brwsr.generate(response.getWriter(), loader);
359 private static class VMInit extends HttpHandler {
364 public void service(Request request, Response response) throws Exception {
365 response.setCharacterEncoding("UTF-8");
366 response.setContentType("text/javascript");
367 response.getWriter().append(
368 "function ldCls(res) {\n"
369 + " var request = new XMLHttpRequest();\n"
370 + " request.open('GET', '/classes/' + res, false);\n"
371 + " request.send();\n"
372 + " var arr = eval('(' + request.responseText + ')');\n"
375 + "var vm = new bck2brwsr(ldCls);\n");
379 private static class Classes extends HttpHandler {
380 private final Res loader;
382 public Classes(Res loader) {
383 this.loader = loader;
387 public void service(Request request, Response response) throws Exception {
388 String res = request.getHttpHandlerPath();
389 if (res.startsWith("/")) {
390 res = res.substring(1);
392 try (InputStream is = loader.get(res)) {
393 response.setContentType("text/javascript");
394 Writer w = response.getWriter();
396 for (int i = 0;; i++) {
410 w.append(Integer.toString(b));
413 } catch (IOException ex) {
415 response.setDetailMessage(ex.getMessage());