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.awt.Desktop;
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 javax.script.Invocable;
40 import javax.script.ScriptEngine;
41 import javax.script.ScriptEngineManager;
42 import javax.script.ScriptException;
43 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
44 import org.apidesign.vm4brwsr.Bck2Brwsr;
45 import org.glassfish.grizzly.PortRange;
46 import org.glassfish.grizzly.http.server.HttpHandler;
47 import org.glassfish.grizzly.http.server.HttpServer;
48 import org.glassfish.grizzly.http.server.NetworkListener;
49 import org.glassfish.grizzly.http.server.Request;
50 import org.glassfish.grizzly.http.server.Response;
51 import org.glassfish.grizzly.http.server.ServerConfiguration;
54 * Lightweight server to launch Bck2Brwsr applications and tests.
55 * Supports execution in native browser as well as Java's internal
58 public class Bck2BrwsrLauncher {
59 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
60 private Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private List<MethodInvocation> methods = new ArrayList<>();
64 private String showURL;
65 private final Res resources = new Res();
68 public MethodInvocation addMethod(Class<?> clazz, String method) {
69 loaders.add(clazz.getClassLoader());
70 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
75 public void setTimeout(long ms) {
79 public void setScriptEngineName(String sen) {
83 public void setStartPage(String startpage) {
84 if (!startpage.startsWith("/")) {
85 startpage = "/" + startpage;
87 this.showURL = startpage;
90 public void addClassLoader(ClassLoader url) {
91 this.loaders.add(url);
94 public static void main( String[] args ) throws Exception {
95 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
96 l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
97 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
103 public void execute() throws IOException {
107 } else if (showURL != null) {
108 HttpServer server = initServer();
109 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
110 launchServerAndBrwsr(server, showURL);
114 } catch (InterruptedException ex) {
115 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
118 } catch (Exception ex) {
119 if (ex instanceof IOException) {
120 throw (IOException)ex;
122 if (ex instanceof RuntimeException) {
123 throw (RuntimeException)ex;
125 throw new IOException(ex);
129 private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
130 StringBuilder sb = new StringBuilder();
131 Bck2Brwsr.generate(sb, new Res());
133 ScriptEngineManager sem = new ScriptEngineManager();
134 ScriptEngine mach = sem.getEngineByExtension(sen);
137 "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
138 + "\nfunction initVM() { return vm; };"
141 Object res = mach.eval(sb.toString());
142 if (!(mach instanceof Invocable)) {
143 throw new IOException("It is invocable object: " + res);
145 Invocable code = (Invocable) mach;
147 Object vm = code.invokeFunction("initVM");
148 Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
150 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
151 for (MethodInvocation mi : cases) {
152 mi.result = code.invokeMethod(console,
153 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
154 mi.className, mi.methodName
159 private HttpServer initServer() {
160 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
162 final ServerConfiguration conf = server.getServerConfiguration();
163 conf.addHttpHandler(new Page(resources,
164 "org/apidesign/bck2brwsr/launcher/console.xhtml",
165 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
167 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
168 conf.addHttpHandler(new VMInit(), "/vm.js");
169 conf.addHttpHandler(new Classes(resources), "/classes/");
173 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
174 final CountDownLatch wait = new CountDownLatch(1);
175 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
177 HttpServer server = initServer();
178 ServerConfiguration conf = server.getServerConfiguration();
179 conf.addHttpHandler(new Page(resources,
180 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
182 final int[] currentTest = { -1 };
183 conf.addHttpHandler(new HttpHandler() {
186 public void service(Request request, Response response) throws Exception {
187 String id = request.getParameter("request");
188 String value = request.getParameter("result");
190 if (id != null && value != null) {
191 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
192 value = value.replace("%20", " ");
193 cases[Integer.parseInt(id)].result = value;
195 currentTest[0] = cnt;
197 if (cnt >= cases.length) {
198 response.getWriter().write("");
204 final String cn = cases[cnt].className;
205 final String mn = cases[cnt].methodName;
206 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
207 response.getWriter().write("{"
208 + "className: '" + cn + "', "
209 + "methodName: '" + mn + "', "
216 launchServerAndBrwsr(server, "/execute");
219 int prev = currentTest[0];
220 if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
223 if (prev == currentTest[0]) {
226 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
232 "Timeout, but tests got from {0} to {1}. Trying again.",
233 new Object[]{prev, currentTest[0]}
239 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
246 int cnt = is.read() - '0';
247 if (cnt == 'U' - '0') {
248 os.write(baseURL.getBytes());
250 if (cnt < params.length) {
251 os.write(params[cnt].getBytes());
259 private void launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
261 NetworkListener listener = server.getListeners().iterator().next();
262 int port = listener.getPort();
264 URI uri = new URI("http://localhost:" + port + page);
265 LOG.log(Level.INFO, "Showing {0}", uri);
267 Desktop.getDesktop().browse(uri);
268 } catch (UnsupportedOperationException ex) {
270 "xdg-open", uri.toString()
272 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
273 final Process process = Runtime.getRuntime().exec(cmd);
274 InputStream stdout = process.getInputStream();
275 InputStream stderr = process.getErrorStream();
276 int res = process.waitFor();
277 LOG.log(Level.INFO, "Exit code: {0}", res);
278 drain("StdOut", stdout);
279 drain("StdErr", stderr);
283 private static void drain(String name, InputStream is) throws IOException {
284 int av = is.available();
286 StringBuilder sb = new StringBuilder();
287 sb.append("v== ").append(name).append(" ==v\n");
289 sb.append((char)is.read());
291 sb.append("\n^== ").append(name).append(" ==^");
292 LOG.log(Level.INFO, sb.toString());
296 private class Res implements Bck2Brwsr.Resources {
298 public InputStream get(String resource) throws IOException {
299 for (ClassLoader l : loaders) {
301 Enumeration<URL> en = l.getResources(resource);
302 while (en.hasMoreElements()) {
303 u = en.nextElement();
306 return u.openStream();
309 throw new IOException("Can't find " + resource);
313 private static class Page extends HttpHandler {
314 private final String resource;
315 private final String[] args;
316 private final Res res;
318 public Page(Res res, String resource, String... args) {
320 this.resource = resource;
325 public void service(Request request, Response response) throws Exception {
328 r = request.getHttpHandlerPath();
329 if (r.startsWith("/")) {
333 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
334 response.setContentType("text/html");
336 OutputStream os = response.getOutputStream();
337 try (InputStream is = res.get(r)) {
338 copyStream(is, os, request.getRequestURL().toString(), args);
339 } catch (IOException ex) {
340 response.setDetailMessage(ex.getLocalizedMessage());
342 response.setStatus(404);
347 private static class VM extends HttpHandler {
348 private final Res loader;
350 public VM(Res loader) {
351 this.loader = loader;
355 public void service(Request request, Response response) throws Exception {
356 response.setCharacterEncoding("UTF-8");
357 response.setContentType("text/javascript");
358 Bck2Brwsr.generate(response.getWriter(), loader);
361 private static class VMInit extends HttpHandler {
366 public void service(Request request, Response response) throws Exception {
367 response.setCharacterEncoding("UTF-8");
368 response.setContentType("text/javascript");
369 response.getWriter().append(
370 "function ldCls(res) {\n"
371 + " var request = new XMLHttpRequest();\n"
372 + " request.open('GET', '/classes/' + res, false);\n"
373 + " request.send();\n"
374 + " var arr = eval('(' + request.responseText + ')');\n"
377 + "var vm = new bck2brwsr(ldCls);\n");
381 private static class Classes extends HttpHandler {
382 private final Res loader;
384 public Classes(Res loader) {
385 this.loader = loader;
389 public void service(Request request, Response response) throws Exception {
390 String res = request.getHttpHandlerPath();
391 if (res.startsWith("/")) {
392 res = res.substring(1);
394 try (InputStream is = loader.get(res)) {
395 response.setContentType("text/javascript");
396 Writer w = response.getWriter();
398 for (int i = 0;; i++) {
412 w.append(Integer.toString(b));
415 } catch (IOException ex) {
417 response.setDetailMessage(ex.getMessage());
422 public static final class MethodInvocation {
423 final String className;
424 final String methodName;
427 MethodInvocation(String className, String methodName) {
428 this.className = className;
429 this.methodName = methodName;
433 public String toString() {