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 conf.addHttpHandler(new HttpHandler() {
185 public void service(Request request, Response response) throws Exception {
186 String id = request.getParameter("request");
187 String value = request.getParameter("result");
188 if (id != null && value != null) {
189 value = value.replace("%20", " ");
190 cases[Integer.parseInt(id)].result = value;
193 if (cnt >= cases.length) {
194 response.getWriter().write("");
200 response.getWriter().write("{"
201 + "className: '" + cases[cnt].className + "', "
202 + "methodName: '" + cases[cnt].methodName + "', "
209 launchServerAndBrwsr(server, "/execute");
211 wait.await(timeOut, TimeUnit.MILLISECONDS);
215 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
222 int cnt = is.read() - '0';
223 if (cnt == 'U' - '0') {
224 os.write(baseURL.getBytes());
226 if (cnt < params.length) {
227 os.write(params[cnt].getBytes());
235 private void launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
237 NetworkListener listener = server.getListeners().iterator().next();
238 int port = listener.getPort();
240 URI uri = new URI("http://localhost:" + port + page);
241 LOG.log(Level.INFO, "Showing {0}", uri);
243 Desktop.getDesktop().browse(uri);
244 } catch (UnsupportedOperationException ex) {
246 "xdg-open", uri.toString()
248 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
249 final Process process = Runtime.getRuntime().exec(cmd);
250 InputStream stdout = process.getInputStream();
251 InputStream stderr = process.getErrorStream();
252 int res = process.waitFor();
253 LOG.log(Level.INFO, "Exit code: {0}", res);
254 drain("StdOut", stdout);
255 drain("StdErr", stderr);
259 private static void drain(String name, InputStream is) throws IOException {
260 int av = is.available();
262 StringBuilder sb = new StringBuilder();
263 sb.append("v== ").append(name).append(" ==v\n");
265 sb.append((char)is.read());
267 sb.append("\n^== ").append(name).append(" ==^");
268 LOG.log(Level.INFO, sb.toString());
272 private class Res implements Bck2Brwsr.Resources {
274 public InputStream get(String resource) throws IOException {
275 for (ClassLoader l : loaders) {
277 Enumeration<URL> en = l.getResources(resource);
278 while (en.hasMoreElements()) {
279 u = en.nextElement();
282 return u.openStream();
285 throw new IOException("Can't find " + resource);
289 private static class Page extends HttpHandler {
290 private final String resource;
291 private final String[] args;
292 private final Res res;
294 public Page(Res res, String resource, String... args) {
296 this.resource = resource;
301 public void service(Request request, Response response) throws Exception {
304 r = request.getHttpHandlerPath();
305 if (r.startsWith("/")) {
309 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
310 response.setContentType("text/html");
312 OutputStream os = response.getOutputStream();
313 try (InputStream is = res.get(r)) {
314 copyStream(is, os, request.getRequestURL().toString(), args);
315 } catch (IOException ex) {
316 response.setDetailMessage(ex.getLocalizedMessage());
318 response.setStatus(404);
323 private static class VM extends HttpHandler {
324 private final Res loader;
326 public VM(Res loader) {
327 this.loader = loader;
331 public void service(Request request, Response response) throws Exception {
332 response.setCharacterEncoding("UTF-8");
333 response.setContentType("text/javascript");
334 Bck2Brwsr.generate(response.getWriter(), loader);
337 private static class VMInit extends HttpHandler {
342 public void service(Request request, Response response) throws Exception {
343 response.setCharacterEncoding("UTF-8");
344 response.setContentType("text/javascript");
345 response.getWriter().append(
346 "function ldCls(res) {\n"
347 + " var request = new XMLHttpRequest();\n"
348 + " request.open('GET', '/classes/' + res, false);\n"
349 + " request.send();\n"
350 + " var arr = eval('(' + request.responseText + ')');\n"
353 + "var vm = new bck2brwsr(ldCls);\n");
357 private static class Classes extends HttpHandler {
358 private final Res loader;
360 public Classes(Res loader) {
361 this.loader = loader;
365 public void service(Request request, Response response) throws Exception {
366 String res = request.getHttpHandlerPath();
367 if (res.startsWith("/")) {
368 res = res.substring(1);
370 try (InputStream is = loader.get(res)) {
371 response.setContentType("text/javascript");
372 Writer w = response.getWriter();
374 for (int i = 0;; i++) {
388 w.append(Integer.toString(b));
391 } catch (IOException ex) {
393 response.setDetailMessage(ex.getMessage());
398 public static final class MethodInvocation {
399 final String className;
400 final String methodName;
403 MethodInvocation(String className, String methodName) {
404 this.className = className;
405 this.methodName = methodName;
409 public String toString() {