JDK8 throws IOException on the build server. Try xdg-open fallback then.
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);
550 } catch (IOException ex) {
551 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
552 LOG.log(Level.FINE, null, ex);
556 String cmdName = cmd == null ? "xdg-open" : cmd;
558 cmdName, uri.toString()
560 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
561 final Process process = Runtime.getRuntime().exec(cmdArr);
562 return new Object[] { process, null };
566 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
567 abstract String harnessResource();
568 String compileJar(JarFile jar) throws IOException {
571 String compileFromClassPath(URL f, Res loader) throws IOException {
575 private static URI pageURL(String protocol, HttpServer server, final String page) {
576 NetworkListener listener = server.getListeners().iterator().next();
577 int port = listener.getPort();
579 return new URI(protocol + "://localhost:" + port + page);
580 } catch (URISyntaxException ex) {
581 throw new IllegalStateException(ex);
586 private final Set<URL> ignore = new HashSet<URL>();
588 String compileJar(JarFile jar, URL jarURL) throws IOException {
589 String ret = BaseHTTPLauncher.this.compileJar(jar);
593 String compileFromClassPath(URL f) throws IOException {
594 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
596 public URL get(String resource, int skip) throws IOException {
597 if (!resource.endsWith(".class")) {
598 return getResource(resource, skip);
601 for (ClassLoader l : loaders) {
602 Enumeration<URL> en = l.getResources(resource);
603 while (en.hasMoreElements()) {
604 u = en.nextElement();
605 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
611 if (u.toExternalForm().contains("rt.jar")) {
612 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
617 throw new IOException("Can't find " + resource);
619 private URL getResource(String resource, int skip) throws IOException {
620 for (ClassLoader l : loaders) {
621 Enumeration<URL> en = l.getResources(resource);
622 while (en.hasMoreElements()) {
623 final URL now = en.nextElement();
624 if (now.toExternalForm().contains("sisu-inject-bean")) {
625 // certainly we don't want this resource, as that
626 // module is not compiled with target 1.6, currently
629 if (now.getProtocol().equals("jar")) {
630 JarURLConnection juc = (JarURLConnection) now.openConnection();
631 if (ignore.contains(juc.getJarFileURL())) {
640 throw new IOException("Not found (anymore of) " + resource);
644 private static class Page extends HttpHandler {
645 final String resource;
646 private final String[] args;
647 private final Res res;
649 public Page(Res res, String resource, String... args) {
651 this.resource = resource;
652 this.args = args.length == 0 ? new String[] { "$0" } : args;
656 public void service(Request request, Response response) throws Exception {
657 String r = computePage(request);
658 if (r.startsWith("/")) {
661 String[] replace = {};
662 if (r.endsWith(".html")) {
663 response.setContentType("text/html");
664 LOG.info("Content type text/html");
667 if (r.endsWith(".xhtml")) {
668 response.setContentType("application/xhtml+xml");
669 LOG.info("Content type application/xhtml+xml");
672 OutputStream os = response.getOutputStream();
674 InputStream is = res.get(r, 0).openStream();
675 copyStream(is, os, request.getRequestURL().toString(), replace);
676 } catch (IOException ex) {
677 response.setDetailMessage(ex.getLocalizedMessage());
679 response.setStatus(404);
683 protected String computePage(Request request) {
686 r = request.getHttpHandlerPath();
692 private static class SubTree extends Page {
694 public SubTree(Res res, String resource, String... args) {
695 super(res, resource, args);
699 protected String computePage(Request request) {
700 return resource + request.getHttpHandlerPath();
706 private class VMAndPages extends StaticHttpHandler {
707 private String vmResource;
709 public VMAndPages() {
710 super((String[]) null);
714 public void service(Request request, Response response) throws Exception {
715 if (request.getRequestURI().equals(vmResource)) {
716 response.setCharacterEncoding("UTF-8");
717 response.setContentType("text/javascript");
718 StringBuilder sb = new StringBuilder();
719 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
720 response.getWriter().write(sb.toString());
722 super.service(request, response);
726 private void registerVM(String vmResource) {
727 this.vmResource = vmResource;
731 private static class Classes extends HttpHandler {
732 private final Res loader;
734 public Classes(Res loader) {
735 this.loader = loader;
739 public void service(Request request, Response response) throws Exception {
740 String res = request.getHttpHandlerPath();
741 if (res.startsWith("/")) {
742 res = res.substring(1);
744 String skip = request.getParameter("skip");
745 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
746 URL url = loader.get(res, skipCnt);
747 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
748 response.setCharacterEncoding("UTF-8");
749 if (url.getProtocol().equals("jar")) {
750 JarURLConnection juc = (JarURLConnection) url.openConnection();
751 String s = loader.compileJar(juc.getJarFile(), juc.getJarFileURL());
753 Writer w = response.getWriter();
759 if (url.getProtocol().equals("file")) {
760 String s = loader.compileFromClassPath(url);
762 Writer w = response.getWriter();
768 } catch (IOException ex) {
769 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
771 InputStream is = null;
774 throw new IOException("Resource not found");
776 is = url.openStream();
777 response.setContentType("text/javascript");
778 Writer w = response.getWriter();
780 for (int i = 0;; i++) {
794 w.append(Integer.toString(b));
797 } catch (IOException ex) {
798 response.setStatus(HttpStatus.NOT_FOUND_404);
800 response.setDetailMessage(ex.getMessage());
809 private static class WS extends WebSocketApplication {
811 private final Resource r;
813 private WS(Resource r) {
818 public void onMessage(WebSocket socket, String text) {
820 r.httpContent.reset();
821 ByteArrayOutputStream out = new ByteArrayOutputStream();
822 copyStream(r.httpContent, out, null, text);
823 String s = new String(out.toByteArray(), "UTF-8");
825 } catch (IOException ex) {
826 LOG.log(Level.WARNING, null, ex);