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.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.Closeable;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InterruptedIOException;
27 import java.io.OutputStream;
28 import java.io.Reader;
29 import java.io.UnsupportedEncodingException;
30 import java.io.Writer;
31 import java.net.JarURLConnection;
33 import java.net.URISyntaxException;
35 import java.net.URLConnection;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Enumeration;
39 import java.util.HashSet;
40 import java.util.LinkedHashSet;
41 import java.util.List;
43 import java.util.Properties;
45 import java.util.concurrent.BlockingQueue;
46 import java.util.concurrent.Callable;
47 import java.util.concurrent.CountDownLatch;
48 import java.util.concurrent.LinkedBlockingQueue;
49 import java.util.concurrent.TimeUnit;
50 import java.util.jar.Attributes;
51 import java.util.jar.JarFile;
52 import java.util.jar.Manifest;
53 import java.util.logging.Level;
54 import java.util.logging.Logger;
55 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
56 import org.glassfish.grizzly.PortRange;
57 import org.glassfish.grizzly.http.server.HttpHandler;
58 import org.glassfish.grizzly.http.server.HttpServer;
59 import org.glassfish.grizzly.http.server.NetworkListener;
60 import org.glassfish.grizzly.http.server.Request;
61 import org.glassfish.grizzly.http.server.Response;
62 import org.glassfish.grizzly.http.server.ServerConfiguration;
63 import org.glassfish.grizzly.http.server.StaticHttpHandler;
64 import org.glassfish.grizzly.http.util.HttpStatus;
65 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
66 import org.glassfish.grizzly.websockets.WebSocket;
67 import org.glassfish.grizzly.websockets.WebSocketAddOn;
68 import org.glassfish.grizzly.websockets.WebSocketApplication;
69 import org.glassfish.grizzly.websockets.WebSocketEngine;
72 * Lightweight server to launch Bck2Brwsr applications and tests.
73 * Supports execution in native browser as well as Java's internal
76 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
77 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
78 private static final InvocationContext END = new InvocationContext(null, null, null);
79 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
80 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
82 private final Res resources = new Res();
83 private final String cmd;
84 private Object[] brwsr;
85 private HttpServer server;
86 private CountDownLatch wait;
88 public BaseHTTPLauncher(String cmd) {
90 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
95 InvocationContext runMethod(InvocationContext c) throws IOException {
96 loaders.add(c.clazz.getClassLoader());
100 } catch (InterruptedException ex) {
101 throw new IOException(ex);
106 public void setTimeout(long ms) {
110 public void addClassLoader(ClassLoader url) {
111 this.loaders.add(url);
114 ClassLoader[] loaders() {
115 return loaders.toArray(new ClassLoader[loaders.size()]);
118 public void showURL(String startpage) throws IOException {
119 if (!startpage.startsWith("/")) {
120 startpage = "/" + startpage;
122 HttpServer s = initServer(".", true, "");
123 int last = startpage.lastIndexOf('/');
124 String prefix = startpage.substring(0, last);
125 String simpleName = startpage.substring(last);
126 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
129 launchServerAndBrwsr(s, simpleName);
130 } catch (Exception ex) {
131 throw new IOException(ex);
135 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
136 if (!startpage.startsWith("/")) {
137 startpage = "/" + startpage;
139 String prefix = null;
140 if (!new File(dir, "bck2brwsr.js").exists()) {
141 int last = startpage.lastIndexOf('/');
143 prefix = startpage.substring(0, last);
146 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
148 launchServerAndBrwsr(s, startpage);
149 } catch (Exception ex) {
150 throw new IOException(ex);
155 public void initialize() throws IOException {
158 } catch (InterruptedException ex) {
159 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
162 } catch (Exception ex) {
163 if (ex instanceof IOException) {
164 throw (IOException)ex;
166 if (ex instanceof RuntimeException) {
167 throw (RuntimeException)ex;
169 throw new IOException(ex);
173 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
174 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
176 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
177 setPoolName("Fx/Bck2 Brwsr").
180 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
181 setPoolName("Kernel Fx/Bck2").
184 for (NetworkListener nl : s.getListeners()) {
185 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
186 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
189 final ServerConfiguration conf = s.getServerConfiguration();
190 VMAndPages vm = new VMAndPages();
191 conf.addHttpHandler(vm, "/");
192 if (vmPrefix != null) {
193 vm.registerVM(vmPrefix + "/bck2brwsr.js");
199 conf.addHttpHandler(new Classes(resources), "/classes/");
201 final WebSocketAddOn addon = new WebSocketAddOn();
202 for (NetworkListener listener : s.getListeners()) {
203 listener.registerAddOn(addon);
208 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
209 wait = new CountDownLatch(1);
210 server = initServer(".", true, "");
211 final ServerConfiguration conf = server.getServerConfiguration();
213 class DynamicResourceHandler extends HttpHandler {
214 private final InvocationContext ic;
215 private int resourcesCount;
216 DynamicResourceHandler delegate;
217 public DynamicResourceHandler(InvocationContext ic) {
219 for (Resource r : ic.resources) {
220 conf.addHttpHandler(this, r.httpPath);
224 public void close(DynamicResourceHandler del) {
225 conf.removeHttpHandler(this);
230 public void service(Request request, Response response) throws Exception {
231 if (delegate != null) {
232 delegate.service(request, response);
236 if ("/dynamic".equals(request.getRequestURI())) {
237 boolean webSocket = false;
238 String mimeType = request.getParameter("mimeType");
239 List<String> params = new ArrayList<String>();
240 for (int i = 0; ; i++) {
241 String p = request.getParameter("param" + i);
246 if ("protocol:ws".equals(p)) {
250 final String cnt = request.getParameter("content");
251 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
252 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
254 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
256 url = registerWebSocket(res);
258 url = registerResource(res);
260 response.getWriter().write(url.toString());
261 response.getWriter().write("\n");
265 for (Resource r : ic.resources) {
266 if (r.httpPath.equals(request.getRequestURI())) {
267 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
268 response.setContentType(r.httpType);
269 r.httpContent.reset();
270 String[] params = null;
271 if (r.parameters.length != 0) {
272 params = new String[r.parameters.length];
273 for (int i = 0; i < r.parameters.length; i++) {
274 params[i] = request.getParameter(r.parameters[i]);
275 if (params[i] == null) {
276 if ("http.method".equals(r.parameters[i])) {
277 params[i] = request.getMethod().toString();
278 } else if ("http.requestBody".equals(r.parameters[i])) {
279 Reader rdr = request.getReader();
280 StringBuilder sb = new StringBuilder();
288 params[i] = sb.toString();
291 if (params[i] == null) {
297 copyStream(r.httpContent, response.getOutputStream(), null, params);
302 private URI registerWebSocket(Resource r) {
303 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
304 return pageURL("ws", server, r.httpPath);
307 private URI registerResource(Resource r) {
308 if (!ic.resources.contains(r)) {
310 conf.addHttpHandler(this, r.httpPath);
312 return pageURL("http", server, r.httpPath);
316 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
318 conf.addHttpHandler(new HttpHandler() {
320 List<InvocationContext> cases = new ArrayList<InvocationContext>();
321 DynamicResourceHandler prev;
323 public void service(Request request, Response response) throws Exception {
324 String id = request.getParameter("request");
325 String value = request.getParameter("result");
326 if (value != null && value.indexOf((char)0xC5) != -1) {
327 value = toUTF8(value);
331 InvocationContext mi = null;
334 if (id != null && value != null) {
335 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
336 value = decodeURL(value);
337 int indx = Integer.parseInt(id);
338 cases.get(indx).result(value, null);
339 if (++indx < cases.size()) {
340 mi = cases.get(indx);
341 LOG.log(Level.INFO, "Re-executing case {0}", indx);
345 if (!cases.isEmpty()) {
346 LOG.info("Re-executing test cases");
357 response.getWriter().write("");
360 LOG.log(Level.INFO, "End of data reached. Exiting.");
363 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
368 conf.addHttpHandler(prev, "/dynamic");
371 final String cn = mi.clazz.getName();
372 final String mn = mi.methodName;
373 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
374 response.getWriter().write("{"
375 + "className: '" + cn + "', "
376 + "methodName: '" + mn + "', "
377 + "request: " + caseNmbr
379 if (mi.html != null) {
380 response.getWriter().write(", html: '");
381 response.getWriter().write(encodeJSON(mi.html));
382 response.getWriter().write("'");
384 response.getWriter().write("}");
388 this.brwsr = launchServerAndBrwsr(server, "/execute");
391 private static String encodeJSON(String in) {
392 StringBuilder sb = new StringBuilder();
393 for (int i = 0; i < in.length(); i++) {
394 char ch = in.charAt(i);
395 if (ch < 32 || ch == '\'' || ch == '"') {
397 String hs = "0000" + Integer.toHexString(ch);
398 hs = hs.substring(hs.length() - 4);
404 return sb.toString();
408 public void shutdown() throws IOException {
411 int prev = methods.size();
413 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
416 } catch (InterruptedException ex) {
417 throw new IOException(ex);
419 if (prev == methods.size()) {
422 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
428 "Timeout, but tests got from {0} to {1}. Trying again.",
429 new Object[]{prev, methods.size()}
432 stopServerAndBrwsr(server, brwsr);
435 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
441 if (ch == '$' && params.length > 0) {
442 int cnt = is.read() - '0';
443 if (baseURL != null && cnt == 'U' - '0') {
444 os.write(baseURL.getBytes("UTF-8"));
446 if (cnt >= 0 && cnt < params.length) {
447 os.write(params[cnt].getBytes("UTF-8"));
459 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
461 URI uri = pageURL("http", server, page);
462 return showBrwsr(uri);
464 private static String toUTF8(String value) throws UnsupportedEncodingException {
465 byte[] arr = new byte[value.length()];
466 for (int i = 0; i < arr.length; i++) {
467 arr[i] = (byte)value.charAt(i);
469 return new String(arr, "UTF-8");
472 private static String decodeURL(String s) {
474 int pos = s.indexOf('%');
478 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
479 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
483 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
487 Process process = (Process)brwsr[0];
490 InputStream stdout = process.getInputStream();
491 InputStream stderr = process.getErrorStream();
492 drain("StdOut", stdout);
493 drain("StdErr", stderr);
497 res = process.waitFor();
498 } catch (InterruptedException ex) {
499 throw new IOException(ex);
501 LOG.log(Level.INFO, "Exit code: {0}", res);
503 deleteTree((File)brwsr[1]);
506 private static void drain(String name, InputStream is) throws IOException {
507 int av = is.available();
509 StringBuilder sb = new StringBuilder();
510 sb.append("v== ").append(name).append(" ==v\n");
512 sb.append((char)is.read());
514 sb.append("\n^== ").append(name).append(" ==^");
515 LOG.log(Level.INFO, sb.toString());
519 private void deleteTree(File file) {
523 File[] arr = file.listFiles();
533 public HttpServer call() throws Exception {
538 public void close() throws IOException {
542 protected Object[] showBrwsr(URI uri) throws IOException {
543 LOG.log(Level.INFO, "Showing {0}", uri);
546 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
547 System.getProperty("java.vm.name"),
548 System.getProperty("java.vm.vendor"),
549 System.getProperty("java.vm.version"),
551 java.awt.Desktop.getDesktop().browse(uri);
552 LOG.log(Level.INFO, "Desktop.browse successfully finished");
554 } catch (UnsupportedOperationException ex) {
555 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
556 LOG.log(Level.FINE, null, ex);
557 } catch (IOException ex) {
558 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
559 LOG.log(Level.FINE, null, ex);
563 String cmdName = cmd == null ? "xdg-open" : cmd;
565 cmdName, uri.toString()
567 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
568 final Process process = Runtime.getRuntime().exec(cmdArr);
569 return new Object[] { process, null };
573 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
574 abstract String harnessResource();
575 Object compileJar(URL jar, URL precompiled) throws IOException {
578 String compileFromClassPath(URL f, Res loader) throws IOException {
582 private static URI pageURL(String protocol, HttpServer server, final String page) {
583 NetworkListener listener = server.getListeners().iterator().next();
584 int port = listener.getPort();
586 return new URI(protocol + "://localhost:" + port + page);
587 } catch (URISyntaxException ex) {
588 throw new IllegalStateException(ex);
593 private final Set<URL> ignore = new HashSet<URL>();
595 Object compileJar(URL jarURL) throws IOException {
596 List<String[]> libraries = new ArrayList<String[]>();
597 for (ClassLoader loader : loaders) {
598 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
599 while (en.hasMoreElements()) {
600 URL e = en.nextElement();
601 Manifest mf = new Manifest(e.openStream());
602 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
603 String key = entrySet.getKey();
604 Attributes attr = entrySet.getValue();
606 final String a = attr.getValue("Bck2BrwsrArtifactId");
607 final String g = attr.getValue("Bck2BrwsrGroupId");
608 final String v = attr.getValue("Bck2BrwsrVersion");
609 final String d = attr.getValue("Bck2BrwsrDebug");
611 if (g != null && a != null && v != null && "true".equals(d)) {
612 libraries.add(new String[] {
619 URL precompiled = null;
620 for (ClassLoader loader : loaders) {
621 for (String[] lib : libraries) {
622 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
623 URL props = loader.getResource(res);
625 URLConnection c = props.openConnection();
626 Properties load = new Properties();
627 final InputStream is = c.getInputStream();
630 if (lib[2].equals(load.getProperty("version"))) {
631 if (c instanceof JarURLConnection) {
632 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
633 if (definedInURL.equals(jarURL)) {
634 precompiled = loader.getResource(lib[3]);
641 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
645 String compileFromClassPath(URL f) throws IOException {
646 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
648 public URL get(String resource, int skip) throws IOException {
649 if (!resource.endsWith(".class")) {
650 return getResource(resource, skip);
653 for (ClassLoader l : loaders) {
654 Enumeration<URL> en = l.getResources(resource);
655 while (en.hasMoreElements()) {
656 u = en.nextElement();
657 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
663 if (u.toExternalForm().contains("rt.jar")) {
664 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
669 throw new IOException("Can't find " + resource);
671 private URL getResource(String resource, int skip) throws IOException {
672 for (ClassLoader l : loaders) {
673 Enumeration<URL> en = l.getResources(resource);
674 while (en.hasMoreElements()) {
675 final URL now = en.nextElement();
676 if (now.toExternalForm().contains("sisu-inject-bean")) {
677 // certainly we don't want this resource, as that
678 // module is not compiled with target 1.6, currently
681 if (now.getProtocol().equals("jar")) {
682 JarURLConnection juc = (JarURLConnection) now.openConnection();
683 if (ignore.contains(juc.getJarFileURL())) {
692 throw new IOException("Not found (anymore of) " + resource);
696 private static class Page extends HttpHandler {
697 final String resource;
698 private final String[] args;
699 private final Res res;
701 public Page(Res res, String resource, String... args) {
703 this.resource = resource;
704 this.args = args.length == 0 ? new String[] { "$0" } : args;
708 public void service(Request request, Response response) throws Exception {
709 String r = computePage(request);
710 if (r.startsWith("/")) {
713 String[] replace = {};
714 if (r.endsWith(".html")) {
715 response.setContentType("text/html");
716 LOG.info("Content type text/html");
719 if (r.endsWith(".xhtml")) {
720 response.setContentType("application/xhtml+xml");
721 LOG.info("Content type application/xhtml+xml");
724 OutputStream os = response.getOutputStream();
726 InputStream is = res.get(r, 0).openStream();
727 copyStream(is, os, request.getRequestURL().toString(), replace);
728 } catch (IOException ex) {
729 response.setDetailMessage(ex.getLocalizedMessage());
731 response.setStatus(404);
735 protected String computePage(Request request) {
738 r = request.getHttpHandlerPath();
744 private static class SubTree extends Page {
746 public SubTree(Res res, String resource, String... args) {
747 super(res, resource, args);
751 protected String computePage(Request request) {
752 return resource + request.getHttpHandlerPath();
758 private class VMAndPages extends StaticHttpHandler {
759 private String vmResource;
761 public VMAndPages() {
762 super((String[]) null);
766 public void service(Request request, Response response) throws Exception {
767 if (request.getRequestURI().equals(vmResource)) {
768 response.setCharacterEncoding("UTF-8");
769 response.setContentType("text/javascript");
770 StringBuilder sb = new StringBuilder();
771 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
772 response.getWriter().write(sb.toString());
774 super.service(request, response);
778 private void registerVM(String vmResource) {
779 this.vmResource = vmResource;
783 private static class Classes extends HttpHandler {
784 private final Res loader;
786 public Classes(Res loader) {
787 this.loader = loader;
791 public void service(Request request, Response response) throws Exception {
792 String res = request.getHttpHandlerPath();
793 if (res.startsWith("/")) {
794 res = res.substring(1);
796 String skip = request.getParameter("skip");
797 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
798 URL url = loader.get(res, skipCnt);
799 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
800 response.setCharacterEncoding("UTF-8");
801 if (url.getProtocol().equals("jar")) {
802 JarURLConnection juc = (JarURLConnection) url.openConnection();
805 s = loader.compileJar(juc.getJarFileURL());
806 } catch (IOException iOException) {
807 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
809 if (s instanceof String) {
810 Writer w = response.getWriter();
815 if (s instanceof InputStream) {
816 copyStream((InputStream) s, response.getOutputStream(), null);
820 if (url.getProtocol().equals("file")) {
821 final String filePart = url.getFile();
822 if (filePart.endsWith(res)) {
827 filePart.substring(0, filePart.length() - res.length())
830 String s = loader.compileFromClassPath(url);
832 Writer w = response.getWriter();
838 } catch (IOException ex) {
839 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
841 InputStream is = null;
844 throw new IOException("Resource not found");
846 is = url.openStream();
847 response.setContentType("text/javascript");
848 Writer w = response.getWriter();
850 for (int i = 0;; i++) {
864 w.append(Integer.toString(b));
867 } catch (IOException ex) {
868 response.setStatus(HttpStatus.NOT_FOUND_404);
870 response.setDetailMessage(ex.getMessage());
879 private static class WS extends WebSocketApplication {
881 private final Resource r;
883 private WS(Resource r) {
888 public void onMessage(WebSocket socket, String text) {
890 r.httpContent.reset();
891 ByteArrayOutputStream out = new ByteArrayOutputStream();
892 copyStream(r.httpContent, out, null, text);
893 String s = new String(out.toByteArray(), "UTF-8");
895 } catch (IOException ex) {
896 LOG.log(Level.WARNING, null, ex);