2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 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.Header;
65 import org.glassfish.grizzly.http.util.HttpStatus;
66 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
67 import org.glassfish.grizzly.websockets.WebSocket;
68 import org.glassfish.grizzly.websockets.WebSocketAddOn;
69 import org.glassfish.grizzly.websockets.WebSocketApplication;
70 import org.glassfish.grizzly.websockets.WebSocketEngine;
73 * Lightweight server to launch Bck2Brwsr applications and tests.
74 * Supports execution in native browser as well as Java's internal
77 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
78 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
79 private static final InvocationContext END = new InvocationContext(null, null, null);
80 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
81 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
83 private final Res resources = new Res();
84 private final String cmd;
85 private Object[] brwsr;
86 private HttpServer server;
87 private CountDownLatch wait;
89 public BaseHTTPLauncher(String cmd) {
91 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
96 InvocationContext runMethod(InvocationContext c) throws IOException {
97 loaders.add(c.clazz.getClassLoader());
101 } catch (InterruptedException ex) {
102 throw new IOException(ex);
107 public void setTimeout(long ms) {
111 public void addClassLoader(ClassLoader url) {
112 this.loaders.add(url);
115 ClassLoader[] loaders() {
116 return loaders.toArray(new ClassLoader[loaders.size()]);
119 public void showURL(String startpage) throws IOException {
120 if (!startpage.startsWith("/")) {
121 startpage = "/" + startpage;
123 HttpServer s = initServer(".", true, "");
124 int last = startpage.lastIndexOf('/');
125 String prefix = startpage.substring(0, last);
126 String simpleName = startpage.substring(last);
127 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
130 launchServerAndBrwsr(s, simpleName);
131 } catch (Exception ex) {
132 throw new IOException(ex);
136 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
137 if (!startpage.startsWith("/")) {
138 startpage = "/" + startpage;
140 String prefix = null;
141 if (!new File(dir, "bck2brwsr.js").exists()) {
142 int last = startpage.lastIndexOf('/');
144 prefix = startpage.substring(0, last);
147 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
149 launchServerAndBrwsr(s, startpage);
150 } catch (Exception ex) {
151 throw new IOException(ex);
156 public void initialize() throws IOException {
159 } catch (InterruptedException ex) {
160 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
163 } catch (Exception ex) {
164 if (ex instanceof IOException) {
165 throw (IOException)ex;
167 if (ex instanceof RuntimeException) {
168 throw (RuntimeException)ex;
170 throw new IOException(ex);
174 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
175 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
177 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
178 setPoolName("Fx/Bck2 Brwsr").
181 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
182 setPoolName("Kernel Fx/Bck2").
185 for (NetworkListener nl : s.getListeners()) {
186 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
187 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
190 final ServerConfiguration conf = s.getServerConfiguration();
191 VMAndPages vm = new VMAndPages();
192 conf.addHttpHandler(vm, "/");
193 if (vmPrefix != null) {
194 vm.registerVM(vmPrefix + "/bck2brwsr.js");
200 conf.addHttpHandler(new Classes(resources), "/classes/");
202 final WebSocketAddOn addon = new WebSocketAddOn();
203 for (NetworkListener listener : s.getListeners()) {
204 listener.registerAddOn(addon);
209 private static int resourcesCount;
210 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
211 wait = new CountDownLatch(1);
212 server = initServer(".", true, "");
213 final ServerConfiguration conf = server.getServerConfiguration();
215 class DynamicResourceHandler extends HttpHandler {
216 private final InvocationContext ic;
217 DynamicResourceHandler delegate;
218 public DynamicResourceHandler(InvocationContext ic) {
220 for (Resource r : ic.resources) {
221 conf.addHttpHandler(this, r.httpPath);
225 public void close(DynamicResourceHandler del) {
226 conf.removeHttpHandler(this);
231 public void service(Request request, Response response) throws Exception {
232 if (delegate != null) {
233 delegate.service(request, response);
237 if ("/dynamic".equals(request.getRequestURI())) {
238 boolean webSocket = false;
239 String mimeType = request.getParameter("mimeType");
240 List<String> params = new ArrayList<String>();
241 for (int i = 0; ; i++) {
242 String p = request.getParameter("param" + i);
247 if ("protocol:ws".equals(p)) {
251 final String cnt = request.getParameter("content");
252 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
253 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
255 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
257 url = registerWebSocket(res);
259 url = registerResource(res);
261 response.setHeader(Header.CacheControl, "no-cache");
262 response.setHeader(Header.Pragma, "no-cache");
263 response.getWriter().write(url.toString());
264 response.getWriter().write("\n");
268 for (Resource r : ic.resources) {
269 if (r.httpPath.equals(request.getRequestURI())) {
270 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
271 response.setContentType(r.httpType);
272 response.setHeader(Header.CacheControl, "no-cache");
273 response.setHeader(Header.Pragma, "no-cache");
274 r.httpContent.reset();
275 String[] params = null;
276 if (r.parameters.length != 0) {
277 params = new String[r.parameters.length];
278 for (int i = 0; i < r.parameters.length; i++) {
279 params[i] = request.getParameter(r.parameters[i]);
280 if (params[i] == null) {
281 if ("http.method".equals(r.parameters[i])) {
282 params[i] = request.getMethod().toString();
283 } else if ("http.requestBody".equals(r.parameters[i])) {
284 Reader rdr = request.getReader();
285 StringBuilder sb = new StringBuilder();
293 params[i] = sb.toString();
296 if (params[i] == null) {
302 copyStream(r.httpContent, response.getOutputStream(), null, params);
307 private URI registerWebSocket(Resource r) {
308 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
309 return pageURL("ws", server, r.httpPath);
312 private URI registerResource(Resource r) {
313 if (!ic.resources.contains(r)) {
315 conf.addHttpHandler(this, r.httpPath);
317 return pageURL("http", server, r.httpPath);
321 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
323 conf.addHttpHandler(new HttpHandler() {
325 List<InvocationContext> cases = new ArrayList<InvocationContext>();
326 DynamicResourceHandler prev;
328 public void service(Request request, Response response) throws Exception {
329 String id = request.getParameter("request");
330 String value = request.getParameter("result");
331 if (value != null && value.indexOf((char)0xC5) != -1) {
332 value = toUTF8(value);
336 InvocationContext mi = null;
339 if (id != null && value != null) {
340 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
341 value = decodeURL(value);
342 int indx = Integer.parseInt(id);
343 cases.get(indx).result(value, null);
344 if (++indx < cases.size()) {
345 mi = cases.get(indx);
346 LOG.log(Level.INFO, "Re-executing case {0}", indx);
350 if (!cases.isEmpty()) {
351 LOG.info("Re-executing test cases");
362 response.getWriter().write("");
365 LOG.log(Level.INFO, "End of data reached. Exiting.");
368 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
373 conf.addHttpHandler(prev, "/dynamic");
376 final String cn = mi.clazz.getName();
377 final String mn = mi.methodName;
378 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
379 response.getWriter().write("{"
380 + "className: '" + cn + "', "
381 + "methodName: '" + mn + "', "
382 + "request: " + caseNmbr
384 if (mi.html != null) {
385 response.getWriter().write(", html: '");
386 response.getWriter().write(encodeJSON(mi.html));
387 response.getWriter().write("'");
389 response.getWriter().write("}");
393 this.brwsr = launchServerAndBrwsr(server, "/execute");
396 private static String encodeJSON(String in) {
397 StringBuilder sb = new StringBuilder();
398 for (int i = 0; i < in.length(); i++) {
399 char ch = in.charAt(i);
400 if (ch < 32 || ch == '\'' || ch == '"') {
402 String hs = "0000" + Integer.toHexString(ch);
403 hs = hs.substring(hs.length() - 4);
409 return sb.toString();
413 public void shutdown() throws IOException {
416 int prev = methods.size();
418 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
421 } catch (InterruptedException ex) {
422 throw new IOException(ex);
424 if (prev == methods.size()) {
427 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
433 "Timeout, but tests got from {0} to {1}. Trying again.",
434 new Object[]{prev, methods.size()}
437 stopServerAndBrwsr(server, brwsr);
440 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
446 if (ch == '$' && params.length > 0) {
447 int cnt = is.read() - '0';
448 if (baseURL != null && cnt == 'U' - '0') {
449 os.write(baseURL.getBytes("UTF-8"));
451 if (cnt >= 0 && cnt < params.length) {
452 os.write(params[cnt].getBytes("UTF-8"));
464 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
466 URI uri = pageURL("http", server, page);
467 return showBrwsr(uri);
469 private static String toUTF8(String value) throws UnsupportedEncodingException {
470 byte[] arr = new byte[value.length()];
471 for (int i = 0; i < arr.length; i++) {
472 arr[i] = (byte)value.charAt(i);
474 return new String(arr, "UTF-8");
477 private static String decodeURL(String s) {
479 int pos = s.indexOf('%');
483 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
484 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
488 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
492 Process process = (Process)brwsr[0];
495 InputStream stdout = process.getInputStream();
496 InputStream stderr = process.getErrorStream();
497 drain("StdOut", stdout);
498 drain("StdErr", stderr);
502 res = process.waitFor();
503 } catch (InterruptedException ex) {
504 throw new IOException(ex);
506 LOG.log(Level.INFO, "Exit code: {0}", res);
508 deleteTree((File)brwsr[1]);
511 private static void drain(String name, InputStream is) throws IOException {
512 int av = is.available();
514 StringBuilder sb = new StringBuilder();
515 sb.append("v== ").append(name).append(" ==v\n");
517 sb.append((char)is.read());
519 sb.append("\n^== ").append(name).append(" ==^");
520 LOG.log(Level.INFO, sb.toString());
524 private void deleteTree(File file) {
528 File[] arr = file.listFiles();
538 public HttpServer call() throws Exception {
543 public void close() throws IOException {
547 protected Object[] showBrwsr(URI uri) throws IOException {
548 LOG.log(Level.INFO, "Showing {0}", uri);
551 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
552 System.getProperty("java.vm.name"),
553 System.getProperty("java.vm.vendor"),
554 System.getProperty("java.vm.version"),
556 java.awt.Desktop.getDesktop().browse(uri);
557 LOG.log(Level.INFO, "Desktop.browse successfully finished");
559 } catch (UnsupportedOperationException ex) {
560 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
561 LOG.log(Level.FINE, null, ex);
562 } catch (IOException ex) {
563 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
564 LOG.log(Level.FINE, null, ex);
568 String cmdName = cmd == null ? "xdg-open" : cmd;
570 cmdName, uri.toString()
572 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
573 final Process process = Runtime.getRuntime().exec(cmdArr);
574 return new Object[] { process, null };
578 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
579 abstract String harnessResource();
580 Object compileJar(URL jar, URL precompiled) throws IOException {
583 String compileFromClassPath(URL f, Res loader) throws IOException {
587 private static URI pageURL(String protocol, HttpServer server, final String page) {
588 NetworkListener listener = server.getListeners().iterator().next();
589 int port = listener.getPort();
591 return new URI(protocol + "://localhost:" + port + page);
592 } catch (URISyntaxException ex) {
593 throw new IllegalStateException(ex);
598 private final Set<URL> ignore = new HashSet<URL>();
600 Object compileJar(URL jarURL) throws IOException {
601 List<String[]> libraries = new ArrayList<String[]>();
602 for (ClassLoader loader : loaders) {
603 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
604 while (en.hasMoreElements()) {
605 URL e = en.nextElement();
606 Manifest mf = new Manifest(e.openStream());
607 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
608 String key = entrySet.getKey();
609 Attributes attr = entrySet.getValue();
611 final String a = attr.getValue("Bck2BrwsrArtifactId");
612 final String g = attr.getValue("Bck2BrwsrGroupId");
613 final String v = attr.getValue("Bck2BrwsrVersion");
614 final String d = attr.getValue("Bck2BrwsrDebug");
616 if (g != null && a != null && v != null && "true".equals(d)) {
617 libraries.add(new String[] {
624 URL precompiled = null;
625 for (ClassLoader loader : loaders) {
626 for (String[] lib : libraries) {
627 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
628 URL props = loader.getResource(res);
630 URLConnection c = props.openConnection();
631 Properties load = new Properties();
632 final InputStream is = c.getInputStream();
635 if (lib[2].equals(load.getProperty("version"))) {
636 if (c instanceof JarURLConnection) {
637 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
638 if (definedInURL.equals(jarURL)) {
639 precompiled = loader.getResource(lib[3]);
646 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
650 String compileFromClassPath(URL f) throws IOException {
651 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
653 public URL get(String resource, int skip) throws IOException {
654 if (!resource.endsWith(".class")) {
655 return getResource(resource, skip);
658 for (ClassLoader l : loaders) {
659 Enumeration<URL> en = l.getResources(resource);
660 while (en.hasMoreElements()) {
661 u = en.nextElement();
662 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
668 if (u.toExternalForm().contains("rt.jar")) {
669 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
674 throw new IOException("Can't find " + resource);
676 private URL getResource(String resource, int skip) throws IOException {
677 for (ClassLoader l : loaders) {
678 Enumeration<URL> en = l.getResources(resource);
679 while (en.hasMoreElements()) {
680 final URL now = en.nextElement();
681 if (now.toExternalForm().contains("sisu-inject-bean")) {
682 // certainly we don't want this resource, as that
683 // module is not compiled with target 1.6, currently
686 if (now.getProtocol().equals("jar")) {
687 JarURLConnection juc = (JarURLConnection) now.openConnection();
688 if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
697 throw new IOException("Not found (anymore of) " + resource);
701 private static class Page extends HttpHandler {
702 final String resource;
703 private final String[] args;
704 private final Res res;
706 public Page(Res res, String resource, String... args) {
708 this.resource = resource;
709 this.args = args.length == 0 ? new String[] { "$0" } : args;
713 public void service(Request request, Response response) throws Exception {
714 String r = computePage(request);
715 if (r.startsWith("/")) {
718 String[] replace = {};
719 if (r.endsWith(".html")) {
720 response.setContentType("text/html");
721 LOG.info("Content type text/html");
724 if (r.endsWith(".xhtml")) {
725 response.setContentType("application/xhtml+xml");
726 LOG.info("Content type application/xhtml+xml");
729 OutputStream os = response.getOutputStream();
731 InputStream is = res.get(r, 0).openStream();
732 copyStream(is, os, request.getRequestURL().toString(), replace);
733 } catch (IOException ex) {
734 response.setDetailMessage(ex.getLocalizedMessage());
736 response.setStatus(404);
740 protected String computePage(Request request) {
743 r = request.getHttpHandlerPath();
749 private static class SubTree extends Page {
751 public SubTree(Res res, String resource, String... args) {
752 super(res, resource, args);
756 protected String computePage(Request request) {
757 return resource + request.getHttpHandlerPath();
763 private class VMAndPages extends StaticHttpHandler {
764 private String vmResource;
766 public VMAndPages() {
767 super((String[]) null);
771 public void service(Request request, Response response) throws Exception {
772 if (request.getRequestURI().equals(vmResource)) {
773 response.setCharacterEncoding("UTF-8");
774 response.setContentType("text/javascript");
775 StringBuilder sb = new StringBuilder();
776 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
777 response.getWriter().write(sb.toString());
779 super.service(request, response);
783 private void registerVM(String vmResource) {
784 this.vmResource = vmResource;
788 private static class Classes extends HttpHandler {
789 private final Res loader;
791 public Classes(Res loader) {
792 this.loader = loader;
796 public void service(Request request, Response response) throws Exception {
797 String res = request.getHttpHandlerPath();
798 if (res.startsWith("/")) {
799 res = res.substring(1);
801 String skip = request.getParameter("skip");
802 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
803 URL url = loader.get(res, skipCnt);
804 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
805 response.setCharacterEncoding("UTF-8");
806 if (url.getProtocol().equals("jar")) {
807 JarURLConnection juc = (JarURLConnection) url.openConnection();
810 s = loader.compileJar(juc.getJarFileURL());
811 } catch (IOException iOException) {
812 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
814 if (s instanceof String) {
815 Writer w = response.getWriter();
820 if (s instanceof InputStream) {
821 copyStream((InputStream) s, response.getOutputStream(), null);
825 if (url.getProtocol().equals("file")) {
826 final String filePart = url.getFile();
827 if (filePart.endsWith(res)) {
832 filePart.substring(0, filePart.length() - res.length())
835 String s = loader.compileFromClassPath(url);
837 Writer w = response.getWriter();
843 } catch (IOException ex) {
844 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
846 InputStream is = null;
849 throw new IOException("Resource not found");
851 is = url.openStream();
852 response.setContentType("text/javascript");
853 Writer w = response.getWriter();
855 for (int i = 0;; i++) {
869 w.append(Integer.toString(b));
872 } catch (IOException ex) {
873 response.setStatus(HttpStatus.NOT_FOUND_404);
875 response.setDetailMessage(ex.getMessage());
884 private static class WS extends WebSocketApplication {
886 private final Resource r;
888 private WS(Resource r) {
893 public void onMessage(WebSocket socket, String text) {
895 r.httpContent.reset();
896 ByteArrayOutputStream out = new ByteArrayOutputStream();
897 copyStream(r.httpContent, out, null, text);
898 String s = new String(out.toByteArray(), "UTF-8");
900 } catch (IOException ex) {
901 LOG.log(Level.WARNING, null, ex);