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.OutputStream;
24 import java.io.Writer;
26 import java.net.URISyntaxException;
28 import java.util.ArrayList;
29 import java.util.Enumeration;
30 import java.util.LinkedHashSet;
31 import java.util.List;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.TimeUnit;
35 import static org.apidesign.bck2brwsr.launcher.Bck2BrwsrLauncher.copyStream;
36 import org.apidesign.vm4brwsr.Bck2Brwsr;
37 import org.glassfish.grizzly.PortRange;
38 import org.glassfish.grizzly.http.server.HttpHandler;
39 import org.glassfish.grizzly.http.server.HttpServer;
40 import org.glassfish.grizzly.http.server.NetworkListener;
41 import org.glassfish.grizzly.http.server.Request;
42 import org.glassfish.grizzly.http.server.Response;
43 import org.glassfish.grizzly.http.server.ServerConfiguration;
46 * Lightweight server to launch Bck2Brwsr applications in real browser.
48 public class Bck2BrwsrLauncher {
49 private Set<ClassLoader> loaders = new LinkedHashSet<>();
50 private List<MethodInvocation> methods = new ArrayList<>();
54 public MethodInvocation addMethod(Class<?> clazz, String method) {
55 loaders.add(clazz.getClassLoader());
56 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
61 public void setTimeout(long ms) {
65 public static void main( String[] args ) throws Exception {
66 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
68 final MethodInvocation[] cases = {
69 l.addMethod(Console.class, "welcome"),
70 l.addMethod(Console.class, "multiply"),
75 for (MethodInvocation c : cases) {
76 System.err.println(c.className + "." + c.methodName + " = " + c.result);
81 public void execute() throws URISyntaxException, IOException, InterruptedException {
82 final CountDownLatch wait = new CountDownLatch(1);
83 final MethodInvocation[] cases = this.methods.toArray(new MethodInvocation[0]);
85 HttpServer server = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
87 Res resources = new Res();
89 final ServerConfiguration conf = server.getServerConfiguration();
90 conf.addHttpHandler(new Page("console.xhtml",
91 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
93 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
94 conf.addHttpHandler(new VMInit(), "/vm.js");
95 conf.addHttpHandler(new Classes(resources), "/classes/");
96 conf.addHttpHandler(new HttpHandler() {
99 public void service(Request request, Response response) throws Exception {
100 String id = request.getParameter("request");
101 String value = request.getParameter("result");
102 if (id != null && value != null) {
103 value = value.replace("%20", " ");
104 cases[Integer.parseInt(id)].result = value;
107 if (cnt >= cases.length) {
108 response.getWriter().write("");
114 response.getWriter().write("{"
115 + "className: '" + cases[cnt].className + "', "
116 + "methodName: '" + cases[cnt].methodName + "', "
122 conf.addHttpHandler(new Page("harness.xhtml"), "/");
125 NetworkListener listener = server.getListeners().iterator().next();
126 int port = listener.getPort();
128 URI uri = new URI("http://localhost:" + port + "/execute");
130 Desktop.getDesktop().browse(uri);
131 } catch (UnsupportedOperationException ex) {
133 "xdg-open", uri.toString()
135 Runtime.getRuntime().exec(cmd).waitFor();
138 wait.await(timeOut, TimeUnit.MILLISECONDS);
142 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
149 int cnt = is.read() - '0';
150 if (cnt == 'U' - '0') {
151 os.write(baseURL.getBytes());
153 if (cnt < params.length) {
154 os.write(params[cnt].getBytes());
162 private class Res implements Bck2Brwsr.Resources {
164 public InputStream get(String resource) throws IOException {
165 for (ClassLoader l : loaders) {
167 Enumeration<URL> en = l.getResources(resource);
168 while (en.hasMoreElements()) {
169 u = en.nextElement();
172 return u.openStream();
175 throw new IOException("Can't find " + resource);
179 private static class Page extends HttpHandler {
180 private final String resource;
181 private final String[] args;
183 public Page(String resource, String... args) {
184 this.resource = resource;
189 public void service(Request request, Response response) throws Exception {
190 response.setContentType("text/html");
191 OutputStream os = response.getOutputStream();
192 InputStream is = Bck2BrwsrLauncher.class.getResourceAsStream(resource);
193 copyStream(is, os, request.getRequestURL().toString(), args);
197 private static class VM extends HttpHandler {
198 private final Res loader;
200 public VM(Res loader) {
201 this.loader = loader;
205 public void service(Request request, Response response) throws Exception {
206 response.setCharacterEncoding("UTF-8");
207 response.setContentType("text/javascript");
208 Bck2Brwsr.generate(response.getWriter(), loader);
211 private static class VMInit extends HttpHandler {
216 public void service(Request request, Response response) throws Exception {
217 response.setCharacterEncoding("UTF-8");
218 response.setContentType("text/javascript");
219 response.getWriter().append(
220 "function ldCls(res) {\n"
221 + " var request = new XMLHttpRequest();\n"
222 + " request.open('GET', 'classes/' + res, false);\n"
223 + " request.send();\n"
224 + " var arr = eval('(' + request.responseText + ')');\n"
227 + "var vm = new bck2brwsr(ldCls);\n");
231 private static class Classes extends HttpHandler {
232 private final Res loader;
234 public Classes(Res loader) {
235 this.loader = loader;
239 public void service(Request request, Response response) throws Exception {
240 String res = request.getHttpHandlerPath();
241 if (res.startsWith("/")) {
242 res = res.substring(1);
244 try (InputStream is = loader.get(res)) {
245 response.setContentType("text/javascript");
246 Writer w = response.getWriter();
248 for (int i = 0;; i++) {
262 w.append(Integer.toString(b));
265 } catch (IOException ex) {
267 response.setDetailMessage(ex.getMessage());
272 public static final class MethodInvocation {
273 final String className;
274 final String methodName;
277 MethodInvocation(String className, String methodName) {
278 this.className = className;
279 this.methodName = methodName;
283 public String toString() {