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 javax.script.Invocable;
38 import javax.script.ScriptEngine;
39 import javax.script.ScriptEngineManager;
40 import javax.script.ScriptException;
41 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
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 public class Bck2BrwsrLauncher {
57 private Set<ClassLoader> loaders = new LinkedHashSet<>();
58 private List<MethodInvocation> methods = new ArrayList<>();
61 private String showURL;
62 private final Res resources = new Res();
65 public MethodInvocation addMethod(Class<?> clazz, String method) {
66 loaders.add(clazz.getClassLoader());
67 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
72 public void setTimeout(long ms) {
76 public void setScriptEngineName(String sen) {
80 public void setStartPage(String startpage) {
81 if (!startpage.startsWith("/")) {
82 startpage = "/" + startpage;
84 this.showURL = startpage;
87 public void addClassLoader(ClassLoader url) {
88 this.loaders.add(url);
91 public static void main( String[] args ) throws Exception {
92 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
93 l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
94 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
100 public void execute() throws IOException {
104 } else if (showURL != null) {
105 HttpServer server = initServer();
106 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
107 launchServerAndBrwsr(server, showURL);
111 } catch (InterruptedException ex) {
112 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
115 } catch (Exception ex) {
116 if (ex instanceof IOException) {
117 throw (IOException)ex;
119 if (ex instanceof RuntimeException) {
120 throw (RuntimeException)ex;
122 throw new IOException(ex);
126 private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
127 StringBuilder sb = new StringBuilder();
128 Bck2Brwsr.generate(sb, new Res());
130 ScriptEngineManager sem = new ScriptEngineManager();
131 ScriptEngine mach = sem.getEngineByExtension(sen);
134 "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
135 + "\nfunction initVM() { return vm; };"
138 Object res = mach.eval(sb.toString());
139 if (!(mach instanceof Invocable)) {
140 throw new IOException("It is invocable object: " + res);
142 Invocable code = (Invocable) mach;
144 Object vm = code.invokeFunction("initVM");
145 Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
147 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
148 for (MethodInvocation mi : cases) {
149 mi.result = code.invokeMethod(console,
150 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
151 mi.className, mi.methodName
156 private HttpServer initServer() {
157 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
159 final ServerConfiguration conf = server.getServerConfiguration();
160 conf.addHttpHandler(new Page(resources,
161 "org/apidesign/bck2brwsr/launcher/console.xhtml",
162 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
164 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
165 conf.addHttpHandler(new VMInit(), "/vm.js");
166 conf.addHttpHandler(new Classes(resources), "/classes/");
170 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
171 final CountDownLatch wait = new CountDownLatch(1);
172 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
174 HttpServer server = initServer();
175 ServerConfiguration conf = server.getServerConfiguration();
176 conf.addHttpHandler(new Page(resources,
177 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
179 conf.addHttpHandler(new HttpHandler() {
182 public void service(Request request, Response response) throws Exception {
183 String id = request.getParameter("request");
184 String value = request.getParameter("result");
185 if (id != null && value != null) {
186 value = value.replace("%20", " ");
187 cases[Integer.parseInt(id)].result = value;
190 if (cnt >= cases.length) {
191 response.getWriter().write("");
197 response.getWriter().write("{"
198 + "className: '" + cases[cnt].className + "', "
199 + "methodName: '" + cases[cnt].methodName + "', "
206 launchServerAndBrwsr(server, "/execute");
208 wait.await(timeOut, TimeUnit.MILLISECONDS);
212 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
219 int cnt = is.read() - '0';
220 if (cnt == 'U' - '0') {
221 os.write(baseURL.getBytes());
223 if (cnt < params.length) {
224 os.write(params[cnt].getBytes());
232 private void launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
234 NetworkListener listener = server.getListeners().iterator().next();
235 int port = listener.getPort();
237 URI uri = new URI("http://localhost:" + port + page);
238 System.err.println("Showing " + uri);
240 Desktop.getDesktop().browse(uri);
241 } catch (UnsupportedOperationException ex) {
243 "xdg-open", uri.toString()
245 System.err.println("Launching " + Arrays.toString(cmd));
246 final Process process = Runtime.getRuntime().exec(cmd);
247 InputStream stdout = process.getInputStream();
248 InputStream stderr = process.getErrorStream();
249 int res = process.waitFor();
250 System.err.println("Exit code: " + res);
251 drain("StdOut", stdout);
252 drain("StdErr", stderr);
256 private static void drain(String name, InputStream is) throws IOException {
257 int av = is.available();
259 System.err.println("v== " + name + " ==v");
261 System.err.write(is.read());
263 System.err.println();
264 System.err.println("^== " + name + " ==^");
268 private class Res implements Bck2Brwsr.Resources {
270 public InputStream get(String resource) throws IOException {
271 for (ClassLoader l : loaders) {
273 Enumeration<URL> en = l.getResources(resource);
274 while (en.hasMoreElements()) {
275 u = en.nextElement();
278 return u.openStream();
281 throw new IOException("Can't find " + resource);
285 private static class Page extends HttpHandler {
286 private final String resource;
287 private final String[] args;
288 private final Res res;
290 public Page(Res res, String resource, String... args) {
292 this.resource = resource;
297 public void service(Request request, Response response) throws Exception {
300 r = request.getHttpHandlerPath();
301 if (r.startsWith("/")) {
305 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
306 response.setContentType("text/html");
308 OutputStream os = response.getOutputStream();
309 try (InputStream is = res.get(r)) {
310 copyStream(is, os, request.getRequestURL().toString(), args);
311 } catch (IOException ex) {
312 response.setDetailMessage(ex.getLocalizedMessage());
314 response.setStatus(404);
319 private static class VM extends HttpHandler {
320 private final Res loader;
322 public VM(Res loader) {
323 this.loader = loader;
327 public void service(Request request, Response response) throws Exception {
328 response.setCharacterEncoding("UTF-8");
329 response.setContentType("text/javascript");
330 Bck2Brwsr.generate(response.getWriter(), loader);
333 private static class VMInit extends HttpHandler {
338 public void service(Request request, Response response) throws Exception {
339 response.setCharacterEncoding("UTF-8");
340 response.setContentType("text/javascript");
341 response.getWriter().append(
342 "function ldCls(res) {\n"
343 + " var request = new XMLHttpRequest();\n"
344 + " request.open('GET', '/classes/' + res, false);\n"
345 + " request.send();\n"
346 + " var arr = eval('(' + request.responseText + ')');\n"
349 + "var vm = new bck2brwsr(ldCls);\n");
353 private static class Classes extends HttpHandler {
354 private final Res loader;
356 public Classes(Res loader) {
357 this.loader = loader;
361 public void service(Request request, Response response) throws Exception {
362 String res = request.getHttpHandlerPath();
363 if (res.startsWith("/")) {
364 res = res.substring(1);
366 try (InputStream is = loader.get(res)) {
367 response.setContentType("text/javascript");
368 Writer w = response.getWriter();
370 for (int i = 0;; i++) {
384 w.append(Integer.toString(b));
387 } catch (IOException ex) {
389 response.setDetailMessage(ex.getMessage());
394 public static final class MethodInvocation {
395 final String className;
396 final String methodName;
399 MethodInvocation(String className, String methodName) {
400 this.className = className;
401 this.methodName = methodName;
405 public String toString() {