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.CountDownLatch;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39 import org.apidesign.vm4brwsr.Bck2Brwsr;
40 import org.glassfish.grizzly.PortRange;
41 import org.glassfish.grizzly.http.server.HttpHandler;
42 import org.glassfish.grizzly.http.server.HttpServer;
43 import org.glassfish.grizzly.http.server.NetworkListener;
44 import org.glassfish.grizzly.http.server.Request;
45 import org.glassfish.grizzly.http.server.Response;
46 import org.glassfish.grizzly.http.server.ServerConfiguration;
49 * Lightweight server to launch Bck2Brwsr applications and tests.
50 * Supports execution in native browser as well as Java's internal
53 public class Bck2BrwsrLauncher {
54 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
55 private Set<ClassLoader> loaders = new LinkedHashSet<>();
56 private List<MethodInvocation> methods = new ArrayList<>();
58 private String showURL;
59 private final Res resources = new Res();
62 public MethodInvocation addMethod(Class<?> clazz, String method) {
63 loaders.add(clazz.getClassLoader());
64 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
69 public void setTimeout(long ms) {
73 public void setStartPage(String startpage) {
74 if (!startpage.startsWith("/")) {
75 startpage = "/" + startpage;
77 this.showURL = startpage;
80 public void addClassLoader(ClassLoader url) {
81 this.loaders.add(url);
84 public static void main( String[] args ) throws Exception {
85 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
86 l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
87 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
93 public void execute() throws IOException {
95 if (showURL != null) {
96 HttpServer server = initServer();
97 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
98 launchServerAndBrwsr(server, showURL);
102 } catch (InterruptedException ex) {
103 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
106 } catch (Exception ex) {
107 if (ex instanceof IOException) {
108 throw (IOException)ex;
110 if (ex instanceof RuntimeException) {
111 throw (RuntimeException)ex;
113 throw new IOException(ex);
117 private HttpServer initServer() {
118 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
120 final ServerConfiguration conf = server.getServerConfiguration();
121 conf.addHttpHandler(new Page(resources,
122 "org/apidesign/bck2brwsr/launcher/console.xhtml",
123 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
125 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
126 conf.addHttpHandler(new VMInit(), "/vm.js");
127 conf.addHttpHandler(new Classes(resources), "/classes/");
131 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
132 final CountDownLatch wait = new CountDownLatch(1);
133 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
135 HttpServer server = initServer();
136 ServerConfiguration conf = server.getServerConfiguration();
137 conf.addHttpHandler(new Page(resources,
138 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
140 final int[] currentTest = { -1 };
141 conf.addHttpHandler(new HttpHandler() {
144 public void service(Request request, Response response) throws Exception {
145 String id = request.getParameter("request");
146 String value = request.getParameter("result");
148 if (id != null && value != null) {
149 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
150 value = value.replace("%20", " ");
151 cases[Integer.parseInt(id)].result = value;
153 currentTest[0] = cnt;
155 if (cnt >= cases.length) {
156 response.getWriter().write("");
162 final String cn = cases[cnt].className;
163 final String mn = cases[cnt].methodName;
164 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
165 response.getWriter().write("{"
166 + "className: '" + cn + "', "
167 + "methodName: '" + mn + "', "
174 Object[] brwsr = launchServerAndBrwsr(server, "/execute");
177 int prev = currentTest[0];
178 if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
181 if (prev == currentTest[0]) {
184 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
190 "Timeout, but tests got from {0} to {1}. Trying again.",
191 new Object[]{prev, currentTest[0]}
194 stopServerAndBrwsr(server, brwsr);
197 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
204 int cnt = is.read() - '0';
205 if (cnt == 'U' - '0') {
206 os.write(baseURL.getBytes());
208 if (cnt < params.length) {
209 os.write(params[cnt].getBytes());
217 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
219 NetworkListener listener = server.getListeners().iterator().next();
220 int port = listener.getPort();
222 URI uri = new URI("http://localhost:" + port + page);
223 LOG.log(Level.INFO, "Showing {0}", uri);
225 // Desktop.getDesktop().browse(uri);
227 // } catch (UnsupportedOperationException ex)
229 // File dir = File.createTempFile("chrome", ".dir");
233 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
235 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
236 // final Process process = Runtime.getRuntime().exec(cmd);
237 // return new Object[] { process, dir };
241 "xdg-open", uri.toString()
243 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
244 final Process process = Runtime.getRuntime().exec(cmd);
245 return new Object[] { process, null };
249 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
250 Process process = (Process)brwsr[0];
253 InputStream stdout = process.getInputStream();
254 InputStream stderr = process.getErrorStream();
255 drain("StdOut", stdout);
256 drain("StdErr", stderr);
258 int res = process.waitFor();
259 LOG.log(Level.INFO, "Exit code: {0}", res);
261 deleteTree((File)brwsr[1]);
264 private static void drain(String name, InputStream is) throws IOException {
265 int av = is.available();
267 StringBuilder sb = new StringBuilder();
268 sb.append("v== ").append(name).append(" ==v\n");
270 sb.append((char)is.read());
272 sb.append("\n^== ").append(name).append(" ==^");
273 LOG.log(Level.INFO, sb.toString());
277 private void deleteTree(File file) {
281 File[] arr = file.listFiles();
290 private class Res implements Bck2Brwsr.Resources {
292 public InputStream get(String resource) throws IOException {
293 for (ClassLoader l : loaders) {
295 Enumeration<URL> en = l.getResources(resource);
296 while (en.hasMoreElements()) {
297 u = en.nextElement();
300 return u.openStream();
303 throw new IOException("Can't find " + resource);
307 private static class Page extends HttpHandler {
308 private final String resource;
309 private final String[] args;
310 private final Res res;
312 public Page(Res res, String resource, String... args) {
314 this.resource = resource;
319 public void service(Request request, Response response) throws Exception {
322 r = request.getHttpHandlerPath();
323 if (r.startsWith("/")) {
327 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
328 response.setContentType("text/html");
330 OutputStream os = response.getOutputStream();
331 try (InputStream is = res.get(r)) {
332 copyStream(is, os, request.getRequestURL().toString(), args);
333 } catch (IOException ex) {
334 response.setDetailMessage(ex.getLocalizedMessage());
336 response.setStatus(404);
341 private static class VM extends HttpHandler {
342 private final Res loader;
344 public VM(Res loader) {
345 this.loader = loader;
349 public void service(Request request, Response response) throws Exception {
350 response.setCharacterEncoding("UTF-8");
351 response.setContentType("text/javascript");
352 Bck2Brwsr.generate(response.getWriter(), loader);
355 private static class VMInit extends HttpHandler {
360 public void service(Request request, Response response) throws Exception {
361 response.setCharacterEncoding("UTF-8");
362 response.setContentType("text/javascript");
363 response.getWriter().append(
364 "function ldCls(res) {\n"
365 + " var request = new XMLHttpRequest();\n"
366 + " request.open('GET', '/classes/' + res, false);\n"
367 + " request.send();\n"
368 + " var arr = eval('(' + request.responseText + ')');\n"
371 + "var vm = new bck2brwsr(ldCls);\n");
375 private static class Classes extends HttpHandler {
376 private final Res loader;
378 public Classes(Res loader) {
379 this.loader = loader;
383 public void service(Request request, Response response) throws Exception {
384 String res = request.getHttpHandlerPath();
385 if (res.startsWith("/")) {
386 res = res.substring(1);
388 try (InputStream is = loader.get(res)) {
389 response.setContentType("text/javascript");
390 Writer w = response.getWriter();
392 for (int i = 0;; i++) {
406 w.append(Integer.toString(b));
409 } catch (IOException ex) {
411 response.setDetailMessage(ex.getMessage());