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.Enumeration;
31 import java.util.LinkedHashSet;
32 import java.util.List;
34 import java.util.concurrent.CountDownLatch;
35 import java.util.concurrent.TimeUnit;
36 import javax.script.Invocable;
37 import javax.script.ScriptEngine;
38 import javax.script.ScriptEngineManager;
39 import javax.script.ScriptException;
40 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
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 Set<ClassLoader> loaders = new LinkedHashSet<>();
57 private List<MethodInvocation> methods = new ArrayList<>();
60 private String showURL;
61 private final Res resources = new Res();
64 public MethodInvocation addMethod(Class<?> clazz, String method) {
65 loaders.add(clazz.getClassLoader());
66 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
71 public void setTimeout(long ms) {
75 public void setScriptEngineName(String sen) {
79 public void setStartPage(String startpage) {
80 if (!startpage.startsWith("/")) {
81 startpage = "/" + startpage;
83 this.showURL = startpage;
86 public void addClassLoader(ClassLoader url) {
87 this.loaders.add(url);
90 public static void main( String[] args ) throws Exception {
91 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
92 l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
93 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
99 public void execute() throws IOException {
103 } else if (showURL != null) {
104 HttpServer server = initServer();
105 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
106 launchServerAndBrwsr(server, showURL);
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 void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
126 StringBuilder sb = new StringBuilder();
127 Bck2Brwsr.generate(sb, new Res());
129 ScriptEngineManager sem = new ScriptEngineManager();
130 ScriptEngine mach = sem.getEngineByExtension(sen);
133 "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
134 + "\nfunction initVM() { return vm; };"
137 Object res = mach.eval(sb.toString());
138 if (!(mach instanceof Invocable)) {
139 throw new IOException("It is invocable object: " + res);
141 Invocable code = (Invocable) mach;
143 Object vm = code.invokeFunction("initVM");
144 Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
146 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
147 for (MethodInvocation mi : cases) {
148 mi.result = code.invokeMethod(console,
149 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
150 mi.className, mi.methodName
155 private HttpServer initServer() {
156 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
158 final ServerConfiguration conf = server.getServerConfiguration();
159 conf.addHttpHandler(new Page(resources,
160 "org/apidesign/bck2brwsr/launcher/console.xhtml",
161 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
163 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
164 conf.addHttpHandler(new VMInit(), "/vm.js");
165 conf.addHttpHandler(new Classes(resources), "/classes/");
169 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
170 final CountDownLatch wait = new CountDownLatch(1);
171 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
173 HttpServer server = initServer();
174 ServerConfiguration conf = server.getServerConfiguration();
175 conf.addHttpHandler(new Page(resources,
176 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
178 conf.addHttpHandler(new HttpHandler() {
181 public void service(Request request, Response response) throws Exception {
182 String id = request.getParameter("request");
183 String value = request.getParameter("result");
184 if (id != null && value != null) {
185 value = value.replace("%20", " ");
186 cases[Integer.parseInt(id)].result = value;
189 if (cnt >= cases.length) {
190 response.getWriter().write("");
196 response.getWriter().write("{"
197 + "className: '" + cases[cnt].className + "', "
198 + "methodName: '" + cases[cnt].methodName + "', "
205 launchServerAndBrwsr(server, "/execute");
207 wait.await(timeOut, TimeUnit.MILLISECONDS);
211 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
218 int cnt = is.read() - '0';
219 if (cnt == 'U' - '0') {
220 os.write(baseURL.getBytes());
222 if (cnt < params.length) {
223 os.write(params[cnt].getBytes());
231 private void launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
233 NetworkListener listener = server.getListeners().iterator().next();
234 int port = listener.getPort();
236 URI uri = new URI("http://localhost:" + port + page);
238 Desktop.getDesktop().browse(uri);
239 } catch (UnsupportedOperationException ex) {
241 "xdg-open", uri.toString()
243 Runtime.getRuntime().exec(cmd).waitFor();
245 System.err.println("Showing " + uri);
248 private class Res implements Bck2Brwsr.Resources {
250 public InputStream get(String resource) throws IOException {
251 for (ClassLoader l : loaders) {
253 Enumeration<URL> en = l.getResources(resource);
254 while (en.hasMoreElements()) {
255 u = en.nextElement();
258 return u.openStream();
261 throw new IOException("Can't find " + resource);
265 private static class Page extends HttpHandler {
266 private final String resource;
267 private final String[] args;
268 private final Res res;
270 public Page(Res res, String resource, String... args) {
272 this.resource = resource;
277 public void service(Request request, Response response) throws Exception {
280 r = request.getHttpHandlerPath();
281 if (r.startsWith("/")) {
285 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
286 response.setContentType("text/html");
288 OutputStream os = response.getOutputStream();
289 try (InputStream is = res.get(r)) {
290 copyStream(is, os, request.getRequestURL().toString(), args);
291 } catch (IOException ex) {
292 response.setDetailMessage(ex.getLocalizedMessage());
294 response.setStatus(404);
299 private static class VM extends HttpHandler {
300 private final Res loader;
302 public VM(Res loader) {
303 this.loader = loader;
307 public void service(Request request, Response response) throws Exception {
308 response.setCharacterEncoding("UTF-8");
309 response.setContentType("text/javascript");
310 Bck2Brwsr.generate(response.getWriter(), loader);
313 private static class VMInit extends HttpHandler {
318 public void service(Request request, Response response) throws Exception {
319 response.setCharacterEncoding("UTF-8");
320 response.setContentType("text/javascript");
321 response.getWriter().append(
322 "function ldCls(res) {\n"
323 + " var request = new XMLHttpRequest();\n"
324 + " request.open('GET', '/classes/' + res, false);\n"
325 + " request.send();\n"
326 + " var arr = eval('(' + request.responseText + ')');\n"
329 + "var vm = new bck2brwsr(ldCls);\n");
333 private static class Classes extends HttpHandler {
334 private final Res loader;
336 public Classes(Res loader) {
337 this.loader = loader;
341 public void service(Request request, Response response) throws Exception {
342 String res = request.getHttpHandlerPath();
343 if (res.startsWith("/")) {
344 res = res.substring(1);
346 try (InputStream is = loader.get(res)) {
347 response.setContentType("text/javascript");
348 Writer w = response.getWriter();
350 for (int i = 0;; i++) {
364 w.append(Integer.toString(b));
367 } catch (IOException ex) {
369 response.setDetailMessage(ex.getMessage());
374 public static final class MethodInvocation {
375 final String className;
376 final String methodName;
379 MethodInvocation(String className, String methodName) {
380 this.className = className;
381 this.methodName = methodName;
385 public String toString() {