Rewriting the (dynamic) calculator demo to be able to reference JARs, but load from a server
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.io.Closeable;
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.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Enumeration;
33 import java.util.LinkedHashSet;
34 import java.util.List;
36 import java.util.concurrent.BlockingQueue;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.LinkedBlockingQueue;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
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 and tests.
54 * Supports execution in native browser as well as Java's internal
57 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
58 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
59 private static final InvocationContext END = new InvocationContext(null, null, null);
60 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
63 private final Res resources = new Res();
64 private final String cmd;
65 private Object[] brwsr;
66 private HttpServer server;
67 private CountDownLatch wait;
69 public Bck2BrwsrLauncher(String cmd) {
74 InvocationContext runMethod(InvocationContext c) throws IOException {
75 loaders.add(c.clazz.getClassLoader());
79 } catch (InterruptedException ex) {
80 throw new IOException(ex);
85 public void setTimeout(long ms) {
89 public void addClassLoader(ClassLoader url) {
90 this.loaders.add(url);
93 public void showURL(String startpage) throws IOException {
94 if (!startpage.startsWith("/")) {
95 startpage = "/" + startpage;
97 HttpServer s = initServer(".", true);
98 s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), "/index.xhtml");
99 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
101 launchServerAndBrwsr(s, "/index.xhtml");
102 } catch (URISyntaxException | InterruptedException ex) {
103 throw new IOException(ex);
107 void showDirectory(File dir, String startpage) throws IOException {
108 if (!startpage.startsWith("/")) {
109 startpage = "/" + startpage;
111 HttpServer s = initServer(dir.getPath(), false);
113 launchServerAndBrwsr(s, startpage);
114 } catch (URISyntaxException | InterruptedException ex) {
115 throw new IOException(ex);
120 public void initialize() throws IOException {
123 } catch (InterruptedException ex) {
124 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
127 } catch (Exception ex) {
128 if (ex instanceof IOException) {
129 throw (IOException)ex;
131 if (ex instanceof RuntimeException) {
132 throw (RuntimeException)ex;
134 throw new IOException(ex);
138 private HttpServer initServer(String path, boolean addClasses) throws IOException {
139 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
141 final ServerConfiguration conf = s.getServerConfiguration();
143 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
144 conf.addHttpHandler(new Classes(resources), "/classes/");
149 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
150 wait = new CountDownLatch(1);
151 server = initServer(".", true);
152 final ServerConfiguration conf = server.getServerConfiguration();
154 class DynamicResourceHandler extends HttpHandler {
155 private final InvocationContext ic;
156 public DynamicResourceHandler(InvocationContext ic) {
157 if (ic == null || ic.resources.isEmpty()) {
158 throw new NullPointerException();
161 for (Resource r : ic.resources) {
162 conf.addHttpHandler(this, r.httpPath);
166 public void close() {
167 conf.removeHttpHandler(this);
171 public void service(Request request, Response response) throws Exception {
172 for (Resource r : ic.resources) {
173 if (r.httpPath.equals(request.getRequestURI())) {
174 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
175 response.setContentType(r.httpType);
176 copyStream(r.httpContent, response.getOutputStream(), null);
182 conf.addHttpHandler(new Page(resources,
183 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
186 conf.addHttpHandler(new HttpHandler() {
188 List<InvocationContext> cases = new ArrayList<>();
189 DynamicResourceHandler prev;
191 public void service(Request request, Response response) throws Exception {
192 String id = request.getParameter("request");
193 String value = request.getParameter("result");
196 InvocationContext mi = null;
199 if (id != null && value != null) {
200 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
201 value = decodeURL(value);
202 int indx = Integer.parseInt(id);
203 cases.get(indx).result(value, null);
204 if (++indx < cases.size()) {
205 mi = cases.get(indx);
206 LOG.log(Level.INFO, "Re-executing case {0}", indx);
210 if (!cases.isEmpty()) {
211 LOG.info("Re-executing test cases");
227 response.getWriter().write("");
230 LOG.log(Level.INFO, "End of data reached. Exiting.");
234 if (!mi.resources.isEmpty()) {
235 prev = new DynamicResourceHandler(mi);
239 final String cn = mi.clazz.getName();
240 final String mn = mi.methodName;
241 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
242 response.getWriter().write("{"
243 + "className: '" + cn + "', "
244 + "methodName: '" + mn + "', "
245 + "request: " + caseNmbr
247 if (mi.html != null) {
248 response.getWriter().write(", html: '");
249 response.getWriter().write(encodeJSON(mi.html));
250 response.getWriter().write("'");
252 response.getWriter().write("}");
256 this.brwsr = launchServerAndBrwsr(server, "/execute");
259 private static String encodeJSON(String in) {
260 StringBuilder sb = new StringBuilder();
261 for (int i = 0; i < in.length(); i++) {
262 char ch = in.charAt(i);
263 if (ch < 32 || ch == '\'' || ch == '"') {
265 String hs = "0000" + Integer.toHexString(ch);
266 hs = hs.substring(hs.length() - 4);
272 return sb.toString();
276 public void shutdown() throws IOException {
279 int prev = methods.size();
281 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
284 } catch (InterruptedException ex) {
285 throw new IOException(ex);
287 if (prev == methods.size()) {
290 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
296 "Timeout, but tests got from {0} to {1}. Trying again.",
297 new Object[]{prev, methods.size()}
300 stopServerAndBrwsr(server, brwsr);
303 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
309 if (ch == '$' && params.length > 0) {
310 int cnt = is.read() - '0';
311 if (cnt == 'U' - '0') {
312 os.write(baseURL.getBytes());
314 if (cnt >= 0 && cnt < params.length) {
315 os.write(params[cnt].getBytes());
323 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
325 NetworkListener listener = server.getListeners().iterator().next();
326 int port = listener.getPort();
328 URI uri = new URI("http://localhost:" + port + page);
329 LOG.log(Level.INFO, "Showing {0}", uri);
332 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
333 System.getProperty("java.vm.name"),
334 System.getProperty("java.vm.vendor"),
335 System.getProperty("java.vm.version"),
337 java.awt.Desktop.getDesktop().browse(uri);
338 LOG.log(Level.INFO, "Desktop.browse successfully finished");
340 } catch (UnsupportedOperationException ex) {
341 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
342 LOG.log(Level.FINE, null, ex);
346 String cmdName = cmd == null ? "xdg-open" : cmd;
348 cmdName, uri.toString()
350 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
351 final Process process = Runtime.getRuntime().exec(cmdArr);
352 return new Object[] { process, null };
356 private static String decodeURL(String s) {
358 int pos = s.indexOf('%');
362 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
363 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
367 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
371 Process process = (Process)brwsr[0];
374 InputStream stdout = process.getInputStream();
375 InputStream stderr = process.getErrorStream();
376 drain("StdOut", stdout);
377 drain("StdErr", stderr);
381 res = process.waitFor();
382 } catch (InterruptedException ex) {
383 throw new IOException(ex);
385 LOG.log(Level.INFO, "Exit code: {0}", res);
387 deleteTree((File)brwsr[1]);
390 private static void drain(String name, InputStream is) throws IOException {
391 int av = is.available();
393 StringBuilder sb = new StringBuilder();
394 sb.append("v== ").append(name).append(" ==v\n");
396 sb.append((char)is.read());
398 sb.append("\n^== ").append(name).append(" ==^");
399 LOG.log(Level.INFO, sb.toString());
403 private void deleteTree(File file) {
407 File[] arr = file.listFiles();
417 public void close() throws IOException {
421 private class Res implements Bck2Brwsr.Resources {
423 public InputStream get(String resource) throws IOException {
424 for (ClassLoader l : loaders) {
426 Enumeration<URL> en = l.getResources(resource);
427 while (en.hasMoreElements()) {
428 u = en.nextElement();
431 return u.openStream();
434 throw new IOException("Can't find " + resource);
438 private static class Page extends HttpHandler {
439 private final String resource;
440 private final String[] args;
441 private final Res res;
443 public Page(Res res, String resource, String... args) {
445 this.resource = resource;
446 this.args = args.length == 0 ? new String[] { "$0" } : args;
450 public void service(Request request, Response response) throws Exception {
453 r = request.getHttpHandlerPath();
455 if (r.startsWith("/")) {
458 String[] replace = {};
459 if (r.endsWith(".html")) {
460 response.setContentType("text/html");
461 LOG.info("Content type text/html");
464 if (r.endsWith(".xhtml")) {
465 response.setContentType("application/xhtml+xml");
466 LOG.info("Content type application/xhtml+xml");
469 OutputStream os = response.getOutputStream();
470 try (InputStream is = res.get(r)) {
471 copyStream(is, os, request.getRequestURL().toString(), replace);
472 } catch (IOException ex) {
473 response.setDetailMessage(ex.getLocalizedMessage());
475 response.setStatus(404);
480 private static class VM extends HttpHandler {
481 private final String bck2brwsr;
483 public VM(Res loader) throws IOException {
484 StringBuilder sb = new StringBuilder();
485 Bck2Brwsr.generate(sb, loader);
487 "(function WrapperVM(global) {"
488 + " function ldCls(res) {\n"
489 + " var request = new XMLHttpRequest();\n"
490 + " request.open('GET', '/classes/' + res, false);\n"
491 + " request.send();\n"
492 + " var arr = eval('(' + request.responseText + ')');\n"
495 + " var prevvm = global.bck2brwsr;\n"
496 + " global.bck2brwsr = function() {\n"
497 + " return prevvm(ldCls);\n"
501 this.bck2brwsr = sb.toString();
505 public void service(Request request, Response response) throws Exception {
506 response.setCharacterEncoding("UTF-8");
507 response.setContentType("text/javascript");
508 response.getWriter().write(bck2brwsr);
512 private static class Classes extends HttpHandler {
513 private final Res loader;
515 public Classes(Res loader) {
516 this.loader = loader;
520 public void service(Request request, Response response) throws Exception {
521 String res = request.getHttpHandlerPath();
522 if (res.startsWith("/")) {
523 res = res.substring(1);
525 try (InputStream is = loader.get(res)) {
526 response.setContentType("text/javascript");
527 Writer w = response.getWriter();
529 for (int i = 0;; i++) {
543 w.append(Integer.toString(b));
546 } catch (IOException ex) {
548 response.setDetailMessage(ex.getMessage());