Make sure exceptions that lead to 500 error are reported to console.
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.Manifest;
52 import java.util.logging.ConsoleHandler;
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.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);
205 Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
206 l.setLevel(Level.FINE);
207 l.setUseParentHandlers(false);
208 ConsoleHandler ch = new ConsoleHandler();
209 ch.setLevel(Level.ALL);
214 private static int resourcesCount;
215 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
216 wait = new CountDownLatch(1);
217 server = initServer(".", true, "");
218 final ServerConfiguration conf = server.getServerConfiguration();
220 class DynamicResourceHandler extends HttpHandler {
221 private final InvocationContext ic;
222 DynamicResourceHandler delegate;
223 public DynamicResourceHandler(InvocationContext ic) {
225 for (Resource r : ic.resources) {
226 conf.addHttpHandler(this, r.httpPath);
230 public void close(DynamicResourceHandler del) {
231 conf.removeHttpHandler(this);
236 public void service(Request request, Response response) throws Exception {
237 if (delegate != null) {
238 delegate.service(request, response);
242 if ("/dynamic".equals(request.getRequestURI())) {
243 boolean webSocket = false;
244 String mimeType = request.getParameter("mimeType");
245 List<String> params = new ArrayList<String>();
246 for (int i = 0; ; i++) {
247 String p = request.getParameter("param" + i);
252 if ("protocol:ws".equals(p)) {
256 final String cnt = request.getParameter("content");
257 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
258 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
260 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
262 url = registerWebSocket(res);
264 url = registerResource(res);
266 response.setHeader(Header.CacheControl, "no-cache");
267 response.setHeader(Header.Pragma, "no-cache");
268 response.getWriter().write(url.toString());
269 response.getWriter().write("\n");
273 for (Resource r : ic.resources) {
274 if (r.httpPath.equals(request.getRequestURI())) {
275 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
276 response.setContentType(r.httpType);
277 response.setHeader(Header.CacheControl, "no-cache");
278 response.setHeader(Header.Pragma, "no-cache");
279 r.httpContent.reset();
280 String[] params = null;
281 if (r.parameters.length != 0) {
282 params = new String[r.parameters.length];
283 for (int i = 0; i < r.parameters.length; i++) {
284 params[i] = request.getParameter(r.parameters[i]);
285 if (params[i] == null) {
286 if ("http.method".equals(r.parameters[i])) {
287 params[i] = request.getMethod().toString();
288 } else if ("http.requestBody".equals(r.parameters[i])) {
289 Reader rdr = request.getReader();
290 StringBuilder sb = new StringBuilder();
298 params[i] = sb.toString();
301 if (params[i] == null) {
307 copyStream(r.httpContent, response.getOutputStream(), null, params);
312 private URI registerWebSocket(Resource r) {
313 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
314 return pageURL("ws", server, r.httpPath);
317 private URI registerResource(Resource r) {
318 if (!ic.resources.contains(r)) {
320 conf.addHttpHandler(this, r.httpPath);
322 return pageURL("http", server, r.httpPath);
326 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
328 conf.addHttpHandler(new HttpHandler() {
330 List<InvocationContext> cases = new ArrayList<InvocationContext>();
331 DynamicResourceHandler prev;
333 public void service(Request request, Response response) throws Exception {
334 String id = request.getParameter("request");
335 String value = request.getParameter("result");
336 if (value != null && value.indexOf((char)0xC5) != -1) {
337 value = toUTF8(value);
341 InvocationContext mi = null;
344 if (id != null && value != null) {
345 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
346 value = decodeURL(value);
347 int indx = Integer.parseInt(id);
348 cases.get(indx).result(value, null);
349 if (++indx < cases.size()) {
350 mi = cases.get(indx);
351 LOG.log(Level.INFO, "Re-executing case {0}", indx);
355 if (!cases.isEmpty()) {
356 LOG.info("Re-executing test cases");
367 response.getWriter().write("");
370 LOG.log(Level.INFO, "End of data reached. Exiting.");
373 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
378 conf.addHttpHandler(prev, "/dynamic");
381 final String cn = mi.clazz.getName();
382 final String mn = mi.methodName;
383 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
384 response.getWriter().write("{"
385 + "className: '" + cn + "', "
386 + "methodName: '" + mn + "', "
387 + "request: " + caseNmbr
389 if (mi.html != null) {
390 response.getWriter().write(", html: '");
391 response.getWriter().write(encodeJSON(mi.html));
392 response.getWriter().write("'");
394 response.getWriter().write("}");
398 this.brwsr = launchServerAndBrwsr(server, "/execute");
401 private static String encodeJSON(String in) {
402 StringBuilder sb = new StringBuilder();
403 for (int i = 0; i < in.length(); i++) {
404 char ch = in.charAt(i);
405 if (ch < 32 || ch == '\'' || ch == '"') {
407 String hs = "0000" + Integer.toHexString(ch);
408 hs = hs.substring(hs.length() - 4);
414 return sb.toString();
418 public void shutdown() throws IOException {
421 int prev = methods.size();
423 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
426 } catch (InterruptedException ex) {
427 throw new IOException(ex);
429 if (prev == methods.size()) {
432 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
438 "Timeout, but tests got from {0} to {1}. Trying again.",
439 new Object[]{prev, methods.size()}
442 stopServerAndBrwsr(server, brwsr);
445 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
451 if (ch == '$' && params.length > 0) {
452 int cnt = is.read() - '0';
453 if (baseURL != null && cnt == 'U' - '0') {
454 os.write(baseURL.getBytes("UTF-8"));
456 if (cnt >= 0 && cnt < params.length) {
457 os.write(params[cnt].getBytes("UTF-8"));
469 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
471 URI uri = pageURL("http", server, page);
472 return showBrwsr(uri);
474 private static String toUTF8(String value) throws UnsupportedEncodingException {
475 byte[] arr = new byte[value.length()];
476 for (int i = 0; i < arr.length; i++) {
477 arr[i] = (byte)value.charAt(i);
479 return new String(arr, "UTF-8");
482 private static String decodeURL(String s) {
484 int pos = s.indexOf('%');
488 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
489 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
493 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
497 Process process = (Process)brwsr[0];
500 InputStream stdout = process.getInputStream();
501 InputStream stderr = process.getErrorStream();
502 drain("StdOut", stdout);
503 drain("StdErr", stderr);
507 res = process.waitFor();
508 } catch (InterruptedException ex) {
509 throw new IOException(ex);
511 LOG.log(Level.INFO, "Exit code: {0}", res);
513 deleteTree((File)brwsr[1]);
516 private static void drain(String name, InputStream is) throws IOException {
517 int av = is.available();
519 StringBuilder sb = new StringBuilder();
520 sb.append("v== ").append(name).append(" ==v\n");
522 sb.append((char)is.read());
524 sb.append("\n^== ").append(name).append(" ==^");
525 LOG.log(Level.INFO, sb.toString());
529 private void deleteTree(File file) {
533 File[] arr = file.listFiles();
543 public HttpServer call() throws Exception {
548 public void close() throws IOException {
552 protected Object[] showBrwsr(URI uri) throws IOException {
553 LOG.log(Level.INFO, "Showing {0}", uri);
556 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
557 System.getProperty("java.vm.name"),
558 System.getProperty("java.vm.vendor"),
559 System.getProperty("java.vm.version"),
561 java.awt.Desktop.getDesktop().browse(uri);
562 LOG.log(Level.INFO, "Desktop.browse successfully finished");
564 } catch (UnsupportedOperationException ex) {
565 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
566 LOG.log(Level.FINE, null, ex);
567 } catch (IOException ex) {
568 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
569 LOG.log(Level.FINE, null, ex);
573 String cmdName = cmd == null ? "xdg-open" : cmd;
575 cmdName, uri.toString()
577 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
578 final Process process = Runtime.getRuntime().exec(cmdArr);
579 return new Object[] { process, null };
583 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
584 abstract String harnessResource();
585 Object compileJar(URL jar, URL precompiled) throws IOException {
588 String compileFromClassPath(URL f, Res loader) throws IOException {
592 private static URI pageURL(String protocol, HttpServer server, final String page) {
593 NetworkListener listener = server.getListeners().iterator().next();
594 int port = listener.getPort();
596 return new URI(protocol + "://localhost:" + port + page);
597 } catch (URISyntaxException ex) {
598 throw new IllegalStateException(ex);
603 private final Set<URL> ignore = new HashSet<URL>();
605 Object compileJar(URL jarURL) throws IOException {
606 List<String[]> libraries = new ArrayList<String[]>();
607 for (ClassLoader loader : loaders) {
608 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
609 while (en.hasMoreElements()) {
610 URL e = en.nextElement();
611 Manifest mf = new Manifest(e.openStream());
612 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
613 String key = entrySet.getKey();
614 Attributes attr = entrySet.getValue();
616 final String a = attr.getValue("Bck2BrwsrArtifactId");
617 final String g = attr.getValue("Bck2BrwsrGroupId");
618 final String v = attr.getValue("Bck2BrwsrVersion");
619 final String d = attr.getValue("Bck2BrwsrDebug");
621 if (g != null && a != null && v != null && "true".equals(d)) {
622 libraries.add(new String[] {
629 URL precompiled = null;
630 for (ClassLoader loader : loaders) {
631 for (String[] lib : libraries) {
632 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
633 URL props = loader.getResource(res);
635 URLConnection c = props.openConnection();
636 Properties load = new Properties();
637 final InputStream is = c.getInputStream();
640 if (lib[2].equals(load.getProperty("version"))) {
641 if (c instanceof JarURLConnection) {
642 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
643 if (definedInURL.equals(jarURL)) {
644 precompiled = loader.getResource(lib[3]);
651 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
655 String compileFromClassPath(URL f) throws IOException {
656 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
658 public URL get(String resource, int skip) throws IOException {
659 if (!resource.endsWith(".class")) {
660 return getResource(resource, skip);
663 for (ClassLoader l : loaders) {
664 Enumeration<URL> en = l.getResources(resource);
665 while (en.hasMoreElements()) {
666 u = en.nextElement();
667 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
673 if (u.toExternalForm().contains("rt.jar")) {
674 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
679 throw new IOException("Can't find " + resource);
681 private URL getResource(String resource, int skip) throws IOException {
682 for (ClassLoader l : loaders) {
683 Enumeration<URL> en = l.getResources(resource);
684 while (en.hasMoreElements()) {
685 final URL now = en.nextElement();
686 if (now.toExternalForm().contains("sisu-inject-bean")) {
687 // certainly we don't want this resource, as that
688 // module is not compiled with target 1.6, currently
691 if (now.getProtocol().equals("jar")) {
692 JarURLConnection juc = (JarURLConnection) now.openConnection();
693 if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
702 throw new IOException("Not found (anymore of) " + resource);
706 private static class Page extends HttpHandler {
707 final String resource;
708 private final String[] args;
709 private final Res res;
711 public Page(Res res, String resource, String... args) {
713 this.resource = resource;
714 this.args = args.length == 0 ? new String[] { "$0" } : args;
718 public void service(Request request, Response response) throws Exception {
719 String r = computePage(request);
720 if (r.startsWith("/")) {
723 String[] replace = {};
724 if (r.endsWith(".html")) {
725 response.setContentType("text/html");
726 LOG.info("Content type text/html");
729 if (r.endsWith(".xhtml")) {
730 response.setContentType("application/xhtml+xml");
731 LOG.info("Content type application/xhtml+xml");
734 OutputStream os = response.getOutputStream();
736 InputStream is = res.get(r, 0).openStream();
737 copyStream(is, os, request.getRequestURL().toString(), replace);
738 } catch (IOException ex) {
739 response.setDetailMessage(ex.getLocalizedMessage());
741 response.setStatus(404);
745 protected String computePage(Request request) {
748 r = request.getHttpHandlerPath();
754 private static class SubTree extends Page {
756 public SubTree(Res res, String resource, String... args) {
757 super(res, resource, args);
761 protected String computePage(Request request) {
762 return resource + request.getHttpHandlerPath();
768 private class VMAndPages extends StaticHttpHandler {
769 private String vmResource;
771 public VMAndPages() {
772 super((String[]) null);
776 public void service(Request request, Response response) throws Exception {
777 if (request.getRequestURI().equals(vmResource)) {
778 response.setCharacterEncoding("UTF-8");
779 response.setContentType("text/javascript");
780 StringBuilder sb = new StringBuilder();
781 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
782 response.getWriter().write(sb.toString());
784 super.service(request, response);
788 private void registerVM(String vmResource) {
789 this.vmResource = vmResource;
793 private static class Classes extends HttpHandler {
794 private final Res loader;
796 public Classes(Res loader) {
797 this.loader = loader;
801 public void service(Request request, Response response) throws Exception {
802 String res = request.getHttpHandlerPath();
803 if (res.startsWith("/")) {
804 res = res.substring(1);
806 String skip = request.getParameter("skip");
807 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
808 URL url = loader.get(res, skipCnt);
809 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
810 response.setCharacterEncoding("UTF-8");
811 if (url.getProtocol().equals("jar")) {
812 JarURLConnection juc = (JarURLConnection) url.openConnection();
815 s = loader.compileJar(juc.getJarFileURL());
816 } catch (IOException iOException) {
817 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
819 if (s instanceof String) {
820 Writer w = response.getWriter();
825 if (s instanceof InputStream) {
826 copyStream((InputStream) s, response.getOutputStream(), null);
830 if (url.getProtocol().equals("file")) {
831 final String filePart = url.getFile();
832 if (filePart.endsWith(res)) {
837 filePart.substring(0, filePart.length() - res.length())
840 String s = loader.compileFromClassPath(url);
842 Writer w = response.getWriter();
848 } catch (IOException ex) {
849 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
851 InputStream is = null;
854 throw new IOException("Resource not found");
856 is = url.openStream();
857 response.setContentType("text/javascript");
858 Writer w = response.getWriter();
860 for (int i = 0;; i++) {
874 w.append(Integer.toString(b));
877 } catch (IOException ex) {
878 response.setStatus(HttpStatus.NOT_FOUND_404);
880 response.setDetailMessage(ex.getMessage());
889 private static class WS extends WebSocketApplication {
891 private final Resource r;
893 private WS(Resource r) {
898 public void onMessage(WebSocket socket, String text) {
900 r.httpContent.reset();
901 ByteArrayOutputStream out = new ByteArrayOutputStream();
902 copyStream(r.httpContent, out, null, text);
903 String s = new String(out.toByteArray(), "UTF-8");
905 } catch (IOException ex) {
906 LOG.log(Level.WARNING, null, ex);