First updates to run with forthcoming version 0.5 - WebSockets in FX launcher and etc.
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.util.HttpStatus;
56 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
57 import org.glassfish.grizzly.websockets.WebSocket;
58 import org.glassfish.grizzly.websockets.WebSocketAddOn;
59 import org.glassfish.grizzly.websockets.WebSocketApplication;
60 import org.glassfish.grizzly.websockets.WebSocketEngine;
61 import org.openide.util.Exceptions;
64 * Lightweight server to launch Bck2Brwsr applications and tests.
65 * Supports execution in native browser as well as Java's internal
68 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
69 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
70 private static final InvocationContext END = new InvocationContext(null, null, null);
71 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
72 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
74 private final Res resources = new Res();
75 private final String cmd;
76 private Object[] brwsr;
77 private HttpServer server;
78 private CountDownLatch wait;
80 public BaseHTTPLauncher(String cmd) {
82 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
87 InvocationContext runMethod(InvocationContext c) throws IOException {
88 loaders.add(c.clazz.getClassLoader());
92 } catch (InterruptedException ex) {
93 throw new IOException(ex);
98 public void setTimeout(long ms) {
102 public void addClassLoader(ClassLoader url) {
103 this.loaders.add(url);
106 ClassLoader[] loaders() {
107 return loaders.toArray(new ClassLoader[loaders.size()]);
110 public void showURL(String startpage) throws IOException {
111 if (!startpage.startsWith("/")) {
112 startpage = "/" + startpage;
114 HttpServer s = initServer(".", true);
115 int last = startpage.lastIndexOf('/');
116 String prefix = startpage.substring(0, last);
117 String simpleName = startpage.substring(last);
118 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
121 launchServerAndBrwsr(s, simpleName);
122 } catch (Exception ex) {
123 throw new IOException(ex);
127 void showDirectory(File dir, String startpage) throws IOException {
128 if (!startpage.startsWith("/")) {
129 startpage = "/" + startpage;
131 HttpServer s = initServer(dir.getPath(), false);
133 launchServerAndBrwsr(s, startpage);
134 } catch (Exception ex) {
135 throw new IOException(ex);
140 public void initialize() throws IOException {
143 } catch (InterruptedException ex) {
144 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
147 } catch (Exception ex) {
148 if (ex instanceof IOException) {
149 throw (IOException)ex;
151 if (ex instanceof RuntimeException) {
152 throw (RuntimeException)ex;
154 throw new IOException(ex);
158 private HttpServer initServer(String path, boolean addClasses) throws IOException {
159 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
160 final WebSocketAddOn addon = new WebSocketAddOn();
161 for (NetworkListener listener : s.getListeners()) {
162 listener.registerAddOn(addon);
165 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
166 setPoolName("Fx/Bck2 Brwsr").
169 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
170 setPoolName("Kernel Fx/Bck2").
173 for (NetworkListener nl : s.getListeners()) {
174 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
175 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
178 final ServerConfiguration conf = s.getServerConfiguration();
180 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
181 conf.addHttpHandler(new Classes(resources), "/classes/");
186 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
187 wait = new CountDownLatch(1);
188 server = initServer(".", true);
189 final ServerConfiguration conf = server.getServerConfiguration();
191 class DynamicResourceHandler extends HttpHandler {
192 private final InvocationContext ic;
193 private int resourcesCount;
194 DynamicResourceHandler delegate;
195 public DynamicResourceHandler(InvocationContext ic) {
197 for (Resource r : ic.resources) {
198 conf.addHttpHandler(this, r.httpPath);
202 public void close(DynamicResourceHandler del) {
203 conf.removeHttpHandler(this);
208 public void service(Request request, Response response) throws Exception {
209 if (delegate != null) {
210 delegate.service(request, response);
214 if ("/dynamic".equals(request.getRequestURI())) {
215 boolean webSocket = false;
216 String mimeType = request.getParameter("mimeType");
217 List<String> params = new ArrayList<String>();
218 for (int i = 0; ; i++) {
219 String p = request.getParameter("param" + i);
224 if ("protocol:ws".equals(p)) {
228 final String cnt = request.getParameter("content");
229 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
230 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
232 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
234 url = registerWebSocket(res);
236 url = registerResource(res);
238 response.getWriter().write(url.toString());
239 response.getWriter().write("\n");
243 for (Resource r : ic.resources) {
244 if (r.httpPath.equals(request.getRequestURI())) {
245 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
246 response.setContentType(r.httpType);
247 r.httpContent.reset();
248 String[] params = null;
249 if (r.parameters.length != 0) {
250 params = new String[r.parameters.length];
251 for (int i = 0; i < r.parameters.length; i++) {
252 params[i] = request.getParameter(r.parameters[i]);
253 if (params[i] == null) {
254 if ("http.method".equals(r.parameters[i])) {
255 params[i] = request.getMethod().toString();
256 } else if ("http.requestBody".equals(r.parameters[i])) {
257 Reader rdr = request.getReader();
258 StringBuilder sb = new StringBuilder();
266 params[i] = sb.toString();
269 if (params[i] == null) {
275 copyStream(r.httpContent, response.getOutputStream(), null, params);
280 private URI registerWebSocket(Resource r) {
281 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
282 return pageURL("ws", server, r.httpPath);
285 private URI registerResource(Resource r) {
286 if (!ic.resources.contains(r)) {
288 conf.addHttpHandler(this, r.httpPath);
290 return pageURL("http", server, r.httpPath);
294 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
296 conf.addHttpHandler(new HttpHandler() {
298 List<InvocationContext> cases = new ArrayList<InvocationContext>();
299 DynamicResourceHandler prev;
301 public void service(Request request, Response response) throws Exception {
302 String id = request.getParameter("request");
303 String value = request.getParameter("result");
304 if (value != null && value.indexOf((char)0xC5) != -1) {
305 value = toUTF8(value);
309 InvocationContext mi = null;
312 if (id != null && value != null) {
313 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
314 value = decodeURL(value);
315 int indx = Integer.parseInt(id);
316 cases.get(indx).result(value, null);
317 if (++indx < cases.size()) {
318 mi = cases.get(indx);
319 LOG.log(Level.INFO, "Re-executing case {0}", indx);
323 if (!cases.isEmpty()) {
324 LOG.info("Re-executing test cases");
335 response.getWriter().write("");
338 LOG.log(Level.INFO, "End of data reached. Exiting.");
341 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
346 conf.addHttpHandler(prev, "/dynamic");
349 final String cn = mi.clazz.getName();
350 final String mn = mi.methodName;
351 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
352 response.getWriter().write("{"
353 + "className: '" + cn + "', "
354 + "methodName: '" + mn + "', "
355 + "request: " + caseNmbr
357 if (mi.html != null) {
358 response.getWriter().write(", html: '");
359 response.getWriter().write(encodeJSON(mi.html));
360 response.getWriter().write("'");
362 response.getWriter().write("}");
366 this.brwsr = launchServerAndBrwsr(server, "/execute");
369 private static String encodeJSON(String in) {
370 StringBuilder sb = new StringBuilder();
371 for (int i = 0; i < in.length(); i++) {
372 char ch = in.charAt(i);
373 if (ch < 32 || ch == '\'' || ch == '"') {
375 String hs = "0000" + Integer.toHexString(ch);
376 hs = hs.substring(hs.length() - 4);
382 return sb.toString();
386 public void shutdown() throws IOException {
389 int prev = methods.size();
391 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
394 } catch (InterruptedException ex) {
395 throw new IOException(ex);
397 if (prev == methods.size()) {
400 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
406 "Timeout, but tests got from {0} to {1}. Trying again.",
407 new Object[]{prev, methods.size()}
410 stopServerAndBrwsr(server, brwsr);
413 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
419 if (ch == '$' && params.length > 0) {
420 int cnt = is.read() - '0';
421 if (baseURL != null && cnt == 'U' - '0') {
422 os.write(baseURL.getBytes("UTF-8"));
424 if (cnt >= 0 && cnt < params.length) {
425 os.write(params[cnt].getBytes("UTF-8"));
437 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
439 URI uri = pageURL("http", server, page);
440 return showBrwsr(uri);
442 private static String toUTF8(String value) throws UnsupportedEncodingException {
443 byte[] arr = new byte[value.length()];
444 for (int i = 0; i < arr.length; i++) {
445 arr[i] = (byte)value.charAt(i);
447 return new String(arr, "UTF-8");
450 private static String decodeURL(String s) {
452 int pos = s.indexOf('%');
456 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
457 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
461 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
465 Process process = (Process)brwsr[0];
468 InputStream stdout = process.getInputStream();
469 InputStream stderr = process.getErrorStream();
470 drain("StdOut", stdout);
471 drain("StdErr", stderr);
475 res = process.waitFor();
476 } catch (InterruptedException ex) {
477 throw new IOException(ex);
479 LOG.log(Level.INFO, "Exit code: {0}", res);
481 deleteTree((File)brwsr[1]);
484 private static void drain(String name, InputStream is) throws IOException {
485 int av = is.available();
487 StringBuilder sb = new StringBuilder();
488 sb.append("v== ").append(name).append(" ==v\n");
490 sb.append((char)is.read());
492 sb.append("\n^== ").append(name).append(" ==^");
493 LOG.log(Level.INFO, sb.toString());
497 private void deleteTree(File file) {
501 File[] arr = file.listFiles();
511 public HttpServer call() throws Exception {
516 public void close() throws IOException {
520 protected Object[] showBrwsr(URI uri) throws IOException {
521 LOG.log(Level.INFO, "Showing {0}", uri);
524 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
525 System.getProperty("java.vm.name"),
526 System.getProperty("java.vm.vendor"),
527 System.getProperty("java.vm.version"),
529 java.awt.Desktop.getDesktop().browse(uri);
530 LOG.log(Level.INFO, "Desktop.browse successfully finished");
532 } catch (UnsupportedOperationException ex) {
533 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
534 LOG.log(Level.FINE, null, ex);
538 String cmdName = cmd == null ? "xdg-open" : cmd;
540 cmdName, uri.toString()
542 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
543 final Process process = Runtime.getRuntime().exec(cmdArr);
544 return new Object[] { process, null };
548 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
549 abstract String harnessResource();
551 private static URI pageURL(String protocol, HttpServer server, final String page) {
552 NetworkListener listener = server.getListeners().iterator().next();
553 int port = listener.getPort();
555 return new URI(protocol + "://localhost:" + port + page);
556 } catch (URISyntaxException ex) {
557 throw new IllegalStateException(ex);
562 public InputStream get(String resource) throws IOException {
564 for (ClassLoader l : loaders) {
565 Enumeration<URL> en = l.getResources(resource);
566 while (en.hasMoreElements()) {
567 u = en.nextElement();
568 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
569 return u.openStream();
574 if (u.toExternalForm().contains("rt.jar")) {
575 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
577 return u.openStream();
579 throw new IOException("Can't find " + resource);
583 private static class Page extends HttpHandler {
584 final String resource;
585 private final String[] args;
586 private final Res res;
588 public Page(Res res, String resource, String... args) {
590 this.resource = resource;
591 this.args = args.length == 0 ? new String[] { "$0" } : args;
595 public void service(Request request, Response response) throws Exception {
596 String r = computePage(request);
597 if (r.startsWith("/")) {
600 String[] replace = {};
601 if (r.endsWith(".html")) {
602 response.setContentType("text/html");
603 LOG.info("Content type text/html");
606 if (r.endsWith(".xhtml")) {
607 response.setContentType("application/xhtml+xml");
608 LOG.info("Content type application/xhtml+xml");
611 OutputStream os = response.getOutputStream();
613 InputStream is = res.get(r);
614 copyStream(is, os, request.getRequestURL().toString(), replace);
615 } catch (IOException ex) {
616 response.setDetailMessage(ex.getLocalizedMessage());
618 response.setStatus(404);
622 protected String computePage(Request request) {
625 r = request.getHttpHandlerPath();
631 private static class SubTree extends Page {
633 public SubTree(Res res, String resource, String... args) {
634 super(res, resource, args);
638 protected String computePage(Request request) {
639 return resource + request.getHttpHandlerPath();
645 private class VM extends HttpHandler {
647 public void service(Request request, Response response) throws Exception {
648 response.setCharacterEncoding("UTF-8");
649 response.setContentType("text/javascript");
650 StringBuilder sb = new StringBuilder();
651 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
652 response.getWriter().write(sb.toString());
656 private static class Classes extends HttpHandler {
657 private final Res loader;
659 public Classes(Res loader) {
660 this.loader = loader;
664 public void service(Request request, Response response) throws Exception {
665 String res = request.getHttpHandlerPath();
666 if (res.startsWith("/")) {
667 res = res.substring(1);
669 InputStream is = null;
671 is = loader.get(res);
672 response.setContentType("text/javascript");
673 Writer w = response.getWriter();
675 for (int i = 0;; i++) {
689 w.append(Integer.toString(b));
692 } catch (IOException ex) {
693 response.setStatus(HttpStatus.NOT_FOUND_404);
695 response.setDetailMessage(ex.getMessage());
703 private static class WS extends WebSocketApplication {
705 private final Resource r;
707 private WS(Resource r) {
712 public void onMessage(WebSocket socket, String text) {
714 r.httpContent.reset();
715 ByteArrayOutputStream out = new ByteArrayOutputStream();
716 copyStream(r.httpContent, out, null, text);
717 String s = new String(out.toByteArray(), "UTF-8");
719 } catch (IOException ex) {
720 Exceptions.printStackTrace(ex);