Merging from default branch and resolving conflicts. mvn install -DskipTests passes OK.
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.LinkedHashSet;
39 import java.util.List;
41 import java.util.concurrent.BlockingQueue;
42 import java.util.concurrent.Callable;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.LinkedBlockingQueue;
45 import java.util.concurrent.TimeUnit;
46 import java.util.jar.JarFile;
47 import java.util.logging.Level;
48 import java.util.logging.Logger;
49 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
50 import org.glassfish.grizzly.PortRange;
51 import org.glassfish.grizzly.http.server.HttpHandler;
52 import org.glassfish.grizzly.http.server.HttpServer;
53 import org.glassfish.grizzly.http.server.NetworkListener;
54 import org.glassfish.grizzly.http.server.Request;
55 import org.glassfish.grizzly.http.server.Response;
56 import org.glassfish.grizzly.http.server.ServerConfiguration;
57 import org.glassfish.grizzly.http.server.StaticHttpHandler;
58 import org.glassfish.grizzly.http.util.HttpStatus;
59 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
60 import org.glassfish.grizzly.websockets.WebSocket;
61 import org.glassfish.grizzly.websockets.WebSocketAddOn;
62 import org.glassfish.grizzly.websockets.WebSocketApplication;
63 import org.glassfish.grizzly.websockets.WebSocketEngine;
66 * Lightweight server to launch Bck2Brwsr applications and tests.
67 * Supports execution in native browser as well as Java's internal
70 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
71 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
72 private static final InvocationContext END = new InvocationContext(null, null, null);
73 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
74 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
76 private final Res resources = new Res();
77 private final String cmd;
78 private Object[] brwsr;
79 private HttpServer server;
80 private CountDownLatch wait;
82 public BaseHTTPLauncher(String cmd) {
84 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
89 InvocationContext runMethod(InvocationContext c) throws IOException {
90 loaders.add(c.clazz.getClassLoader());
94 } catch (InterruptedException ex) {
95 throw new IOException(ex);
100 public void setTimeout(long ms) {
104 public void addClassLoader(ClassLoader url) {
105 this.loaders.add(url);
108 ClassLoader[] loaders() {
109 return loaders.toArray(new ClassLoader[loaders.size()]);
112 public void showURL(String startpage) throws IOException {
113 if (!startpage.startsWith("/")) {
114 startpage = "/" + startpage;
116 HttpServer s = initServer(".", true, "");
117 int last = startpage.lastIndexOf('/');
118 String prefix = startpage.substring(0, last);
119 String simpleName = startpage.substring(last);
120 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
123 launchServerAndBrwsr(s, simpleName);
124 } catch (Exception ex) {
125 throw new IOException(ex);
129 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
130 if (!startpage.startsWith("/")) {
131 startpage = "/" + startpage;
134 int last = startpage.lastIndexOf('/');
136 prefix = startpage.substring(0, last);
138 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
140 launchServerAndBrwsr(s, startpage);
141 } catch (Exception ex) {
142 throw new IOException(ex);
147 public void initialize() throws IOException {
150 } catch (InterruptedException ex) {
151 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
154 } catch (Exception ex) {
155 if (ex instanceof IOException) {
156 throw (IOException)ex;
158 if (ex instanceof RuntimeException) {
159 throw (RuntimeException)ex;
161 throw new IOException(ex);
165 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
166 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
168 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
169 setPoolName("Fx/Bck2 Brwsr").
172 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
173 setPoolName("Kernel Fx/Bck2").
176 for (NetworkListener nl : s.getListeners()) {
177 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
178 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
181 final ServerConfiguration conf = s.getServerConfiguration();
182 VMAndPages vm = new VMAndPages();
183 conf.addHttpHandler(vm, "/");
184 if (vmPrefix != null) {
185 vm.registerVM(vmPrefix + "/bck2brwsr.js");
191 conf.addHttpHandler(new Classes(resources), "/classes/");
193 final WebSocketAddOn addon = new WebSocketAddOn();
194 for (NetworkListener listener : s.getListeners()) {
195 listener.registerAddOn(addon);
200 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
201 wait = new CountDownLatch(1);
202 server = initServer(".", true, "");
203 final ServerConfiguration conf = server.getServerConfiguration();
205 class DynamicResourceHandler extends HttpHandler {
206 private final InvocationContext ic;
207 private int resourcesCount;
208 DynamicResourceHandler delegate;
209 public DynamicResourceHandler(InvocationContext ic) {
211 for (Resource r : ic.resources) {
212 conf.addHttpHandler(this, r.httpPath);
216 public void close(DynamicResourceHandler del) {
217 conf.removeHttpHandler(this);
222 public void service(Request request, Response response) throws Exception {
223 if (delegate != null) {
224 delegate.service(request, response);
228 if ("/dynamic".equals(request.getRequestURI())) {
229 boolean webSocket = false;
230 String mimeType = request.getParameter("mimeType");
231 List<String> params = new ArrayList<String>();
232 for (int i = 0; ; i++) {
233 String p = request.getParameter("param" + i);
238 if ("protocol:ws".equals(p)) {
242 final String cnt = request.getParameter("content");
243 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
244 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
246 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
248 url = registerWebSocket(res);
250 url = registerResource(res);
252 response.getWriter().write(url.toString());
253 response.getWriter().write("\n");
257 for (Resource r : ic.resources) {
258 if (r.httpPath.equals(request.getRequestURI())) {
259 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
260 response.setContentType(r.httpType);
261 r.httpContent.reset();
262 String[] params = null;
263 if (r.parameters.length != 0) {
264 params = new String[r.parameters.length];
265 for (int i = 0; i < r.parameters.length; i++) {
266 params[i] = request.getParameter(r.parameters[i]);
267 if (params[i] == null) {
268 if ("http.method".equals(r.parameters[i])) {
269 params[i] = request.getMethod().toString();
270 } else if ("http.requestBody".equals(r.parameters[i])) {
271 Reader rdr = request.getReader();
272 StringBuilder sb = new StringBuilder();
280 params[i] = sb.toString();
283 if (params[i] == null) {
289 copyStream(r.httpContent, response.getOutputStream(), null, params);
294 private URI registerWebSocket(Resource r) {
295 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
296 return pageURL("ws", server, r.httpPath);
299 private URI registerResource(Resource r) {
300 if (!ic.resources.contains(r)) {
302 conf.addHttpHandler(this, r.httpPath);
304 return pageURL("http", server, r.httpPath);
308 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
310 conf.addHttpHandler(new HttpHandler() {
312 List<InvocationContext> cases = new ArrayList<InvocationContext>();
313 DynamicResourceHandler prev;
315 public void service(Request request, Response response) throws Exception {
316 String id = request.getParameter("request");
317 String value = request.getParameter("result");
318 if (value != null && value.indexOf((char)0xC5) != -1) {
319 value = toUTF8(value);
323 InvocationContext mi = null;
326 if (id != null && value != null) {
327 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
328 value = decodeURL(value);
329 int indx = Integer.parseInt(id);
330 cases.get(indx).result(value, null);
331 if (++indx < cases.size()) {
332 mi = cases.get(indx);
333 LOG.log(Level.INFO, "Re-executing case {0}", indx);
337 if (!cases.isEmpty()) {
338 LOG.info("Re-executing test cases");
349 response.getWriter().write("");
352 LOG.log(Level.INFO, "End of data reached. Exiting.");
355 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
360 conf.addHttpHandler(prev, "/dynamic");
363 final String cn = mi.clazz.getName();
364 final String mn = mi.methodName;
365 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
366 response.getWriter().write("{"
367 + "className: '" + cn + "', "
368 + "methodName: '" + mn + "', "
369 + "request: " + caseNmbr
371 if (mi.html != null) {
372 response.getWriter().write(", html: '");
373 response.getWriter().write(encodeJSON(mi.html));
374 response.getWriter().write("'");
376 response.getWriter().write("}");
380 this.brwsr = launchServerAndBrwsr(server, "/execute");
383 private static String encodeJSON(String in) {
384 StringBuilder sb = new StringBuilder();
385 for (int i = 0; i < in.length(); i++) {
386 char ch = in.charAt(i);
387 if (ch < 32 || ch == '\'' || ch == '"') {
389 String hs = "0000" + Integer.toHexString(ch);
390 hs = hs.substring(hs.length() - 4);
396 return sb.toString();
400 public void shutdown() throws IOException {
403 int prev = methods.size();
405 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
408 } catch (InterruptedException ex) {
409 throw new IOException(ex);
411 if (prev == methods.size()) {
414 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
420 "Timeout, but tests got from {0} to {1}. Trying again.",
421 new Object[]{prev, methods.size()}
424 stopServerAndBrwsr(server, brwsr);
427 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
433 if (ch == '$' && params.length > 0) {
434 int cnt = is.read() - '0';
435 if (baseURL != null && cnt == 'U' - '0') {
436 os.write(baseURL.getBytes("UTF-8"));
438 if (cnt >= 0 && cnt < params.length) {
439 os.write(params[cnt].getBytes("UTF-8"));
451 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
453 URI uri = pageURL("http", server, page);
454 return showBrwsr(uri);
456 private static String toUTF8(String value) throws UnsupportedEncodingException {
457 byte[] arr = new byte[value.length()];
458 for (int i = 0; i < arr.length; i++) {
459 arr[i] = (byte)value.charAt(i);
461 return new String(arr, "UTF-8");
464 private static String decodeURL(String s) {
466 int pos = s.indexOf('%');
470 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
471 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
475 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
479 Process process = (Process)brwsr[0];
482 InputStream stdout = process.getInputStream();
483 InputStream stderr = process.getErrorStream();
484 drain("StdOut", stdout);
485 drain("StdErr", stderr);
489 res = process.waitFor();
490 } catch (InterruptedException ex) {
491 throw new IOException(ex);
493 LOG.log(Level.INFO, "Exit code: {0}", res);
495 deleteTree((File)brwsr[1]);
498 private static void drain(String name, InputStream is) throws IOException {
499 int av = is.available();
501 StringBuilder sb = new StringBuilder();
502 sb.append("v== ").append(name).append(" ==v\n");
504 sb.append((char)is.read());
506 sb.append("\n^== ").append(name).append(" ==^");
507 LOG.log(Level.INFO, sb.toString());
511 private void deleteTree(File file) {
515 File[] arr = file.listFiles();
525 public HttpServer call() throws Exception {
530 public void close() throws IOException {
534 protected Object[] showBrwsr(URI uri) throws IOException {
535 LOG.log(Level.INFO, "Showing {0}", uri);
538 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
539 System.getProperty("java.vm.name"),
540 System.getProperty("java.vm.vendor"),
541 System.getProperty("java.vm.version"),
543 java.awt.Desktop.getDesktop().browse(uri);
544 LOG.log(Level.INFO, "Desktop.browse successfully finished");
546 } catch (UnsupportedOperationException ex) {
547 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
548 LOG.log(Level.FINE, null, ex);
552 String cmdName = cmd == null ? "xdg-open" : cmd;
554 cmdName, uri.toString()
556 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
557 final Process process = Runtime.getRuntime().exec(cmdArr);
558 return new Object[] { process, null };
562 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
563 abstract String harnessResource();
564 String compileJar(JarFile jar) throws IOException {
567 String compileFromClassPath(URL f, Res loader) throws IOException {
571 private static URI pageURL(String protocol, HttpServer server, final String page) {
572 NetworkListener listener = server.getListeners().iterator().next();
573 int port = listener.getPort();
575 return new URI(protocol + "://localhost:" + port + page);
576 } catch (URISyntaxException ex) {
577 throw new IllegalStateException(ex);
582 String compileJar(JarFile jar) throws IOException {
583 return BaseHTTPLauncher.this.compileJar(jar);
585 String compileFromClassPath(URL f) throws IOException {
586 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
588 public URL get(String resource, int skip) throws IOException {
589 if (!resource.endsWith(".class")) {
590 return getResource(resource, skip);
593 for (ClassLoader l : loaders) {
594 Enumeration<URL> en = l.getResources(resource);
595 while (en.hasMoreElements()) {
596 u = en.nextElement();
597 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
603 if (u.toExternalForm().contains("rt.jar")) {
604 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
609 throw new IOException("Can't find " + resource);
611 private URL getResource(String resource, int skip) throws IOException {
612 for (ClassLoader l : loaders) {
613 Enumeration<URL> en = l.getResources(resource);
614 while (en.hasMoreElements()) {
615 final URL now = en.nextElement();
616 if (now.toExternalForm().contains("sisu-inject-bean")) {
617 // certainly we don't want this resource, as that
618 // module is not compiled with target 1.6, currently
626 throw new IOException("Not found (anymore of) " + resource);
630 private static class Page extends HttpHandler {
631 final String resource;
632 private final String[] args;
633 private final Res res;
635 public Page(Res res, String resource, String... args) {
637 this.resource = resource;
638 this.args = args.length == 0 ? new String[] { "$0" } : args;
642 public void service(Request request, Response response) throws Exception {
643 String r = computePage(request);
644 if (r.startsWith("/")) {
647 String[] replace = {};
648 if (r.endsWith(".html")) {
649 response.setContentType("text/html");
650 LOG.info("Content type text/html");
653 if (r.endsWith(".xhtml")) {
654 response.setContentType("application/xhtml+xml");
655 LOG.info("Content type application/xhtml+xml");
658 OutputStream os = response.getOutputStream();
660 InputStream is = res.get(r, 0).openStream();
661 copyStream(is, os, request.getRequestURL().toString(), replace);
662 } catch (IOException ex) {
663 response.setDetailMessage(ex.getLocalizedMessage());
665 response.setStatus(404);
669 protected String computePage(Request request) {
672 r = request.getHttpHandlerPath();
678 private static class SubTree extends Page {
680 public SubTree(Res res, String resource, String... args) {
681 super(res, resource, args);
685 protected String computePage(Request request) {
686 return resource + request.getHttpHandlerPath();
692 private class VMAndPages extends StaticHttpHandler {
693 private String vmResource;
695 public VMAndPages() {
696 super((String[]) null);
700 public void service(Request request, Response response) throws Exception {
701 if (request.getRequestURI().equals(vmResource)) {
702 response.setCharacterEncoding("UTF-8");
703 response.setContentType("text/javascript");
704 StringBuilder sb = new StringBuilder();
705 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
706 response.getWriter().write(sb.toString());
708 super.service(request, response);
712 private void registerVM(String vmResource) {
713 this.vmResource = vmResource;
717 private static class Classes extends HttpHandler {
718 private final Res loader;
720 public Classes(Res loader) {
721 this.loader = loader;
725 public void service(Request request, Response response) throws Exception {
726 String res = request.getHttpHandlerPath();
727 if (res.startsWith("/")) {
728 res = res.substring(1);
730 String skip = request.getParameter("skip");
731 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
732 URL url = loader.get(res, skipCnt);
733 if (url.getProtocol().equals("jar")) {
734 JarURLConnection juc = (JarURLConnection) url.openConnection();
735 String s = loader.compileJar(juc.getJarFile());
737 Writer w = response.getWriter();
743 if (url.getProtocol().equals("file")) {
744 String s = loader.compileFromClassPath(url);
746 Writer w = response.getWriter();
752 Exception ex = new Exception("Won't server bytes of " + url);
754 try (InputStream is = url.openStream()) {
756 InputStream is = null;
758 String skip = request.getParameter("skip");
759 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
760 is = loader.get(res, skipCnt);
762 response.setContentType("text/javascript");
763 Writer w = response.getWriter();
765 for (int i = 0;; i++) {
779 w.append(Integer.toString(b));
782 } catch (IOException ex)
784 response.setStatus(HttpStatus.NOT_FOUND_404);
786 response.setDetailMessage(ex.getMessage());
795 private static class WS extends WebSocketApplication {
797 private final Resource r;
799 private WS(Resource r) {
804 public void onMessage(WebSocket socket, String text) {
806 r.httpContent.reset();
807 ByteArrayOutputStream out = new ByteArrayOutputStream();
808 copyStream(r.httpContent, out, null, text);
809 String s = new String(out.toByteArray(), "UTF-8");
811 } catch (IOException ex) {
812 LOG.log(Level.WARNING, null, ex);