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;
51 import org.glassfish.grizzly.http.util.HttpStatus;
54 * Lightweight server to launch Bck2Brwsr applications and tests.
55 * Supports execution in native browser as well as Java's internal
58 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
59 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
60 private static final InvocationContext END = new InvocationContext(null, null, null);
61 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
62 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
64 private final Res resources = new Res();
65 private final String cmd;
66 private Object[] brwsr;
67 private HttpServer server;
68 private CountDownLatch wait;
70 public Bck2BrwsrLauncher(String cmd) {
75 InvocationContext runMethod(InvocationContext c) throws IOException {
76 loaders.add(c.clazz.getClassLoader());
80 } catch (InterruptedException ex) {
81 throw new IOException(ex);
86 public void setTimeout(long ms) {
90 public void addClassLoader(ClassLoader url) {
91 this.loaders.add(url);
94 public void showURL(String startpage) throws IOException {
95 if (!startpage.startsWith("/")) {
96 startpage = "/" + startpage;
98 HttpServer s = initServer(".", true);
99 int last = startpage.lastIndexOf('/');
100 String simpleName = startpage.substring(last);
101 s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), simpleName);
102 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
104 launchServerAndBrwsr(s, simpleName);
105 } catch (URISyntaxException | InterruptedException ex) {
106 throw new IOException(ex);
110 void showDirectory(File dir, String startpage) throws IOException {
111 if (!startpage.startsWith("/")) {
112 startpage = "/" + startpage;
114 HttpServer s = initServer(dir.getPath(), false);
116 launchServerAndBrwsr(s, startpage);
117 } catch (URISyntaxException | InterruptedException ex) {
118 throw new IOException(ex);
123 public void initialize() throws IOException {
126 } catch (InterruptedException ex) {
127 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
130 } catch (Exception ex) {
131 if (ex instanceof IOException) {
132 throw (IOException)ex;
134 if (ex instanceof RuntimeException) {
135 throw (RuntimeException)ex;
137 throw new IOException(ex);
141 private HttpServer initServer(String path, boolean addClasses) throws IOException {
142 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
144 final ServerConfiguration conf = s.getServerConfiguration();
146 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
147 conf.addHttpHandler(new Classes(resources), "/classes/");
152 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
153 wait = new CountDownLatch(1);
154 server = initServer(".", true);
155 final ServerConfiguration conf = server.getServerConfiguration();
157 class DynamicResourceHandler extends HttpHandler {
158 private final InvocationContext ic;
159 public DynamicResourceHandler(InvocationContext ic) {
160 if (ic == null || ic.resources.isEmpty()) {
161 throw new NullPointerException();
164 for (Resource r : ic.resources) {
165 conf.addHttpHandler(this, r.httpPath);
169 public void close() {
170 conf.removeHttpHandler(this);
174 public void service(Request request, Response response) throws Exception {
175 for (Resource r : ic.resources) {
176 if (r.httpPath.equals(request.getRequestURI())) {
177 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
178 response.setContentType(r.httpType);
179 copyStream(r.httpContent, response.getOutputStream(), null);
185 conf.addHttpHandler(new Page(resources,
186 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
189 conf.addHttpHandler(new HttpHandler() {
191 List<InvocationContext> cases = new ArrayList<>();
192 DynamicResourceHandler prev;
194 public void service(Request request, Response response) throws Exception {
195 String id = request.getParameter("request");
196 String value = request.getParameter("result");
199 InvocationContext mi = null;
202 if (id != null && value != null) {
203 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
204 value = decodeURL(value);
205 int indx = Integer.parseInt(id);
206 cases.get(indx).result(value, null);
207 if (++indx < cases.size()) {
208 mi = cases.get(indx);
209 LOG.log(Level.INFO, "Re-executing case {0}", indx);
213 if (!cases.isEmpty()) {
214 LOG.info("Re-executing test cases");
230 response.getWriter().write("");
233 LOG.log(Level.INFO, "End of data reached. Exiting.");
237 if (!mi.resources.isEmpty()) {
238 prev = new DynamicResourceHandler(mi);
242 final String cn = mi.clazz.getName();
243 final String mn = mi.methodName;
244 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
245 response.getWriter().write("{"
246 + "className: '" + cn + "', "
247 + "methodName: '" + mn + "', "
248 + "request: " + caseNmbr
250 if (mi.html != null) {
251 response.getWriter().write(", html: '");
252 response.getWriter().write(encodeJSON(mi.html));
253 response.getWriter().write("'");
255 response.getWriter().write("}");
259 this.brwsr = launchServerAndBrwsr(server, "/execute");
262 private static String encodeJSON(String in) {
263 StringBuilder sb = new StringBuilder();
264 for (int i = 0; i < in.length(); i++) {
265 char ch = in.charAt(i);
266 if (ch < 32 || ch == '\'' || ch == '"') {
268 String hs = "0000" + Integer.toHexString(ch);
269 hs = hs.substring(hs.length() - 4);
275 return sb.toString();
279 public void shutdown() throws IOException {
282 int prev = methods.size();
284 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
287 } catch (InterruptedException ex) {
288 throw new IOException(ex);
290 if (prev == methods.size()) {
293 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
299 "Timeout, but tests got from {0} to {1}. Trying again.",
300 new Object[]{prev, methods.size()}
303 stopServerAndBrwsr(server, brwsr);
306 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
312 if (ch == '$' && params.length > 0) {
313 int cnt = is.read() - '0';
314 if (cnt == 'U' - '0') {
315 os.write(baseURL.getBytes("UTF-8"));
317 if (cnt >= 0 && cnt < params.length) {
318 os.write(params[cnt].getBytes("UTF-8"));
326 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
328 NetworkListener listener = server.getListeners().iterator().next();
329 int port = listener.getPort();
331 URI uri = new URI("http://localhost:" + port + page);
332 LOG.log(Level.INFO, "Showing {0}", uri);
335 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
336 System.getProperty("java.vm.name"),
337 System.getProperty("java.vm.vendor"),
338 System.getProperty("java.vm.version"),
340 java.awt.Desktop.getDesktop().browse(uri);
341 LOG.log(Level.INFO, "Desktop.browse successfully finished");
343 } catch (UnsupportedOperationException ex) {
344 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
345 LOG.log(Level.FINE, null, ex);
349 String cmdName = cmd == null ? "xdg-open" : cmd;
351 cmdName, uri.toString()
353 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
354 final Process process = Runtime.getRuntime().exec(cmdArr);
355 return new Object[] { process, null };
359 private static String decodeURL(String s) {
361 int pos = s.indexOf('%');
365 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
366 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
370 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
374 Process process = (Process)brwsr[0];
377 InputStream stdout = process.getInputStream();
378 InputStream stderr = process.getErrorStream();
379 drain("StdOut", stdout);
380 drain("StdErr", stderr);
384 res = process.waitFor();
385 } catch (InterruptedException ex) {
386 throw new IOException(ex);
388 LOG.log(Level.INFO, "Exit code: {0}", res);
390 deleteTree((File)brwsr[1]);
393 private static void drain(String name, InputStream is) throws IOException {
394 int av = is.available();
396 StringBuilder sb = new StringBuilder();
397 sb.append("v== ").append(name).append(" ==v\n");
399 sb.append((char)is.read());
401 sb.append("\n^== ").append(name).append(" ==^");
402 LOG.log(Level.INFO, sb.toString());
406 private void deleteTree(File file) {
410 File[] arr = file.listFiles();
420 public void close() throws IOException {
424 private class Res implements Bck2Brwsr.Resources {
426 public InputStream get(String resource) throws IOException {
427 for (ClassLoader l : loaders) {
429 Enumeration<URL> en = l.getResources(resource);
430 while (en.hasMoreElements()) {
431 u = en.nextElement();
434 return u.openStream();
437 throw new IOException("Can't find " + resource);
441 private static class Page extends HttpHandler {
442 private final String resource;
443 private final String[] args;
444 private final Res res;
446 public Page(Res res, String resource, String... args) {
448 this.resource = resource;
449 this.args = args.length == 0 ? new String[] { "$0" } : args;
453 public void service(Request request, Response response) throws Exception {
456 r = request.getHttpHandlerPath();
458 if (r.startsWith("/")) {
461 String[] replace = {};
462 if (r.endsWith(".html")) {
463 response.setContentType("text/html");
464 LOG.info("Content type text/html");
467 if (r.endsWith(".xhtml")) {
468 response.setContentType("application/xhtml+xml");
469 LOG.info("Content type application/xhtml+xml");
472 OutputStream os = response.getOutputStream();
473 try (InputStream is = res.get(r)) {
474 copyStream(is, os, request.getRequestURL().toString(), replace);
475 } catch (IOException ex) {
476 response.setDetailMessage(ex.getLocalizedMessage());
478 response.setStatus(404);
483 private static class VM extends HttpHandler {
484 private final String bck2brwsr;
486 public VM(Res loader) throws IOException {
487 StringBuilder sb = new StringBuilder();
488 Bck2Brwsr.generate(sb, loader);
490 "(function WrapperVM(global) {"
491 + " function ldCls(res) {\n"
492 + " var request = new XMLHttpRequest();\n"
493 + " request.open('GET', '/classes/' + res, false);\n"
494 + " request.send();\n"
495 + " if (request.status !== 200) return null;\n"
496 + " var arr = eval('(' + request.responseText + ')');\n"
499 + " var prevvm = global.bck2brwsr;\n"
500 + " global.bck2brwsr = function() {\n"
501 + " var args = Array.prototype.slice.apply(arguments);\n"
502 + " args.unshift(ldCls);\n"
503 + " return prevvm.apply(null, args);\n"
507 this.bck2brwsr = sb.toString();
511 public void service(Request request, Response response) throws Exception {
512 response.setCharacterEncoding("UTF-8");
513 response.setContentType("text/javascript");
514 response.getWriter().write(bck2brwsr);
518 private static class Classes extends HttpHandler {
519 private final Res loader;
521 public Classes(Res loader) {
522 this.loader = loader;
526 public void service(Request request, Response response) throws Exception {
527 String res = request.getHttpHandlerPath();
528 if (res.startsWith("/")) {
529 res = res.substring(1);
531 try (InputStream is = loader.get(res)) {
532 response.setContentType("text/javascript");
533 Writer w = response.getWriter();
535 for (int i = 0;; i++) {
549 w.append(Integer.toString(b));
552 } catch (IOException ex) {
553 response.setStatus(HttpStatus.NOT_FOUND_404);
555 response.setDetailMessage(ex.getMessage());