Directly derive the parent root folder based on resource name rather than going through classpath
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.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Enumeration;
38 import java.util.HashSet;
39 import java.util.LinkedHashSet;
40 import java.util.List;
42 import java.util.concurrent.BlockingQueue;
43 import java.util.concurrent.Callable;
44 import java.util.concurrent.CountDownLatch;
45 import java.util.concurrent.LinkedBlockingQueue;
46 import java.util.concurrent.TimeUnit;
47 import java.util.jar.JarFile;
48 import java.util.logging.Level;
49 import java.util.logging.Logger;
50 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
51 import org.glassfish.grizzly.PortRange;
52 import org.glassfish.grizzly.http.server.HttpHandler;
53 import org.glassfish.grizzly.http.server.HttpServer;
54 import org.glassfish.grizzly.http.server.NetworkListener;
55 import org.glassfish.grizzly.http.server.Request;
56 import org.glassfish.grizzly.http.server.Response;
57 import org.glassfish.grizzly.http.server.ServerConfiguration;
58 import org.glassfish.grizzly.http.server.StaticHttpHandler;
59 import org.glassfish.grizzly.http.util.HttpStatus;
60 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
61 import org.glassfish.grizzly.websockets.WebSocket;
62 import org.glassfish.grizzly.websockets.WebSocketAddOn;
63 import org.glassfish.grizzly.websockets.WebSocketApplication;
64 import org.glassfish.grizzly.websockets.WebSocketEngine;
67 * Lightweight server to launch Bck2Brwsr applications and tests.
68 * Supports execution in native browser as well as Java's internal
71 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
72 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
73 private static final InvocationContext END = new InvocationContext(null, null, null);
74 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
75 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
77 private final Res resources = new Res();
78 private final String cmd;
79 private Object[] brwsr;
80 private HttpServer server;
81 private CountDownLatch wait;
83 public BaseHTTPLauncher(String cmd) {
85 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
90 InvocationContext runMethod(InvocationContext c) throws IOException {
91 loaders.add(c.clazz.getClassLoader());
95 } catch (InterruptedException ex) {
96 throw new IOException(ex);
101 public void setTimeout(long ms) {
105 public void addClassLoader(ClassLoader url) {
106 this.loaders.add(url);
109 ClassLoader[] loaders() {
110 return loaders.toArray(new ClassLoader[loaders.size()]);
113 public void showURL(String startpage) throws IOException {
114 if (!startpage.startsWith("/")) {
115 startpage = "/" + startpage;
117 HttpServer s = initServer(".", true, "");
118 int last = startpage.lastIndexOf('/');
119 String prefix = startpage.substring(0, last);
120 String simpleName = startpage.substring(last);
121 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
124 launchServerAndBrwsr(s, simpleName);
125 } catch (Exception ex) {
126 throw new IOException(ex);
130 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
131 if (!startpage.startsWith("/")) {
132 startpage = "/" + startpage;
135 int last = startpage.lastIndexOf('/');
137 prefix = startpage.substring(0, last);
139 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
141 launchServerAndBrwsr(s, startpage);
142 } catch (Exception ex) {
143 throw new IOException(ex);
148 public void initialize() throws IOException {
151 } catch (InterruptedException ex) {
152 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
155 } catch (Exception ex) {
156 if (ex instanceof IOException) {
157 throw (IOException)ex;
159 if (ex instanceof RuntimeException) {
160 throw (RuntimeException)ex;
162 throw new IOException(ex);
166 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
167 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
169 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
170 setPoolName("Fx/Bck2 Brwsr").
173 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
174 setPoolName("Kernel Fx/Bck2").
177 for (NetworkListener nl : s.getListeners()) {
178 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
179 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
182 final ServerConfiguration conf = s.getServerConfiguration();
183 VMAndPages vm = new VMAndPages();
184 conf.addHttpHandler(vm, "/");
185 if (vmPrefix != null) {
186 vm.registerVM(vmPrefix + "/bck2brwsr.js");
192 conf.addHttpHandler(new Classes(resources), "/classes/");
194 final WebSocketAddOn addon = new WebSocketAddOn();
195 for (NetworkListener listener : s.getListeners()) {
196 listener.registerAddOn(addon);
201 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
202 wait = new CountDownLatch(1);
203 server = initServer(".", true, "");
204 final ServerConfiguration conf = server.getServerConfiguration();
206 class DynamicResourceHandler extends HttpHandler {
207 private final InvocationContext ic;
208 private int resourcesCount;
209 DynamicResourceHandler delegate;
210 public DynamicResourceHandler(InvocationContext ic) {
212 for (Resource r : ic.resources) {
213 conf.addHttpHandler(this, r.httpPath);
217 public void close(DynamicResourceHandler del) {
218 conf.removeHttpHandler(this);
223 public void service(Request request, Response response) throws Exception {
224 if (delegate != null) {
225 delegate.service(request, response);
229 if ("/dynamic".equals(request.getRequestURI())) {
230 boolean webSocket = false;
231 String mimeType = request.getParameter("mimeType");
232 List<String> params = new ArrayList<String>();
233 for (int i = 0; ; i++) {
234 String p = request.getParameter("param" + i);
239 if ("protocol:ws".equals(p)) {
243 final String cnt = request.getParameter("content");
244 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
245 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
247 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
249 url = registerWebSocket(res);
251 url = registerResource(res);
253 response.getWriter().write(url.toString());
254 response.getWriter().write("\n");
258 for (Resource r : ic.resources) {
259 if (r.httpPath.equals(request.getRequestURI())) {
260 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
261 response.setContentType(r.httpType);
262 r.httpContent.reset();
263 String[] params = null;
264 if (r.parameters.length != 0) {
265 params = new String[r.parameters.length];
266 for (int i = 0; i < r.parameters.length; i++) {
267 params[i] = request.getParameter(r.parameters[i]);
268 if (params[i] == null) {
269 if ("http.method".equals(r.parameters[i])) {
270 params[i] = request.getMethod().toString();
271 } else if ("http.requestBody".equals(r.parameters[i])) {
272 Reader rdr = request.getReader();
273 StringBuilder sb = new StringBuilder();
281 params[i] = sb.toString();
284 if (params[i] == null) {
290 copyStream(r.httpContent, response.getOutputStream(), null, params);
295 private URI registerWebSocket(Resource r) {
296 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
297 return pageURL("ws", server, r.httpPath);
300 private URI registerResource(Resource r) {
301 if (!ic.resources.contains(r)) {
303 conf.addHttpHandler(this, r.httpPath);
305 return pageURL("http", server, r.httpPath);
309 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
311 conf.addHttpHandler(new HttpHandler() {
313 List<InvocationContext> cases = new ArrayList<InvocationContext>();
314 DynamicResourceHandler prev;
316 public void service(Request request, Response response) throws Exception {
317 String id = request.getParameter("request");
318 String value = request.getParameter("result");
319 if (value != null && value.indexOf((char)0xC5) != -1) {
320 value = toUTF8(value);
324 InvocationContext mi = null;
327 if (id != null && value != null) {
328 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
329 value = decodeURL(value);
330 int indx = Integer.parseInt(id);
331 cases.get(indx).result(value, null);
332 if (++indx < cases.size()) {
333 mi = cases.get(indx);
334 LOG.log(Level.INFO, "Re-executing case {0}", indx);
338 if (!cases.isEmpty()) {
339 LOG.info("Re-executing test cases");
350 response.getWriter().write("");
353 LOG.log(Level.INFO, "End of data reached. Exiting.");
356 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
361 conf.addHttpHandler(prev, "/dynamic");
364 final String cn = mi.clazz.getName();
365 final String mn = mi.methodName;
366 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
367 response.getWriter().write("{"
368 + "className: '" + cn + "', "
369 + "methodName: '" + mn + "', "
370 + "request: " + caseNmbr
372 if (mi.html != null) {
373 response.getWriter().write(", html: '");
374 response.getWriter().write(encodeJSON(mi.html));
375 response.getWriter().write("'");
377 response.getWriter().write("}");
381 this.brwsr = launchServerAndBrwsr(server, "/execute");
384 private static String encodeJSON(String in) {
385 StringBuilder sb = new StringBuilder();
386 for (int i = 0; i < in.length(); i++) {
387 char ch = in.charAt(i);
388 if (ch < 32 || ch == '\'' || ch == '"') {
390 String hs = "0000" + Integer.toHexString(ch);
391 hs = hs.substring(hs.length() - 4);
397 return sb.toString();
401 public void shutdown() throws IOException {
404 int prev = methods.size();
406 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
409 } catch (InterruptedException ex) {
410 throw new IOException(ex);
412 if (prev == methods.size()) {
415 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
421 "Timeout, but tests got from {0} to {1}. Trying again.",
422 new Object[]{prev, methods.size()}
425 stopServerAndBrwsr(server, brwsr);
428 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
434 if (ch == '$' && params.length > 0) {
435 int cnt = is.read() - '0';
436 if (baseURL != null && cnt == 'U' - '0') {
437 os.write(baseURL.getBytes("UTF-8"));
439 if (cnt >= 0 && cnt < params.length) {
440 os.write(params[cnt].getBytes("UTF-8"));
452 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
454 URI uri = pageURL("http", server, page);
455 return showBrwsr(uri);
457 private static String toUTF8(String value) throws UnsupportedEncodingException {
458 byte[] arr = new byte[value.length()];
459 for (int i = 0; i < arr.length; i++) {
460 arr[i] = (byte)value.charAt(i);
462 return new String(arr, "UTF-8");
465 private static String decodeURL(String s) {
467 int pos = s.indexOf('%');
471 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
472 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
476 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
480 Process process = (Process)brwsr[0];
483 InputStream stdout = process.getInputStream();
484 InputStream stderr = process.getErrorStream();
485 drain("StdOut", stdout);
486 drain("StdErr", stderr);
490 res = process.waitFor();
491 } catch (InterruptedException ex) {
492 throw new IOException(ex);
494 LOG.log(Level.INFO, "Exit code: {0}", res);
496 deleteTree((File)brwsr[1]);
499 private static void drain(String name, InputStream is) throws IOException {
500 int av = is.available();
502 StringBuilder sb = new StringBuilder();
503 sb.append("v== ").append(name).append(" ==v\n");
505 sb.append((char)is.read());
507 sb.append("\n^== ").append(name).append(" ==^");
508 LOG.log(Level.INFO, sb.toString());
512 private void deleteTree(File file) {
516 File[] arr = file.listFiles();
526 public HttpServer call() throws Exception {
531 public void close() throws IOException {
535 protected Object[] showBrwsr(URI uri) throws IOException {
536 LOG.log(Level.INFO, "Showing {0}", uri);
539 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
540 System.getProperty("java.vm.name"),
541 System.getProperty("java.vm.vendor"),
542 System.getProperty("java.vm.version"),
544 java.awt.Desktop.getDesktop().browse(uri);
545 LOG.log(Level.INFO, "Desktop.browse successfully finished");
547 } catch (UnsupportedOperationException ex) {
548 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
549 LOG.log(Level.FINE, null, ex);
553 String cmdName = cmd == null ? "xdg-open" : cmd;
555 cmdName, uri.toString()
557 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
558 final Process process = Runtime.getRuntime().exec(cmdArr);
559 return new Object[] { process, null };
563 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
564 abstract String harnessResource();
565 String compileJar(URL jar) throws IOException {
568 String compileFromClassPath(URL f, Res loader) throws IOException {
572 private static URI pageURL(String protocol, HttpServer server, final String page) {
573 NetworkListener listener = server.getListeners().iterator().next();
574 int port = listener.getPort();
576 return new URI(protocol + "://localhost:" + port + page);
577 } catch (URISyntaxException ex) {
578 throw new IllegalStateException(ex);
583 private final Set<URL> ignore = new HashSet<URL>();
585 String compileJar(URL jarURL) throws IOException {
586 String ret = BaseHTTPLauncher.this.compileJar(jarURL);
590 String compileFromClassPath(URL f) throws IOException {
591 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
593 public URL get(String resource, int skip) throws IOException {
594 if (!resource.endsWith(".class")) {
595 return getResource(resource, skip);
598 for (ClassLoader l : loaders) {
599 Enumeration<URL> en = l.getResources(resource);
600 while (en.hasMoreElements()) {
601 u = en.nextElement();
602 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
608 if (u.toExternalForm().contains("rt.jar")) {
609 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
614 throw new IOException("Can't find " + resource);
616 private URL getResource(String resource, int skip) throws IOException {
617 for (ClassLoader l : loaders) {
618 Enumeration<URL> en = l.getResources(resource);
619 while (en.hasMoreElements()) {
620 final URL now = en.nextElement();
621 if (now.toExternalForm().contains("sisu-inject-bean")) {
622 // certainly we don't want this resource, as that
623 // module is not compiled with target 1.6, currently
626 if (now.getProtocol().equals("jar")) {
627 JarURLConnection juc = (JarURLConnection) now.openConnection();
628 if (ignore.contains(juc.getJarFileURL())) {
637 throw new IOException("Not found (anymore of) " + resource);
641 private static class Page extends HttpHandler {
642 final String resource;
643 private final String[] args;
644 private final Res res;
646 public Page(Res res, String resource, String... args) {
648 this.resource = resource;
649 this.args = args.length == 0 ? new String[] { "$0" } : args;
653 public void service(Request request, Response response) throws Exception {
654 String r = computePage(request);
655 if (r.startsWith("/")) {
658 String[] replace = {};
659 if (r.endsWith(".html")) {
660 response.setContentType("text/html");
661 LOG.info("Content type text/html");
664 if (r.endsWith(".xhtml")) {
665 response.setContentType("application/xhtml+xml");
666 LOG.info("Content type application/xhtml+xml");
669 OutputStream os = response.getOutputStream();
671 InputStream is = res.get(r, 0).openStream();
672 copyStream(is, os, request.getRequestURL().toString(), replace);
673 } catch (IOException ex) {
674 response.setDetailMessage(ex.getLocalizedMessage());
676 response.setStatus(404);
680 protected String computePage(Request request) {
683 r = request.getHttpHandlerPath();
689 private static class SubTree extends Page {
691 public SubTree(Res res, String resource, String... args) {
692 super(res, resource, args);
696 protected String computePage(Request request) {
697 return resource + request.getHttpHandlerPath();
703 private class VMAndPages extends StaticHttpHandler {
704 private String vmResource;
706 public VMAndPages() {
707 super((String[]) null);
711 public void service(Request request, Response response) throws Exception {
712 if (request.getRequestURI().equals(vmResource)) {
713 response.setCharacterEncoding("UTF-8");
714 response.setContentType("text/javascript");
715 StringBuilder sb = new StringBuilder();
716 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
717 response.getWriter().write(sb.toString());
719 super.service(request, response);
723 private void registerVM(String vmResource) {
724 this.vmResource = vmResource;
728 private static class Classes extends HttpHandler {
729 private final Res loader;
731 public Classes(Res loader) {
732 this.loader = loader;
736 public void service(Request request, Response response) throws Exception {
737 String res = request.getHttpHandlerPath();
738 if (res.startsWith("/")) {
739 res = res.substring(1);
741 String skip = request.getParameter("skip");
742 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
743 URL url = loader.get(res, skipCnt);
744 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
745 response.setCharacterEncoding("UTF-8");
746 if (url.getProtocol().equals("jar")) {
747 JarURLConnection juc = (JarURLConnection) url.openConnection();
748 String s = loader.compileJar(juc.getJarFileURL());
750 Writer w = response.getWriter();
756 if (url.getProtocol().equals("file")) {
757 final String filePart = url.getFile();
758 if (filePart.endsWith(res)) {
763 filePart.substring(0, filePart.length() - res.length())
766 String s = loader.compileFromClassPath(url);
768 Writer w = response.getWriter();
774 } catch (IOException ex) {
775 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
777 InputStream is = null;
780 throw new IOException("Resource not found");
782 is = url.openStream();
783 response.setContentType("text/javascript");
784 Writer w = response.getWriter();
786 for (int i = 0;; i++) {
800 w.append(Integer.toString(b));
803 } catch (IOException ex) {
804 response.setStatus(HttpStatus.NOT_FOUND_404);
806 response.setDetailMessage(ex.getMessage());
815 private static class WS extends WebSocketApplication {
817 private final Resource r;
819 private WS(Resource r) {
824 public void onMessage(WebSocket socket, String text) {
826 r.httpContent.reset();
827 ByteArrayOutputStream out = new ByteArrayOutputStream();
828 copyStream(r.httpContent, out, null, text);
829 String s = new String(out.toByteArray(), "UTF-8");
831 } catch (IOException ex) {
832 LOG.log(Level.WARNING, null, ex);