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;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InterruptedIOException;
25 import java.io.OutputStream;
26 import java.io.Writer;
28 import java.net.URISyntaxException;
30 import java.nio.file.Files;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Enumeration;
34 import java.util.LinkedHashSet;
35 import java.util.List;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import javax.script.Invocable;
42 import javax.script.ScriptEngine;
43 import javax.script.ScriptEngineManager;
44 import javax.script.ScriptException;
45 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
46 import org.apidesign.vm4brwsr.Bck2Brwsr;
47 import org.glassfish.grizzly.PortRange;
48 import org.glassfish.grizzly.http.server.HttpHandler;
49 import org.glassfish.grizzly.http.server.HttpServer;
50 import org.glassfish.grizzly.http.server.NetworkListener;
51 import org.glassfish.grizzly.http.server.Request;
52 import org.glassfish.grizzly.http.server.Response;
53 import org.glassfish.grizzly.http.server.ServerConfiguration;
56 * Lightweight server to launch Bck2Brwsr applications and tests.
57 * Supports execution in native browser as well as Java's internal
60 public class Bck2BrwsrLauncher {
61 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
62 private Set<ClassLoader> loaders = new LinkedHashSet<>();
63 private List<MethodInvocation> methods = new ArrayList<>();
66 private String showURL;
67 private final Res resources = new Res();
70 public MethodInvocation addMethod(Class<?> clazz, String method) {
71 loaders.add(clazz.getClassLoader());
72 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
77 public void setTimeout(long ms) {
81 public void setScriptEngineName(String sen) {
85 public void setStartPage(String startpage) {
86 if (!startpage.startsWith("/")) {
87 startpage = "/" + startpage;
89 this.showURL = startpage;
92 public void addClassLoader(ClassLoader url) {
93 this.loaders.add(url);
96 public static void main( String[] args ) throws Exception {
97 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
98 l.setStartPage("org/apidesign/bck2brwsr/launcher/console.xhtml");
99 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
105 public void execute() throws IOException {
109 } else if (showURL != null) {
110 HttpServer server = initServer();
111 server.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
112 launchServerAndBrwsr(server, showURL);
116 } catch (InterruptedException ex) {
117 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
120 } catch (Exception ex) {
121 if (ex instanceof IOException) {
122 throw (IOException)ex;
124 if (ex instanceof RuntimeException) {
125 throw (RuntimeException)ex;
127 throw new IOException(ex);
131 private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
132 StringBuilder sb = new StringBuilder();
133 Bck2Brwsr.generate(sb, new Res());
135 ScriptEngineManager sem = new ScriptEngineManager();
136 ScriptEngine mach = sem.getEngineByExtension(sen);
139 "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.Console.read);"
140 + "\nfunction initVM() { return vm; };"
143 Object res = mach.eval(sb.toString());
144 if (!(mach instanceof Invocable)) {
145 throw new IOException("It is invocable object: " + res);
147 Invocable code = (Invocable) mach;
149 Object vm = code.invokeFunction("initVM");
150 Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
152 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
153 for (MethodInvocation mi : cases) {
154 mi.result = code.invokeMethod(console,
155 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
156 mi.className, mi.methodName
161 private HttpServer initServer() {
162 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
164 final ServerConfiguration conf = server.getServerConfiguration();
165 conf.addHttpHandler(new Page(resources,
166 "org/apidesign/bck2brwsr/launcher/console.xhtml",
167 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
169 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
170 conf.addHttpHandler(new VMInit(), "/vm.js");
171 conf.addHttpHandler(new Classes(resources), "/classes/");
175 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
176 final CountDownLatch wait = new CountDownLatch(1);
177 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
179 HttpServer server = initServer();
180 ServerConfiguration conf = server.getServerConfiguration();
181 conf.addHttpHandler(new Page(resources,
182 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
184 final int[] currentTest = { -1 };
185 conf.addHttpHandler(new HttpHandler() {
188 public void service(Request request, Response response) throws Exception {
189 String id = request.getParameter("request");
190 String value = request.getParameter("result");
192 if (id != null && value != null) {
193 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
194 value = value.replace("%20", " ");
195 cases[Integer.parseInt(id)].result = value;
197 currentTest[0] = cnt;
199 if (cnt >= cases.length) {
200 response.getWriter().write("");
206 final String cn = cases[cnt].className;
207 final String mn = cases[cnt].methodName;
208 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
209 response.getWriter().write("{"
210 + "className: '" + cn + "', "
211 + "methodName: '" + mn + "', "
218 Object[] brwsr = launchServerAndBrwsr(server, "/execute");
221 int prev = currentTest[0];
222 if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
225 if (prev == currentTest[0]) {
228 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
234 "Timeout, but tests got from {0} to {1}. Trying again.",
235 new Object[]{prev, currentTest[0]}
238 stopServerAndBrwsr(server, brwsr);
241 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
248 int cnt = is.read() - '0';
249 if (cnt == 'U' - '0') {
250 os.write(baseURL.getBytes());
252 if (cnt < params.length) {
253 os.write(params[cnt].getBytes());
261 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
263 NetworkListener listener = server.getListeners().iterator().next();
264 int port = listener.getPort();
266 URI uri = new URI("http://localhost:" + port + page);
267 LOG.log(Level.INFO, "Showing {0}", uri);
269 // Desktop.getDesktop().browse(uri);
271 // } catch (UnsupportedOperationException ex)
273 // File dir = File.createTempFile("chrome", ".dir");
277 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
279 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
280 // final Process process = Runtime.getRuntime().exec(cmd);
281 // return new Object[] { process, dir };
285 "xdg-open", uri.toString()
287 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
288 final Process process = Runtime.getRuntime().exec(cmd);
289 return new Object[] { process, null };
293 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
294 Process process = (Process)brwsr[0];
297 InputStream stdout = process.getInputStream();
298 InputStream stderr = process.getErrorStream();
299 drain("StdOut", stdout);
300 drain("StdErr", stderr);
302 int res = process.waitFor();
303 LOG.log(Level.INFO, "Exit code: {0}", res);
305 deleteTree((File)brwsr[1]);
308 private static void drain(String name, InputStream is) throws IOException {
309 int av = is.available();
311 StringBuilder sb = new StringBuilder();
312 sb.append("v== ").append(name).append(" ==v\n");
314 sb.append((char)is.read());
316 sb.append("\n^== ").append(name).append(" ==^");
317 LOG.log(Level.INFO, sb.toString());
321 private void deleteTree(File file) {
325 File[] arr = file.listFiles();
334 private class Res implements Bck2Brwsr.Resources {
336 public InputStream get(String resource) throws IOException {
337 for (ClassLoader l : loaders) {
339 Enumeration<URL> en = l.getResources(resource);
340 while (en.hasMoreElements()) {
341 u = en.nextElement();
344 return u.openStream();
347 throw new IOException("Can't find " + resource);
351 private static class Page extends HttpHandler {
352 private final String resource;
353 private final String[] args;
354 private final Res res;
356 public Page(Res res, String resource, String... args) {
358 this.resource = resource;
363 public void service(Request request, Response response) throws Exception {
366 r = request.getHttpHandlerPath();
367 if (r.startsWith("/")) {
371 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
372 response.setContentType("text/html");
374 OutputStream os = response.getOutputStream();
375 try (InputStream is = res.get(r)) {
376 copyStream(is, os, request.getRequestURL().toString(), args);
377 } catch (IOException ex) {
378 response.setDetailMessage(ex.getLocalizedMessage());
380 response.setStatus(404);
385 private static class VM extends HttpHandler {
386 private final Res loader;
388 public VM(Res loader) {
389 this.loader = loader;
393 public void service(Request request, Response response) throws Exception {
394 response.setCharacterEncoding("UTF-8");
395 response.setContentType("text/javascript");
396 Bck2Brwsr.generate(response.getWriter(), loader);
399 private static class VMInit extends HttpHandler {
404 public void service(Request request, Response response) throws Exception {
405 response.setCharacterEncoding("UTF-8");
406 response.setContentType("text/javascript");
407 response.getWriter().append(
408 "function ldCls(res) {\n"
409 + " var request = new XMLHttpRequest();\n"
410 + " request.open('GET', '/classes/' + res, false);\n"
411 + " request.send();\n"
412 + " var arr = eval('(' + request.responseText + ')');\n"
415 + "var vm = new bck2brwsr(ldCls);\n");
419 private static class Classes extends HttpHandler {
420 private final Res loader;
422 public Classes(Res loader) {
423 this.loader = loader;
427 public void service(Request request, Response response) throws Exception {
428 String res = request.getHttpHandlerPath();
429 if (res.startsWith("/")) {
430 res = res.substring(1);
432 try (InputStream is = loader.get(res)) {
433 response.setContentType("text/javascript");
434 Writer w = response.getWriter();
436 for (int i = 0;; i++) {
450 w.append(Integer.toString(b));
453 } catch (IOException ex) {
455 response.setDetailMessage(ex.getMessage());
460 public static final class MethodInvocation {
461 final String className;
462 final String methodName;
465 MethodInvocation(String className, String methodName) {
466 this.className = className;
467 this.methodName = methodName;
471 public String toString() {