launcher/http/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java
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.UnsupportedEncodingException;
27 import java.io.Writer;
29 import java.net.URISyntaxException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Enumeration;
34 import java.util.LinkedHashSet;
35 import java.util.List;
37 import java.util.concurrent.BlockingQueue;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.CountDownLatch;
40 import java.util.concurrent.LinkedBlockingQueue;
41 import java.util.concurrent.TimeUnit;
42 import java.util.logging.Level;
43 import java.util.logging.Logger;
44 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
45 import org.apidesign.vm4brwsr.Bck2Brwsr;
46 import org.glassfish.grizzly.PortRange;
47 import org.glassfish.grizzly.http.server.HttpHandler;
48 import org.glassfish.grizzly.http.server.HttpServer;
49 import org.glassfish.grizzly.http.server.NetworkListener;
50 import org.glassfish.grizzly.http.server.Request;
51 import org.glassfish.grizzly.http.server.Response;
52 import org.glassfish.grizzly.http.server.ServerConfiguration;
53 import org.glassfish.grizzly.http.util.HttpStatus;
56 * Lightweight server to launch Bck2Brwsr applications and tests.
57 * Supports execution in native browser as well as Java's internal
60 final class Bck2BrwsrLauncher extends Launcher implements Closeable, Callable<HttpServer> {
61 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
62 private static final InvocationContext END = new InvocationContext(null, null, null);
63 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
64 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
66 private final Res resources = new Res();
67 private final String cmd;
68 private Object[] brwsr;
69 private HttpServer server;
70 private CountDownLatch wait;
72 public Bck2BrwsrLauncher(String cmd) {
74 addClassLoader(Bck2Brwsr.class.getClassLoader());
79 InvocationContext runMethod(InvocationContext c) throws IOException {
80 loaders.add(c.clazz.getClassLoader());
84 } catch (InterruptedException ex) {
85 throw new IOException(ex);
90 public void setTimeout(long ms) {
94 public void addClassLoader(ClassLoader url) {
95 this.loaders.add(url);
98 public void showURL(String startpage) throws IOException {
99 if (!startpage.startsWith("/")) {
100 startpage = "/" + startpage;
102 HttpServer s = initServer(".", true);
103 int last = startpage.lastIndexOf('/');
104 String prefix = startpage.substring(0, last);
105 String simpleName = startpage.substring(last);
106 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
109 launchServerAndBrwsr(s, simpleName);
110 } catch (URISyntaxException | InterruptedException ex) {
111 throw new IOException(ex);
115 void showDirectory(File dir, String startpage) throws IOException {
116 if (!startpage.startsWith("/")) {
117 startpage = "/" + startpage;
119 HttpServer s = initServer(dir.getPath(), false);
121 launchServerAndBrwsr(s, startpage);
122 } catch (URISyntaxException | InterruptedException ex) {
123 throw new IOException(ex);
128 public void initialize() throws IOException {
131 } catch (InterruptedException ex) {
132 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
135 } catch (Exception ex) {
136 if (ex instanceof IOException) {
137 throw (IOException)ex;
139 if (ex instanceof RuntimeException) {
140 throw (RuntimeException)ex;
142 throw new IOException(ex);
146 private HttpServer initServer(String path, boolean addClasses) throws IOException {
147 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
149 final ServerConfiguration conf = s.getServerConfiguration();
151 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
152 conf.addHttpHandler(new Classes(resources), "/classes/");
157 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
158 wait = new CountDownLatch(1);
159 server = initServer(".", true);
160 final ServerConfiguration conf = server.getServerConfiguration();
162 class DynamicResourceHandler extends HttpHandler {
163 private final InvocationContext ic;
164 public DynamicResourceHandler(InvocationContext ic) {
165 if (ic == null || ic.resources.isEmpty()) {
166 throw new NullPointerException();
169 for (Resource r : ic.resources) {
170 conf.addHttpHandler(this, r.httpPath);
174 public void close() {
175 conf.removeHttpHandler(this);
179 public void service(Request request, Response response) throws Exception {
180 for (Resource r : ic.resources) {
181 if (r.httpPath.equals(request.getRequestURI())) {
182 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
183 response.setContentType(r.httpType);
184 r.httpContent.reset();
185 String[] params = null;
186 if (r.parameters.length != 0) {
187 params = new String[r.parameters.length];
188 for (int i = 0; i < r.parameters.length; i++) {
189 params[i] = request.getParameter(r.parameters[i]);
193 copyStream(r.httpContent, response.getOutputStream(), null, params);
199 conf.addHttpHandler(new Page(resources,
200 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
203 conf.addHttpHandler(new HttpHandler() {
205 List<InvocationContext> cases = new ArrayList<>();
206 DynamicResourceHandler prev;
208 public void service(Request request, Response response) throws Exception {
209 String id = request.getParameter("request");
210 String value = request.getParameter("result");
213 InvocationContext mi = null;
216 if (id != null && value != null) {
217 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
218 value = decodeURL(value);
219 int indx = Integer.parseInt(id);
220 cases.get(indx).result(value, null);
221 if (++indx < cases.size()) {
222 mi = cases.get(indx);
223 LOG.log(Level.INFO, "Re-executing case {0}", indx);
227 if (!cases.isEmpty()) {
228 LOG.info("Re-executing test cases");
244 response.getWriter().write("");
247 LOG.log(Level.INFO, "End of data reached. Exiting.");
251 if (!mi.resources.isEmpty()) {
252 prev = new DynamicResourceHandler(mi);
256 final String cn = mi.clazz.getName();
257 final String mn = mi.methodName;
258 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
259 response.getWriter().write("{"
260 + "className: '" + cn + "', "
261 + "methodName: '" + mn + "', "
262 + "request: " + caseNmbr
264 if (mi.html != null) {
265 response.getWriter().write(", html: '");
266 response.getWriter().write(encodeJSON(mi.html));
267 response.getWriter().write("'");
269 response.getWriter().write("}");
273 this.brwsr = launchServerAndBrwsr(server, "/execute");
276 private static String encodeJSON(String in) {
277 StringBuilder sb = new StringBuilder();
278 for (int i = 0; i < in.length(); i++) {
279 char ch = in.charAt(i);
280 if (ch < 32 || ch == '\'' || ch == '"') {
282 String hs = "0000" + Integer.toHexString(ch);
283 hs = hs.substring(hs.length() - 4);
289 return sb.toString();
293 public void shutdown() throws IOException {
296 int prev = methods.size();
298 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
301 } catch (InterruptedException ex) {
302 throw new IOException(ex);
304 if (prev == methods.size()) {
307 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
313 "Timeout, but tests got from {0} to {1}. Trying again.",
314 new Object[]{prev, methods.size()}
317 stopServerAndBrwsr(server, brwsr);
320 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
326 if (ch == '$' && params.length > 0) {
327 int cnt = is.read() - '0';
328 if (baseURL != null && cnt == 'U' - '0') {
329 os.write(baseURL.getBytes("UTF-8"));
331 if (cnt >= 0 && cnt < params.length) {
332 os.write(params[cnt].getBytes("UTF-8"));
344 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
346 NetworkListener listener = server.getListeners().iterator().next();
347 int port = listener.getPort();
349 URI uri = new URI("http://localhost:" + port + page);
350 LOG.log(Level.INFO, "Showing {0}", uri);
353 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
354 System.getProperty("java.vm.name"),
355 System.getProperty("java.vm.vendor"),
356 System.getProperty("java.vm.version"),
358 java.awt.Desktop.getDesktop().browse(uri);
359 LOG.log(Level.INFO, "Desktop.browse successfully finished");
361 } catch (UnsupportedOperationException ex) {
362 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
363 LOG.log(Level.FINE, null, ex);
367 String cmdName = cmd == null ? "xdg-open" : cmd;
369 cmdName, uri.toString()
371 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
372 final Process process = Runtime.getRuntime().exec(cmdArr);
373 return new Object[] { process, null };
377 private static String decodeURL(String s) {
379 int pos = s.indexOf('%');
383 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
384 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
388 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
392 Process process = (Process)brwsr[0];
395 InputStream stdout = process.getInputStream();
396 InputStream stderr = process.getErrorStream();
397 drain("StdOut", stdout);
398 drain("StdErr", stderr);
402 res = process.waitFor();
403 } catch (InterruptedException ex) {
404 throw new IOException(ex);
406 LOG.log(Level.INFO, "Exit code: {0}", res);
408 deleteTree((File)brwsr[1]);
411 private static void drain(String name, InputStream is) throws IOException {
412 int av = is.available();
414 StringBuilder sb = new StringBuilder();
415 sb.append("v== ").append(name).append(" ==v\n");
417 sb.append((char)is.read());
419 sb.append("\n^== ").append(name).append(" ==^");
420 LOG.log(Level.INFO, sb.toString());
424 private void deleteTree(File file) {
428 File[] arr = file.listFiles();
438 public HttpServer call() throws Exception {
443 public void close() throws IOException {
447 private class Res implements Bck2Brwsr.Resources {
449 public InputStream get(String resource) throws IOException {
451 for (ClassLoader l : loaders) {
452 Enumeration<URL> en = l.getResources(resource);
453 while (en.hasMoreElements()) {
454 u = en.nextElement();
458 return u.openStream();
460 throw new IOException("Can't find " + resource);
464 private static class Page extends HttpHandler {
465 final String resource;
466 private final String[] args;
467 private final Res res;
469 public Page(Res res, String resource, String... args) {
471 this.resource = resource;
472 this.args = args.length == 0 ? new String[] { "$0" } : args;
476 public void service(Request request, Response response) throws Exception {
477 String r = computePage(request);
478 if (r.startsWith("/")) {
481 String[] replace = {};
482 if (r.endsWith(".html")) {
483 response.setContentType("text/html");
484 LOG.info("Content type text/html");
487 if (r.endsWith(".xhtml")) {
488 response.setContentType("application/xhtml+xml");
489 LOG.info("Content type application/xhtml+xml");
492 OutputStream os = response.getOutputStream();
493 try (InputStream is = res.get(r)) {
494 copyStream(is, os, request.getRequestURL().toString(), replace);
495 } catch (IOException ex) {
496 response.setDetailMessage(ex.getLocalizedMessage());
498 response.setStatus(404);
502 protected String computePage(Request request) {
505 r = request.getHttpHandlerPath();
511 private static class SubTree extends Page {
513 public SubTree(Res res, String resource, String... args) {
514 super(res, resource, args);
518 protected String computePage(Request request) {
519 return resource + request.getHttpHandlerPath();
525 private static class VM extends HttpHandler {
526 private final String bck2brwsr;
528 public VM(Res loader) throws IOException {
529 StringBuilder sb = new StringBuilder();
530 Bck2Brwsr.generate(sb, loader);
532 "(function WrapperVM(global) {"
533 + " function ldCls(res) {\n"
534 + " var request = new XMLHttpRequest();\n"
535 + " request.open('GET', '/classes/' + res, false);\n"
536 + " request.send();\n"
537 + " if (request.status !== 200) return null;\n"
538 + " var arr = eval('(' + request.responseText + ')');\n"
541 + " var prevvm = global.bck2brwsr;\n"
542 + " global.bck2brwsr = function() {\n"
543 + " var args = Array.prototype.slice.apply(arguments);\n"
544 + " args.unshift(ldCls);\n"
545 + " return prevvm.apply(null, args);\n"
549 this.bck2brwsr = sb.toString();
553 public void service(Request request, Response response) throws Exception {
554 response.setCharacterEncoding("UTF-8");
555 response.setContentType("text/javascript");
556 response.getWriter().write(bck2brwsr);
560 private static class Classes extends HttpHandler {
561 private final Res loader;
563 public Classes(Res loader) {
564 this.loader = loader;
568 public void service(Request request, Response response) throws Exception {
569 String res = request.getHttpHandlerPath();
570 if (res.startsWith("/")) {
571 res = res.substring(1);
573 try (InputStream is = loader.get(res)) {
574 response.setContentType("text/javascript");
575 Writer w = response.getWriter();
577 for (int i = 0;; i++) {
591 w.append(Integer.toString(b));
594 } catch (IOException ex) {
595 response.setStatus(HttpStatus.NOT_FOUND_404);
597 response.setDetailMessage(ex.getMessage());