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 int last = startpage.lastIndexOf('/');
99 String simpleName = startpage.substring(last);
100 s.getServerConfiguration().addHttpHandler(new Page(resources, startpage), simpleName);
101 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
103 launchServerAndBrwsr(s, simpleName);
104 } catch (URISyntaxException | InterruptedException ex) {
105 throw new IOException(ex);
109 void showDirectory(File dir, String startpage) throws IOException {
110 if (!startpage.startsWith("/")) {
111 startpage = "/" + startpage;
113 HttpServer s = initServer(dir.getPath(), false);
115 launchServerAndBrwsr(s, startpage);
116 } catch (URISyntaxException | InterruptedException ex) {
117 throw new IOException(ex);
122 public void initialize() throws IOException {
125 } catch (InterruptedException ex) {
126 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
129 } catch (Exception ex) {
130 if (ex instanceof IOException) {
131 throw (IOException)ex;
133 if (ex instanceof RuntimeException) {
134 throw (RuntimeException)ex;
136 throw new IOException(ex);
140 private HttpServer initServer(String path, boolean addClasses) throws IOException {
141 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
143 final ServerConfiguration conf = s.getServerConfiguration();
145 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
146 conf.addHttpHandler(new Classes(resources), "/classes/");
151 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
152 wait = new CountDownLatch(1);
153 server = initServer(".", true);
154 final ServerConfiguration conf = server.getServerConfiguration();
156 class DynamicResourceHandler extends HttpHandler {
157 private final InvocationContext ic;
158 public DynamicResourceHandler(InvocationContext ic) {
159 if (ic == null || ic.resources.isEmpty()) {
160 throw new NullPointerException();
163 for (Resource r : ic.resources) {
164 conf.addHttpHandler(this, r.httpPath);
168 public void close() {
169 conf.removeHttpHandler(this);
173 public void service(Request request, Response response) throws Exception {
174 for (Resource r : ic.resources) {
175 if (r.httpPath.equals(request.getRequestURI())) {
176 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
177 response.setContentType(r.httpType);
178 copyStream(r.httpContent, response.getOutputStream(), null);
184 conf.addHttpHandler(new Page(resources,
185 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
188 conf.addHttpHandler(new HttpHandler() {
190 List<InvocationContext> cases = new ArrayList<>();
191 DynamicResourceHandler prev;
193 public void service(Request request, Response response) throws Exception {
194 String id = request.getParameter("request");
195 String value = request.getParameter("result");
198 InvocationContext mi = null;
201 if (id != null && value != null) {
202 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
203 value = decodeURL(value);
204 int indx = Integer.parseInt(id);
205 cases.get(indx).result(value, null);
206 if (++indx < cases.size()) {
207 mi = cases.get(indx);
208 LOG.log(Level.INFO, "Re-executing case {0}", indx);
212 if (!cases.isEmpty()) {
213 LOG.info("Re-executing test cases");
229 response.getWriter().write("");
232 LOG.log(Level.INFO, "End of data reached. Exiting.");
236 if (!mi.resources.isEmpty()) {
237 prev = new DynamicResourceHandler(mi);
241 final String cn = mi.clazz.getName();
242 final String mn = mi.methodName;
243 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
244 response.getWriter().write("{"
245 + "className: '" + cn + "', "
246 + "methodName: '" + mn + "', "
247 + "request: " + caseNmbr
249 if (mi.html != null) {
250 response.getWriter().write(", html: '");
251 response.getWriter().write(encodeJSON(mi.html));
252 response.getWriter().write("'");
254 response.getWriter().write("}");
258 this.brwsr = launchServerAndBrwsr(server, "/execute");
261 private static String encodeJSON(String in) {
262 StringBuilder sb = new StringBuilder();
263 for (int i = 0; i < in.length(); i++) {
264 char ch = in.charAt(i);
265 if (ch < 32 || ch == '\'' || ch == '"') {
267 String hs = "0000" + Integer.toHexString(ch);
268 hs = hs.substring(hs.length() - 4);
274 return sb.toString();
278 public void shutdown() throws IOException {
281 int prev = methods.size();
283 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
286 } catch (InterruptedException ex) {
287 throw new IOException(ex);
289 if (prev == methods.size()) {
292 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
298 "Timeout, but tests got from {0} to {1}. Trying again.",
299 new Object[]{prev, methods.size()}
302 stopServerAndBrwsr(server, brwsr);
305 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
311 if (ch == '$' && params.length > 0) {
312 int cnt = is.read() - '0';
313 if (cnt == 'U' - '0') {
314 os.write(baseURL.getBytes());
316 if (cnt >= 0 && cnt < params.length) {
317 os.write(params[cnt].getBytes());
325 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
327 NetworkListener listener = server.getListeners().iterator().next();
328 int port = listener.getPort();
330 URI uri = new URI("http://localhost:" + port + page);
331 LOG.log(Level.INFO, "Showing {0}", uri);
334 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
335 System.getProperty("java.vm.name"),
336 System.getProperty("java.vm.vendor"),
337 System.getProperty("java.vm.version"),
339 java.awt.Desktop.getDesktop().browse(uri);
340 LOG.log(Level.INFO, "Desktop.browse successfully finished");
342 } catch (UnsupportedOperationException ex) {
343 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
344 LOG.log(Level.FINE, null, ex);
348 String cmdName = cmd == null ? "xdg-open" : cmd;
350 cmdName, uri.toString()
352 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
353 final Process process = Runtime.getRuntime().exec(cmdArr);
354 return new Object[] { process, null };
358 private static String decodeURL(String s) {
360 int pos = s.indexOf('%');
364 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
365 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
369 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
373 Process process = (Process)brwsr[0];
376 InputStream stdout = process.getInputStream();
377 InputStream stderr = process.getErrorStream();
378 drain("StdOut", stdout);
379 drain("StdErr", stderr);
383 res = process.waitFor();
384 } catch (InterruptedException ex) {
385 throw new IOException(ex);
387 LOG.log(Level.INFO, "Exit code: {0}", res);
389 deleteTree((File)brwsr[1]);
392 private static void drain(String name, InputStream is) throws IOException {
393 int av = is.available();
395 StringBuilder sb = new StringBuilder();
396 sb.append("v== ").append(name).append(" ==v\n");
398 sb.append((char)is.read());
400 sb.append("\n^== ").append(name).append(" ==^");
401 LOG.log(Level.INFO, sb.toString());
405 private void deleteTree(File file) {
409 File[] arr = file.listFiles();
419 public void close() throws IOException {
423 private class Res implements Bck2Brwsr.Resources {
425 public InputStream get(String resource) throws IOException {
426 for (ClassLoader l : loaders) {
428 Enumeration<URL> en = l.getResources(resource);
429 while (en.hasMoreElements()) {
430 u = en.nextElement();
433 return u.openStream();
436 throw new IOException("Can't find " + resource);
440 private static class Page extends HttpHandler {
441 private final String resource;
442 private final String[] args;
443 private final Res res;
445 public Page(Res res, String resource, String... args) {
447 this.resource = resource;
448 this.args = args.length == 0 ? new String[] { "$0" } : args;
452 public void service(Request request, Response response) throws Exception {
455 r = request.getHttpHandlerPath();
457 if (r.startsWith("/")) {
460 String[] replace = {};
461 if (r.endsWith(".html")) {
462 response.setContentType("text/html");
463 LOG.info("Content type text/html");
466 if (r.endsWith(".xhtml")) {
467 response.setContentType("application/xhtml+xml");
468 LOG.info("Content type application/xhtml+xml");
471 OutputStream os = response.getOutputStream();
472 try (InputStream is = res.get(r)) {
473 copyStream(is, os, request.getRequestURL().toString(), replace);
474 } catch (IOException ex) {
475 response.setDetailMessage(ex.getLocalizedMessage());
477 response.setStatus(404);
482 private static class VM extends HttpHandler {
483 private final String bck2brwsr;
485 public VM(Res loader) throws IOException {
486 StringBuilder sb = new StringBuilder();
487 Bck2Brwsr.generate(sb, loader);
489 "(function WrapperVM(global) {"
490 + " function ldCls(res) {\n"
491 + " var request = new XMLHttpRequest();\n"
492 + " request.open('GET', '/classes/' + res, false);\n"
493 + " request.send();\n"
494 + " var arr = eval('(' + request.responseText + ')');\n"
497 + " var prevvm = global.bck2brwsr;\n"
498 + " global.bck2brwsr = function() {\n"
499 + " return prevvm(ldCls);\n"
503 this.bck2brwsr = sb.toString();
507 public void service(Request request, Response response) throws Exception {
508 response.setCharacterEncoding("UTF-8");
509 response.setContentType("text/javascript");
510 response.getWriter().write(bck2brwsr);
514 private static class Classes extends HttpHandler {
515 private final Res loader;
517 public Classes(Res loader) {
518 this.loader = loader;
522 public void service(Request request, Response response) throws Exception {
523 String res = request.getHttpHandlerPath();
524 if (res.startsWith("/")) {
525 res = res.substring(1);
527 try (InputStream is = loader.get(res)) {
528 response.setContentType("text/javascript");
529 Writer w = response.getWriter();
531 for (int i = 0;; i++) {
545 w.append(Integer.toString(b));
548 } catch (IOException ex) {
550 response.setDetailMessage(ex.getMessage());