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;
32 import java.net.URISyntaxException;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Enumeration;
37 import java.util.LinkedHashSet;
38 import java.util.List;
40 import java.util.concurrent.BlockingQueue;
41 import java.util.concurrent.Callable;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.LinkedBlockingQueue;
44 import java.util.concurrent.TimeUnit;
45 import java.util.logging.Level;
46 import java.util.logging.Logger;
47 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
48 import org.glassfish.grizzly.PortRange;
49 import org.glassfish.grizzly.http.server.HttpHandler;
50 import org.glassfish.grizzly.http.server.HttpServer;
51 import org.glassfish.grizzly.http.server.NetworkListener;
52 import org.glassfish.grizzly.http.server.Request;
53 import org.glassfish.grizzly.http.server.Response;
54 import org.glassfish.grizzly.http.server.ServerConfiguration;
55 import org.glassfish.grizzly.http.server.StaticHttpHandler;
56 import org.glassfish.grizzly.http.util.HttpStatus;
57 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
58 import org.glassfish.grizzly.websockets.WebSocket;
59 import org.glassfish.grizzly.websockets.WebSocketAddOn;
60 import org.glassfish.grizzly.websockets.WebSocketApplication;
61 import org.glassfish.grizzly.websockets.WebSocketEngine;
62 import org.openide.util.Exceptions;
65 * Lightweight server to launch Bck2Brwsr applications and tests.
66 * Supports execution in native browser as well as Java's internal
69 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
70 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
71 private static final InvocationContext END = new InvocationContext(null, null, null);
72 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
73 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
75 private final Res resources = new Res();
76 private final String cmd;
77 private Object[] brwsr;
78 private HttpServer server;
79 private CountDownLatch wait;
81 public BaseHTTPLauncher(String cmd) {
83 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
88 InvocationContext runMethod(InvocationContext c) throws IOException {
89 loaders.add(c.clazz.getClassLoader());
93 } catch (InterruptedException ex) {
94 throw new IOException(ex);
99 public void setTimeout(long ms) {
103 public void addClassLoader(ClassLoader url) {
104 this.loaders.add(url);
107 ClassLoader[] loaders() {
108 return loaders.toArray(new ClassLoader[loaders.size()]);
111 public void showURL(String startpage) throws IOException {
112 if (!startpage.startsWith("/")) {
113 startpage = "/" + startpage;
115 HttpServer s = initServer(".", true, "");
116 int last = startpage.lastIndexOf('/');
117 String prefix = startpage.substring(0, last);
118 String simpleName = startpage.substring(last);
119 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
122 launchServerAndBrwsr(s, simpleName);
123 } catch (Exception ex) {
124 throw new IOException(ex);
128 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
129 if (!startpage.startsWith("/")) {
130 startpage = "/" + startpage;
133 int last = startpage.lastIndexOf('/');
135 prefix = startpage.substring(0, last);
137 HttpServer s = initServer(dir.getPath(), addClasses, prefix);
139 launchServerAndBrwsr(s, startpage);
140 } catch (Exception ex) {
141 throw new IOException(ex);
146 public void initialize() throws IOException {
149 } catch (InterruptedException ex) {
150 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
153 } catch (Exception ex) {
154 if (ex instanceof IOException) {
155 throw (IOException)ex;
157 if (ex instanceof RuntimeException) {
158 throw (RuntimeException)ex;
160 throw new IOException(ex);
164 private HttpServer initServer(String path, boolean addClasses, String vmPrefix) throws IOException {
165 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
167 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
168 setPoolName("Fx/Bck2 Brwsr").
171 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
172 setPoolName("Kernel Fx/Bck2").
175 for (NetworkListener nl : s.getListeners()) {
176 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
177 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
180 final ServerConfiguration conf = s.getServerConfiguration();
181 VMAndPages vm = new VMAndPages();
182 conf.addHttpHandler(vm, "/");
183 if (vmPrefix != null) {
184 vm.registerVM(vmPrefix + "/bck2brwsr.js");
190 conf.addHttpHandler(new Classes(resources), "/classes/");
192 final WebSocketAddOn addon = new WebSocketAddOn();
193 for (NetworkListener listener : s.getListeners()) {
194 listener.registerAddOn(addon);
199 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
200 wait = new CountDownLatch(1);
201 server = initServer(".", true, "");
202 final ServerConfiguration conf = server.getServerConfiguration();
204 class DynamicResourceHandler extends HttpHandler {
205 private final InvocationContext ic;
206 private int resourcesCount;
207 DynamicResourceHandler delegate;
208 public DynamicResourceHandler(InvocationContext ic) {
210 for (Resource r : ic.resources) {
211 conf.addHttpHandler(this, r.httpPath);
215 public void close(DynamicResourceHandler del) {
216 conf.removeHttpHandler(this);
221 public void service(Request request, Response response) throws Exception {
222 if (delegate != null) {
223 delegate.service(request, response);
227 if ("/dynamic".equals(request.getRequestURI())) {
228 boolean webSocket = false;
229 String mimeType = request.getParameter("mimeType");
230 List<String> params = new ArrayList<String>();
231 for (int i = 0; ; i++) {
232 String p = request.getParameter("param" + i);
237 if ("protocol:ws".equals(p)) {
241 final String cnt = request.getParameter("content");
242 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
243 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
245 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
247 url = registerWebSocket(res);
249 url = registerResource(res);
251 response.getWriter().write(url.toString());
252 response.getWriter().write("\n");
256 for (Resource r : ic.resources) {
257 if (r.httpPath.equals(request.getRequestURI())) {
258 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
259 response.setContentType(r.httpType);
260 r.httpContent.reset();
261 String[] params = null;
262 if (r.parameters.length != 0) {
263 params = new String[r.parameters.length];
264 for (int i = 0; i < r.parameters.length; i++) {
265 params[i] = request.getParameter(r.parameters[i]);
266 if (params[i] == null) {
267 if ("http.method".equals(r.parameters[i])) {
268 params[i] = request.getMethod().toString();
269 } else if ("http.requestBody".equals(r.parameters[i])) {
270 Reader rdr = request.getReader();
271 StringBuilder sb = new StringBuilder();
279 params[i] = sb.toString();
282 if (params[i] == null) {
288 copyStream(r.httpContent, response.getOutputStream(), null, params);
293 private URI registerWebSocket(Resource r) {
294 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
295 return pageURL("ws", server, r.httpPath);
298 private URI registerResource(Resource r) {
299 if (!ic.resources.contains(r)) {
301 conf.addHttpHandler(this, r.httpPath);
303 return pageURL("http", server, r.httpPath);
307 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
309 conf.addHttpHandler(new HttpHandler() {
311 List<InvocationContext> cases = new ArrayList<InvocationContext>();
312 DynamicResourceHandler prev;
314 public void service(Request request, Response response) throws Exception {
315 String id = request.getParameter("request");
316 String value = request.getParameter("result");
317 if (value != null && value.indexOf((char)0xC5) != -1) {
318 value = toUTF8(value);
322 InvocationContext mi = null;
325 if (id != null && value != null) {
326 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
327 value = decodeURL(value);
328 int indx = Integer.parseInt(id);
329 cases.get(indx).result(value, null);
330 if (++indx < cases.size()) {
331 mi = cases.get(indx);
332 LOG.log(Level.INFO, "Re-executing case {0}", indx);
336 if (!cases.isEmpty()) {
337 LOG.info("Re-executing test cases");
348 response.getWriter().write("");
351 LOG.log(Level.INFO, "End of data reached. Exiting.");
354 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
359 conf.addHttpHandler(prev, "/dynamic");
362 final String cn = mi.clazz.getName();
363 final String mn = mi.methodName;
364 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
365 response.getWriter().write("{"
366 + "className: '" + cn + "', "
367 + "methodName: '" + mn + "', "
368 + "request: " + caseNmbr
370 if (mi.html != null) {
371 response.getWriter().write(", html: '");
372 response.getWriter().write(encodeJSON(mi.html));
373 response.getWriter().write("'");
375 response.getWriter().write("}");
379 this.brwsr = launchServerAndBrwsr(server, "/execute");
382 private static String encodeJSON(String in) {
383 StringBuilder sb = new StringBuilder();
384 for (int i = 0; i < in.length(); i++) {
385 char ch = in.charAt(i);
386 if (ch < 32 || ch == '\'' || ch == '"') {
388 String hs = "0000" + Integer.toHexString(ch);
389 hs = hs.substring(hs.length() - 4);
395 return sb.toString();
399 public void shutdown() throws IOException {
402 int prev = methods.size();
404 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
407 } catch (InterruptedException ex) {
408 throw new IOException(ex);
410 if (prev == methods.size()) {
413 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
419 "Timeout, but tests got from {0} to {1}. Trying again.",
420 new Object[]{prev, methods.size()}
423 stopServerAndBrwsr(server, brwsr);
426 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
432 if (ch == '$' && params.length > 0) {
433 int cnt = is.read() - '0';
434 if (baseURL != null && cnt == 'U' - '0') {
435 os.write(baseURL.getBytes("UTF-8"));
437 if (cnt >= 0 && cnt < params.length) {
438 os.write(params[cnt].getBytes("UTF-8"));
450 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
452 URI uri = pageURL("http", server, page);
453 return showBrwsr(uri);
455 private static String toUTF8(String value) throws UnsupportedEncodingException {
456 byte[] arr = new byte[value.length()];
457 for (int i = 0; i < arr.length; i++) {
458 arr[i] = (byte)value.charAt(i);
460 return new String(arr, "UTF-8");
463 private static String decodeURL(String s) {
465 int pos = s.indexOf('%');
469 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
470 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
474 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
478 Process process = (Process)brwsr[0];
481 InputStream stdout = process.getInputStream();
482 InputStream stderr = process.getErrorStream();
483 drain("StdOut", stdout);
484 drain("StdErr", stderr);
488 res = process.waitFor();
489 } catch (InterruptedException ex) {
490 throw new IOException(ex);
492 LOG.log(Level.INFO, "Exit code: {0}", res);
494 deleteTree((File)brwsr[1]);
497 private static void drain(String name, InputStream is) throws IOException {
498 int av = is.available();
500 StringBuilder sb = new StringBuilder();
501 sb.append("v== ").append(name).append(" ==v\n");
503 sb.append((char)is.read());
505 sb.append("\n^== ").append(name).append(" ==^");
506 LOG.log(Level.INFO, sb.toString());
510 private void deleteTree(File file) {
514 File[] arr = file.listFiles();
524 public HttpServer call() throws Exception {
529 public void close() throws IOException {
533 protected Object[] showBrwsr(URI uri) throws IOException {
534 LOG.log(Level.INFO, "Showing {0}", uri);
537 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
538 System.getProperty("java.vm.name"),
539 System.getProperty("java.vm.vendor"),
540 System.getProperty("java.vm.version"),
542 java.awt.Desktop.getDesktop().browse(uri);
543 LOG.log(Level.INFO, "Desktop.browse successfully finished");
545 } catch (UnsupportedOperationException ex) {
546 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
547 LOG.log(Level.FINE, null, ex);
551 String cmdName = cmd == null ? "xdg-open" : cmd;
553 cmdName, uri.toString()
555 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
556 final Process process = Runtime.getRuntime().exec(cmdArr);
557 return new Object[] { process, null };
561 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
562 abstract String harnessResource();
564 private static URI pageURL(String protocol, HttpServer server, final String page) {
565 NetworkListener listener = server.getListeners().iterator().next();
566 int port = listener.getPort();
568 return new URI(protocol + "://localhost:" + port + page);
569 } catch (URISyntaxException ex) {
570 throw new IllegalStateException(ex);
575 public InputStream get(String resource) throws IOException {
577 for (ClassLoader l : loaders) {
578 Enumeration<URL> en = l.getResources(resource);
579 while (en.hasMoreElements()) {
580 u = en.nextElement();
581 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
582 return u.openStream();
587 if (u.toExternalForm().contains("rt.jar")) {
588 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
590 return u.openStream();
592 throw new IOException("Can't find " + resource);
596 private static class Page extends HttpHandler {
597 final String resource;
598 private final String[] args;
599 private final Res res;
601 public Page(Res res, String resource, String... args) {
603 this.resource = resource;
604 this.args = args.length == 0 ? new String[] { "$0" } : args;
608 public void service(Request request, Response response) throws Exception {
609 String r = computePage(request);
610 if (r.startsWith("/")) {
613 String[] replace = {};
614 if (r.endsWith(".html")) {
615 response.setContentType("text/html");
616 LOG.info("Content type text/html");
619 if (r.endsWith(".xhtml")) {
620 response.setContentType("application/xhtml+xml");
621 LOG.info("Content type application/xhtml+xml");
624 OutputStream os = response.getOutputStream();
626 InputStream is = res.get(r);
627 copyStream(is, os, request.getRequestURL().toString(), replace);
628 } catch (IOException ex) {
629 response.setDetailMessage(ex.getLocalizedMessage());
631 response.setStatus(404);
635 protected String computePage(Request request) {
638 r = request.getHttpHandlerPath();
644 private static class SubTree extends Page {
646 public SubTree(Res res, String resource, String... args) {
647 super(res, resource, args);
651 protected String computePage(Request request) {
652 return resource + request.getHttpHandlerPath();
658 private class VMAndPages extends StaticHttpHandler {
659 private String vmResource;
661 public VMAndPages() {
662 super((String[]) null);
666 public void service(Request request, Response response) throws Exception {
667 if (request.getRequestURI().equals(vmResource)) {
668 response.setCharacterEncoding("UTF-8");
669 response.setContentType("text/javascript");
670 StringBuilder sb = new StringBuilder();
671 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
672 response.getWriter().write(sb.toString());
674 super.service(request, response);
678 private void registerVM(String vmResource) {
679 this.vmResource = vmResource;
683 private static class Classes extends HttpHandler {
684 private final Res loader;
686 public Classes(Res loader) {
687 this.loader = loader;
691 public void service(Request request, Response response) throws Exception {
692 String res = request.getHttpHandlerPath();
693 if (res.startsWith("/")) {
694 res = res.substring(1);
696 InputStream is = null;
698 is = loader.get(res);
699 response.setContentType("text/javascript");
700 Writer w = response.getWriter();
702 for (int i = 0;; i++) {
716 w.append(Integer.toString(b));
719 } catch (IOException ex) {
720 response.setStatus(HttpStatus.NOT_FOUND_404);
722 response.setDetailMessage(ex.getMessage());
730 private static class WS extends WebSocketApplication {
732 private final Resource r;
734 private WS(Resource r) {
739 public void onMessage(WebSocket socket, String text) {
741 r.httpContent.reset();
742 ByteArrayOutputStream out = new ByteArrayOutputStream();
743 copyStream(r.httpContent, out, null, text);
744 String s = new String(out.toByteArray(), "UTF-8");
746 } catch (IOException ex) {
747 Exceptions.printStackTrace(ex);