Using the Console for invoking VMTests in Rhino. All tests are passing now.
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 java.util.logging.Level;
37 import java.util.logging.Logger;
38 import javax.script.Invocable;
39 import javax.script.ScriptEngine;
40 import javax.script.ScriptEngineManager;
41 import javax.script.ScriptException;
42 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
43 import org.apidesign.vm4brwsr.Bck2Brwsr;
44 import org.glassfish.grizzly.PortRange;
45 import org.glassfish.grizzly.http.server.HttpHandler;
46 import org.glassfish.grizzly.http.server.HttpServer;
47 import org.glassfish.grizzly.http.server.NetworkListener;
48 import org.glassfish.grizzly.http.server.Request;
49 import org.glassfish.grizzly.http.server.Response;
50 import org.glassfish.grizzly.http.server.ServerConfiguration;
53 * Lightweight server to launch Bck2Brwsr applications in real browser.
55 public class Bck2BrwsrLauncher {
56 private Set<ClassLoader> loaders = new LinkedHashSet<>();
57 private List<MethodInvocation> methods = new ArrayList<>();
62 public MethodInvocation addMethod(Class<?> clazz, String method) {
63 loaders.add(clazz.getClassLoader());
64 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
69 public void setTimeout(long ms) {
73 public void setScriptEngineName(String sen) {
77 public static void main( String[] args ) throws Exception {
78 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
80 final MethodInvocation[] cases = {
81 l.addMethod(Console.class, "welcome"),
82 l.addMethod(Console.class, "multiply"),
87 for (MethodInvocation c : cases) {
88 System.err.println(c.className + "." + c.methodName + " = " + c.result);
93 public void execute() throws IOException {
100 } catch (InterruptedException ex) {
101 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
104 } catch (Exception ex) {
105 if (ex instanceof IOException) {
106 throw (IOException)ex;
108 if (ex instanceof RuntimeException) {
109 throw (RuntimeException)ex;
111 throw new IOException(ex);
115 private void executeRhino() throws IOException, ScriptException, NoSuchMethodException {
116 StringBuilder sb = new StringBuilder();
117 Bck2Brwsr.generate(sb, new Res());
119 ScriptEngineManager sem = new ScriptEngineManager();
120 ScriptEngine mach = sem.getEngineByExtension(sen);
123 "\nvar vm = bck2brwsr(org.apidesign.bck2brwsr.vmtest.VMTest.read);"
124 + "\nfunction initVM() { return vm; };"
127 Object res = mach.eval(sb.toString());
128 if (!(mach instanceof Invocable)) {
129 throw new IOException("It is invocable object: " + res);
131 Invocable code = (Invocable) mach;
133 Object vm = code.invokeFunction("initVM");
134 Object console = code.invokeMethod(vm, "loadClass", Console.class.getName());
136 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
137 for (MethodInvocation mi : cases) {
138 mi.result = code.invokeMethod(console,
139 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
140 mi.className, mi.methodName
145 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
146 final CountDownLatch wait = new CountDownLatch(1);
147 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
149 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
151 Res resources = new Res();
153 final ServerConfiguration conf = server.getServerConfiguration();
154 conf.addHttpHandler(new Page("console.xhtml",
155 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
157 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
158 conf.addHttpHandler(new VMInit(), "/vm.js");
159 conf.addHttpHandler(new Classes(resources), "/classes/");
160 conf.addHttpHandler(new HttpHandler() {
163 public void service(Request request, Response response) throws Exception {
164 String id = request.getParameter("request");
165 String value = request.getParameter("result");
166 if (id != null && value != null) {
167 value = value.replace("%20", " ");
168 cases[Integer.parseInt(id)].result = value;
171 if (cnt >= cases.length) {
172 response.getWriter().write("");
178 response.getWriter().write("{"
179 + "className: '" + cases[cnt].className + "', "
180 + "methodName: '" + cases[cnt].methodName + "', "
186 conf.addHttpHandler(new Page("harness.xhtml"), "/");
189 NetworkListener listener = server.getListeners().iterator().next();
190 int port = listener.getPort();
192 URI uri = new URI("http://localhost:" + port + "/execute");
194 Desktop.getDesktop().browse(uri);
195 } catch (UnsupportedOperationException ex) {
197 "xdg-open", uri.toString()
199 Runtime.getRuntime().exec(cmd).waitFor();
202 wait.await(timeOut, TimeUnit.MILLISECONDS);
206 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
213 int cnt = is.read() - '0';
214 if (cnt == 'U' - '0') {
215 os.write(baseURL.getBytes());
217 if (cnt < params.length) {
218 os.write(params[cnt].getBytes());
226 private class Res implements Bck2Brwsr.Resources {
228 public InputStream get(String resource) throws IOException {
229 for (ClassLoader l : loaders) {
231 Enumeration<URL> en = l.getResources(resource);
232 while (en.hasMoreElements()) {
233 u = en.nextElement();
236 return u.openStream();
239 throw new IOException("Can't find " + resource);
243 private static class Page extends HttpHandler {
244 private final String resource;
245 private final String[] args;
247 public Page(String resource, String... args) {
248 this.resource = resource;
253 public void service(Request request, Response response) throws Exception {
254 response.setContentType("text/html");
255 OutputStream os = response.getOutputStream();
256 InputStream is = Bck2BrwsrLauncher.class.getResourceAsStream(resource);
257 copyStream(is, os, request.getRequestURL().toString(), args);
261 private static class VM extends HttpHandler {
262 private final Res loader;
264 public VM(Res loader) {
265 this.loader = loader;
269 public void service(Request request, Response response) throws Exception {
270 response.setCharacterEncoding("UTF-8");
271 response.setContentType("text/javascript");
272 Bck2Brwsr.generate(response.getWriter(), loader);
275 private static class VMInit extends HttpHandler {
280 public void service(Request request, Response response) throws Exception {
281 response.setCharacterEncoding("UTF-8");
282 response.setContentType("text/javascript");
283 response.getWriter().append(
284 "function ldCls(res) {\n"
285 + " var request = new XMLHttpRequest();\n"
286 + " request.open('GET', 'classes/' + res, false);\n"
287 + " request.send();\n"
288 + " var arr = eval('(' + request.responseText + ')');\n"
291 + "var vm = new bck2brwsr(ldCls);\n");
295 private static class Classes extends HttpHandler {
296 private final Res loader;
298 public Classes(Res loader) {
299 this.loader = loader;
303 public void service(Request request, Response response) throws Exception {
304 String res = request.getHttpHandlerPath();
305 if (res.startsWith("/")) {
306 res = res.substring(1);
308 try (InputStream is = loader.get(res)) {
309 response.setContentType("text/javascript");
310 Writer w = response.getWriter();
312 for (int i = 0;; i++) {
326 w.append(Integer.toString(b));
329 } catch (IOException ex) {
331 response.setDetailMessage(ex.getMessage());
336 public static final class MethodInvocation {
337 final String className;
338 final String methodName;
341 MethodInvocation(String className, String methodName) {
342 this.className = className;
343 this.methodName = methodName;
347 public String toString() {