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;
134 String prefix = null;
135 if (!new File(dir, "bck2brwsr.js").exists()) {
136 int last = startpage.lastIndexOf('/');
138 prefix = startpage.substring(0, last);
141 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
143 launchServerAndBrwsr(s, startpage);
144 } catch (Exception ex) {
145 throw new IOException(ex);
150 public void initialize() throws IOException {
153 } catch (InterruptedException ex) {
154 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
157 } catch (Exception ex) {
158 if (ex instanceof IOException) {
159 throw (IOException)ex;
161 if (ex instanceof RuntimeException) {
162 throw (RuntimeException)ex;
164 throw new IOException(ex);
168 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
169 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
171 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
172 setPoolName("Fx/Bck2 Brwsr").
175 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
176 setPoolName("Kernel Fx/Bck2").
179 for (NetworkListener nl : s.getListeners()) {
180 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
181 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
184 final ServerConfiguration conf = s.getServerConfiguration();
185 VMAndPages vm = new VMAndPages();
186 conf.addHttpHandler(vm, "/");
187 if (vmPrefix != null) {
188 vm.registerVM(vmPrefix + "/bck2brwsr.js");
194 conf.addHttpHandler(new Classes(resources), "/classes/");
196 final WebSocketAddOn addon = new WebSocketAddOn();
197 for (NetworkListener listener : s.getListeners()) {
198 listener.registerAddOn(addon);
203 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
204 wait = new CountDownLatch(1);
205 server = initServer(".", true, "");
206 final ServerConfiguration conf = server.getServerConfiguration();
208 class DynamicResourceHandler extends HttpHandler {
209 private final InvocationContext ic;
210 private int resourcesCount;
211 DynamicResourceHandler delegate;
212 public DynamicResourceHandler(InvocationContext ic) {
214 for (Resource r : ic.resources) {
215 conf.addHttpHandler(this, r.httpPath);
219 public void close(DynamicResourceHandler del) {
220 conf.removeHttpHandler(this);
225 public void service(Request request, Response response) throws Exception {
226 if (delegate != null) {
227 delegate.service(request, response);
231 if ("/dynamic".equals(request.getRequestURI())) {
232 boolean webSocket = false;
233 String mimeType = request.getParameter("mimeType");
234 List<String> params = new ArrayList<String>();
235 for (int i = 0; ; i++) {
236 String p = request.getParameter("param" + i);
241 if ("protocol:ws".equals(p)) {
245 final String cnt = request.getParameter("content");
246 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
247 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
249 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
251 url = registerWebSocket(res);
253 url = registerResource(res);
255 response.getWriter().write(url.toString());
256 response.getWriter().write("\n");
260 for (Resource r : ic.resources) {
261 if (r.httpPath.equals(request.getRequestURI())) {
262 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
263 response.setContentType(r.httpType);
264 r.httpContent.reset();
265 String[] params = null;
266 if (r.parameters.length != 0) {
267 params = new String[r.parameters.length];
268 for (int i = 0; i < r.parameters.length; i++) {
269 params[i] = request.getParameter(r.parameters[i]);
270 if (params[i] == null) {
271 if ("http.method".equals(r.parameters[i])) {
272 params[i] = request.getMethod().toString();
273 } else if ("http.requestBody".equals(r.parameters[i])) {
274 Reader rdr = request.getReader();
275 StringBuilder sb = new StringBuilder();
283 params[i] = sb.toString();
286 if (params[i] == null) {
292 copyStream(r.httpContent, response.getOutputStream(), null, params);
297 private URI registerWebSocket(Resource r) {
298 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
299 return pageURL("ws", server, r.httpPath);
302 private URI registerResource(Resource r) {
303 if (!ic.resources.contains(r)) {
305 conf.addHttpHandler(this, r.httpPath);
307 return pageURL("http", server, r.httpPath);
311 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
313 conf.addHttpHandler(new HttpHandler() {
315 List<InvocationContext> cases = new ArrayList<InvocationContext>();
316 DynamicResourceHandler prev;
318 public void service(Request request, Response response) throws Exception {
319 String id = request.getParameter("request");
320 String value = request.getParameter("result");
321 if (value != null && value.indexOf((char)0xC5) != -1) {
322 value = toUTF8(value);
326 InvocationContext mi = null;
329 if (id != null && value != null) {
330 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
331 value = decodeURL(value);
332 int indx = Integer.parseInt(id);
333 cases.get(indx).result(value, null);
334 if (++indx < cases.size()) {
335 mi = cases.get(indx);
336 LOG.log(Level.INFO, "Re-executing case {0}", indx);
340 if (!cases.isEmpty()) {
341 LOG.info("Re-executing test cases");
352 response.getWriter().write("");
355 LOG.log(Level.INFO, "End of data reached. Exiting.");
358 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
363 conf.addHttpHandler(prev, "/dynamic");
366 final String cn = mi.clazz.getName();
367 final String mn = mi.methodName;
368 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
369 response.getWriter().write("{"
370 + "className: '" + cn + "', "
371 + "methodName: '" + mn + "', "
372 + "request: " + caseNmbr
374 if (mi.html != null) {
375 response.getWriter().write(", html: '");
376 response.getWriter().write(encodeJSON(mi.html));
377 response.getWriter().write("'");
379 response.getWriter().write("}");
383 this.brwsr = launchServerAndBrwsr(server, "/execute");
386 private static String encodeJSON(String in) {
387 StringBuilder sb = new StringBuilder();
388 for (int i = 0; i < in.length(); i++) {
389 char ch = in.charAt(i);
390 if (ch < 32 || ch == '\'' || ch == '"') {
392 String hs = "0000" + Integer.toHexString(ch);
393 hs = hs.substring(hs.length() - 4);
399 return sb.toString();
403 public void shutdown() throws IOException {
406 int prev = methods.size();
408 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
411 } catch (InterruptedException ex) {
412 throw new IOException(ex);
414 if (prev == methods.size()) {
417 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
423 "Timeout, but tests got from {0} to {1}. Trying again.",
424 new Object[]{prev, methods.size()}
427 stopServerAndBrwsr(server, brwsr);
430 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
436 if (ch == '$' && params.length > 0) {
437 int cnt = is.read() - '0';
438 if (baseURL != null && cnt == 'U' - '0') {
439 os.write(baseURL.getBytes("UTF-8"));
441 if (cnt >= 0 && cnt < params.length) {
442 os.write(params[cnt].getBytes("UTF-8"));
454 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
456 URI uri = pageURL("http", server, page);
457 return showBrwsr(uri);
459 private static String toUTF8(String value) throws UnsupportedEncodingException {
460 byte[] arr = new byte[value.length()];
461 for (int i = 0; i < arr.length; i++) {
462 arr[i] = (byte)value.charAt(i);
464 return new String(arr, "UTF-8");
467 private static String decodeURL(String s) {
469 int pos = s.indexOf('%');
473 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
474 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
478 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
482 Process process = (Process)brwsr[0];
485 InputStream stdout = process.getInputStream();
486 InputStream stderr = process.getErrorStream();
487 drain("StdOut", stdout);
488 drain("StdErr", stderr);
492 res = process.waitFor();
493 } catch (InterruptedException ex) {
494 throw new IOException(ex);
496 LOG.log(Level.INFO, "Exit code: {0}", res);
498 deleteTree((File)brwsr[1]);
501 private static void drain(String name, InputStream is) throws IOException {
502 int av = is.available();
504 StringBuilder sb = new StringBuilder();
505 sb.append("v== ").append(name).append(" ==v\n");
507 sb.append((char)is.read());
509 sb.append("\n^== ").append(name).append(" ==^");
510 LOG.log(Level.INFO, sb.toString());
514 private void deleteTree(File file) {
518 File[] arr = file.listFiles();
528 public HttpServer call() throws Exception {
533 public void close() throws IOException {
537 protected Object[] showBrwsr(URI uri) throws IOException {
538 LOG.log(Level.INFO, "Showing {0}", uri);
541 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
542 System.getProperty("java.vm.name"),
543 System.getProperty("java.vm.vendor"),
544 System.getProperty("java.vm.version"),
546 java.awt.Desktop.getDesktop().browse(uri);
547 LOG.log(Level.INFO, "Desktop.browse successfully finished");
549 } catch (UnsupportedOperationException ex) {
550 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
551 LOG.log(Level.FINE, null, ex);
552 } catch (IOException ex) {
553 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
554 LOG.log(Level.FINE, null, ex);
558 String cmdName = cmd == null ? "xdg-open" : cmd;
560 cmdName, uri.toString()
562 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
563 final Process process = Runtime.getRuntime().exec(cmdArr);
564 return new Object[] { process, null };
568 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
569 abstract String harnessResource();
570 String compileJar(URL jar) throws IOException {
573 String compileFromClassPath(URL f, Res loader) throws IOException {
577 private static URI pageURL(String protocol, HttpServer server, final String page) {
578 NetworkListener listener = server.getListeners().iterator().next();
579 int port = listener.getPort();
581 return new URI(protocol + "://localhost:" + port + page);
582 } catch (URISyntaxException ex) {
583 throw new IllegalStateException(ex);
588 private final Set<URL> ignore = new HashSet<URL>();
590 String compileJar(URL jarURL) throws IOException {
591 String ret = BaseHTTPLauncher.this.compileJar(jarURL);
595 String compileFromClassPath(URL f) throws IOException {
596 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
598 public URL get(String resource, int skip) throws IOException {
599 if (!resource.endsWith(".class")) {
600 return getResource(resource, skip);
603 for (ClassLoader l : loaders) {
604 Enumeration<URL> en = l.getResources(resource);
605 while (en.hasMoreElements()) {
606 u = en.nextElement();
607 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
613 if (u.toExternalForm().contains("rt.jar")) {
614 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
619 throw new IOException("Can't find " + resource);
621 private URL getResource(String resource, int skip) throws IOException {
622 for (ClassLoader l : loaders) {
623 Enumeration<URL> en = l.getResources(resource);
624 while (en.hasMoreElements()) {
625 final URL now = en.nextElement();
626 if (now.toExternalForm().contains("sisu-inject-bean")) {
627 // certainly we don't want this resource, as that
628 // module is not compiled with target 1.6, currently
631 if (now.getProtocol().equals("jar")) {
632 JarURLConnection juc = (JarURLConnection) now.openConnection();
633 if (ignore.contains(juc.getJarFileURL())) {
642 throw new IOException("Not found (anymore of) " + resource);
646 private static class Page extends HttpHandler {
647 final String resource;
648 private final String[] args;
649 private final Res res;
651 public Page(Res res, String resource, String... args) {
653 this.resource = resource;
654 this.args = args.length == 0 ? new String[] { "$0" } : args;
658 public void service(Request request, Response response) throws Exception {
659 String r = computePage(request);
660 if (r.startsWith("/")) {
663 String[] replace = {};
664 if (r.endsWith(".html")) {
665 response.setContentType("text/html");
666 LOG.info("Content type text/html");
669 if (r.endsWith(".xhtml")) {
670 response.setContentType("application/xhtml+xml");
671 LOG.info("Content type application/xhtml+xml");
674 OutputStream os = response.getOutputStream();
676 InputStream is = res.get(r, 0).openStream();
677 copyStream(is, os, request.getRequestURL().toString(), replace);
678 } catch (IOException ex) {
679 response.setDetailMessage(ex.getLocalizedMessage());
681 response.setStatus(404);
685 protected String computePage(Request request) {
688 r = request.getHttpHandlerPath();
694 private static class SubTree extends Page {
696 public SubTree(Res res, String resource, String... args) {
697 super(res, resource, args);
701 protected String computePage(Request request) {
702 return resource + request.getHttpHandlerPath();
708 private class VMAndPages extends StaticHttpHandler {
709 private String vmResource;
711 public VMAndPages() {
712 super((String[]) null);
716 public void service(Request request, Response response) throws Exception {
717 if (request.getRequestURI().equals(vmResource)) {
718 response.setCharacterEncoding("UTF-8");
719 response.setContentType("text/javascript");
720 StringBuilder sb = new StringBuilder();
721 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
722 response.getWriter().write(sb.toString());
724 super.service(request, response);
728 private void registerVM(String vmResource) {
729 this.vmResource = vmResource;
733 private static class Classes extends HttpHandler {
734 private final Res loader;
736 public Classes(Res loader) {
737 this.loader = loader;
741 public void service(Request request, Response response) throws Exception {
742 String res = request.getHttpHandlerPath();
743 if (res.startsWith("/")) {
744 res = res.substring(1);
746 String skip = request.getParameter("skip");
747 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
748 URL url = loader.get(res, skipCnt);
749 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
750 response.setCharacterEncoding("UTF-8");
751 if (url.getProtocol().equals("jar")) {
752 JarURLConnection juc = (JarURLConnection) url.openConnection();
753 String s = loader.compileJar(juc.getJarFileURL());
755 Writer w = response.getWriter();
761 if (url.getProtocol().equals("file")) {
762 final String filePart = url.getFile();
763 if (filePart.endsWith(res)) {
768 filePart.substring(0, filePart.length() - res.length())
771 String s = loader.compileFromClassPath(url);
773 Writer w = response.getWriter();
779 } catch (IOException ex) {
780 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
782 InputStream is = null;
785 throw new IOException("Resource not found");
787 is = url.openStream();
788 response.setContentType("text/javascript");
789 Writer w = response.getWriter();
791 for (int i = 0;; i++) {
805 w.append(Integer.toString(b));
808 } catch (IOException ex) {
809 response.setStatus(HttpStatus.NOT_FOUND_404);
811 response.setDetailMessage(ex.getMessage());
820 private static class WS extends WebSocketApplication {
822 private final Resource r;
824 private WS(Resource r) {
829 public void onMessage(WebSocket socket, String text) {
831 r.httpContent.reset();
832 ByteArrayOutputStream out = new ByteArrayOutputStream();
833 copyStream(r.httpContent, out, null, text);
834 String s = new String(out.toByteArray(), "UTF-8");
836 } catch (IOException ex) {
837 LOG.log(Level.WARNING, null, ex);