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.Closeable;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InterruptedIOException;
25 import java.io.OutputStream;
26 import java.io.Reader;
27 import java.io.UnsupportedEncodingException;
28 import java.io.Writer;
30 import java.net.URISyntaxException;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Enumeration;
35 import java.util.LinkedHashSet;
36 import java.util.List;
38 import java.util.concurrent.BlockingQueue;
39 import java.util.concurrent.Callable;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.LinkedBlockingQueue;
42 import java.util.concurrent.TimeUnit;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
45 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
46 import org.glassfish.grizzly.PortRange;
47 import org.glassfish.grizzly.http.server.HttpHandler;
48 import org.glassfish.grizzly.http.server.HttpServer;
49 import org.glassfish.grizzly.http.server.NetworkListener;
50 import org.glassfish.grizzly.http.server.Request;
51 import org.glassfish.grizzly.http.server.Response;
52 import org.glassfish.grizzly.http.server.ServerConfiguration;
53 import org.glassfish.grizzly.http.util.HttpStatus;
54 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
57 * Lightweight server to launch Bck2Brwsr applications and tests.
58 * Supports execution in native browser as well as Java's internal
61 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
62 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
63 private static final InvocationContext END = new InvocationContext(null, null, null);
64 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
65 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
67 private final Res resources = new Res();
68 private final String cmd;
69 private Object[] brwsr;
70 private HttpServer server;
71 private CountDownLatch wait;
73 public BaseHTTPLauncher(String cmd) {
75 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
80 InvocationContext runMethod(InvocationContext c) throws IOException {
81 loaders.add(c.clazz.getClassLoader());
85 } catch (InterruptedException ex) {
86 throw new IOException(ex);
91 public void setTimeout(long ms) {
95 public void addClassLoader(ClassLoader url) {
96 this.loaders.add(url);
99 ClassLoader[] loaders() {
100 return loaders.toArray(new ClassLoader[loaders.size()]);
103 public void showURL(String startpage) throws IOException {
104 if (!startpage.startsWith("/")) {
105 startpage = "/" + startpage;
107 HttpServer s = initServer(".", true);
108 int last = startpage.lastIndexOf('/');
109 String prefix = startpage.substring(0, last);
110 String simpleName = startpage.substring(last);
111 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
114 launchServerAndBrwsr(s, simpleName);
115 } catch (Exception ex) {
116 throw new IOException(ex);
120 void showDirectory(File dir, String startpage) throws IOException {
121 if (!startpage.startsWith("/")) {
122 startpage = "/" + startpage;
124 HttpServer s = initServer(dir.getPath(), false);
126 launchServerAndBrwsr(s, startpage);
127 } catch (Exception ex) {
128 throw new IOException(ex);
133 public void initialize() throws IOException {
136 } catch (InterruptedException ex) {
137 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
140 } catch (Exception ex) {
141 if (ex instanceof IOException) {
142 throw (IOException)ex;
144 if (ex instanceof RuntimeException) {
145 throw (RuntimeException)ex;
147 throw new IOException(ex);
151 private HttpServer initServer(String path, boolean addClasses) throws IOException {
152 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
154 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
155 setPoolName("Fx/Bck2 Brwsr").
158 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
159 setPoolName("Kernel Fx/Bck2").
162 for (NetworkListener nl : s.getListeners()) {
163 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
164 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
167 final ServerConfiguration conf = s.getServerConfiguration();
169 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
170 conf.addHttpHandler(new Classes(resources), "/classes/");
175 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
176 wait = new CountDownLatch(1);
177 server = initServer(".", true);
178 final ServerConfiguration conf = server.getServerConfiguration();
180 class DynamicResourceHandler extends HttpHandler implements InvocationContext.RegisterResource {
181 private final InvocationContext ic;
182 public DynamicResourceHandler(InvocationContext ic) {
184 for (Resource r : ic.resources) {
185 conf.addHttpHandler(this, r.httpPath);
187 InvocationContext.register(this);
190 public void close() {
191 conf.removeHttpHandler(this);
192 InvocationContext.register(null);
196 public void service(Request request, Response response) throws Exception {
197 for (Resource r : ic.resources) {
198 if (r.httpPath.equals(request.getRequestURI())) {
199 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
200 response.setContentType(r.httpType);
201 r.httpContent.reset();
202 String[] params = null;
203 if (r.parameters.length != 0) {
204 params = new String[r.parameters.length];
205 for (int i = 0; i < r.parameters.length; i++) {
206 params[i] = request.getParameter(r.parameters[i]);
207 if (params[i] == null) {
208 if ("http.method".equals(r.parameters[i])) {
209 params[i] = request.getMethod().toString();
210 } else if ("http.requestBody".equals(r.parameters[i])) {
211 Reader rdr = request.getReader();
212 StringBuilder sb = new StringBuilder();
220 params[i] = sb.toString();
223 if (params[i] == null) {
229 copyStream(r.httpContent, response.getOutputStream(), null, params);
235 public URI registerResource(Resource r) {
236 if (!ic.resources.contains(r)) {
238 conf.addHttpHandler(this, r.httpPath);
240 return pageURL(server, r.httpPath);
244 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
246 conf.addHttpHandler(new HttpHandler() {
248 List<InvocationContext> cases = new ArrayList<InvocationContext>();
249 DynamicResourceHandler prev;
251 public void service(Request request, Response response) throws Exception {
252 String id = request.getParameter("request");
253 String value = request.getParameter("result");
254 if (value != null && value.indexOf((char)0xC5) != -1) {
255 value = toUTF8(value);
259 InvocationContext mi = null;
262 if (id != null && value != null) {
263 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
264 value = decodeURL(value);
265 int indx = Integer.parseInt(id);
266 cases.get(indx).result(value, null);
267 if (++indx < cases.size()) {
268 mi = cases.get(indx);
269 LOG.log(Level.INFO, "Re-executing case {0}", indx);
273 if (!cases.isEmpty()) {
274 LOG.info("Re-executing test cases");
290 response.getWriter().write("");
293 LOG.log(Level.INFO, "End of data reached. Exiting.");
297 prev = new DynamicResourceHandler(mi);
300 final String cn = mi.clazz.getName();
301 final String mn = mi.methodName;
302 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
303 response.getWriter().write("{"
304 + "className: '" + cn + "', "
305 + "methodName: '" + mn + "', "
306 + "request: " + caseNmbr
308 if (mi.html != null) {
309 response.getWriter().write(", html: '");
310 response.getWriter().write(encodeJSON(mi.html));
311 response.getWriter().write("'");
313 response.getWriter().write("}");
317 this.brwsr = launchServerAndBrwsr(server, "/execute");
320 private static String encodeJSON(String in) {
321 StringBuilder sb = new StringBuilder();
322 for (int i = 0; i < in.length(); i++) {
323 char ch = in.charAt(i);
324 if (ch < 32 || ch == '\'' || ch == '"') {
326 String hs = "0000" + Integer.toHexString(ch);
327 hs = hs.substring(hs.length() - 4);
333 return sb.toString();
337 public void shutdown() throws IOException {
340 int prev = methods.size();
342 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
345 } catch (InterruptedException ex) {
346 throw new IOException(ex);
348 if (prev == methods.size()) {
351 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
357 "Timeout, but tests got from {0} to {1}. Trying again.",
358 new Object[]{prev, methods.size()}
361 stopServerAndBrwsr(server, brwsr);
364 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
370 if (ch == '$' && params.length > 0) {
371 int cnt = is.read() - '0';
372 if (baseURL != null && cnt == 'U' - '0') {
373 os.write(baseURL.getBytes("UTF-8"));
375 if (cnt >= 0 && cnt < params.length) {
376 os.write(params[cnt].getBytes("UTF-8"));
388 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
390 URI uri = pageURL(server, page);
391 return showBrwsr(uri);
393 private static String toUTF8(String value) throws UnsupportedEncodingException {
394 byte[] arr = new byte[value.length()];
395 for (int i = 0; i < arr.length; i++) {
396 arr[i] = (byte)value.charAt(i);
398 return new String(arr, "UTF-8");
401 private static String decodeURL(String s) {
403 int pos = s.indexOf('%');
407 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
408 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
412 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
416 Process process = (Process)brwsr[0];
419 InputStream stdout = process.getInputStream();
420 InputStream stderr = process.getErrorStream();
421 drain("StdOut", stdout);
422 drain("StdErr", stderr);
426 res = process.waitFor();
427 } catch (InterruptedException ex) {
428 throw new IOException(ex);
430 LOG.log(Level.INFO, "Exit code: {0}", res);
432 deleteTree((File)brwsr[1]);
435 private static void drain(String name, InputStream is) throws IOException {
436 int av = is.available();
438 StringBuilder sb = new StringBuilder();
439 sb.append("v== ").append(name).append(" ==v\n");
441 sb.append((char)is.read());
443 sb.append("\n^== ").append(name).append(" ==^");
444 LOG.log(Level.INFO, sb.toString());
448 private void deleteTree(File file) {
452 File[] arr = file.listFiles();
462 public HttpServer call() throws Exception {
467 public void close() throws IOException {
471 protected Object[] showBrwsr(URI uri) throws IOException {
472 LOG.log(Level.INFO, "Showing {0}", uri);
475 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
476 System.getProperty("java.vm.name"),
477 System.getProperty("java.vm.vendor"),
478 System.getProperty("java.vm.version"),
480 java.awt.Desktop.getDesktop().browse(uri);
481 LOG.log(Level.INFO, "Desktop.browse successfully finished");
483 } catch (UnsupportedOperationException ex) {
484 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
485 LOG.log(Level.FINE, null, ex);
489 String cmdName = cmd == null ? "xdg-open" : cmd;
491 cmdName, uri.toString()
493 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
494 final Process process = Runtime.getRuntime().exec(cmdArr);
495 return new Object[] { process, null };
499 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
500 abstract String harnessResource();
502 private static URI pageURL(HttpServer server, final String page) {
503 NetworkListener listener = server.getListeners().iterator().next();
504 int port = listener.getPort();
506 return new URI("http://localhost:" + port + page);
507 } catch (URISyntaxException ex) {
508 throw new IllegalStateException(ex);
513 public InputStream get(String resource) throws IOException {
515 for (ClassLoader l : loaders) {
516 Enumeration<URL> en = l.getResources(resource);
517 while (en.hasMoreElements()) {
518 u = en.nextElement();
519 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
520 return u.openStream();
525 if (u.toExternalForm().contains("rt.jar")) {
526 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
528 return u.openStream();
530 throw new IOException("Can't find " + resource);
534 private static class Page extends HttpHandler {
535 final String resource;
536 private final String[] args;
537 private final Res res;
539 public Page(Res res, String resource, String... args) {
541 this.resource = resource;
542 this.args = args.length == 0 ? new String[] { "$0" } : args;
546 public void service(Request request, Response response) throws Exception {
547 String r = computePage(request);
548 if (r.startsWith("/")) {
551 String[] replace = {};
552 if (r.endsWith(".html")) {
553 response.setContentType("text/html");
554 LOG.info("Content type text/html");
557 if (r.endsWith(".xhtml")) {
558 response.setContentType("application/xhtml+xml");
559 LOG.info("Content type application/xhtml+xml");
562 OutputStream os = response.getOutputStream();
564 InputStream is = res.get(r);
565 copyStream(is, os, request.getRequestURL().toString(), replace);
566 } catch (IOException ex) {
567 response.setDetailMessage(ex.getLocalizedMessage());
569 response.setStatus(404);
573 protected String computePage(Request request) {
576 r = request.getHttpHandlerPath();
582 private static class SubTree extends Page {
584 public SubTree(Res res, String resource, String... args) {
585 super(res, resource, args);
589 protected String computePage(Request request) {
590 return resource + request.getHttpHandlerPath();
596 private class VM extends HttpHandler {
598 public void service(Request request, Response response) throws Exception {
599 response.setCharacterEncoding("UTF-8");
600 response.setContentType("text/javascript");
601 StringBuilder sb = new StringBuilder();
602 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
603 response.getWriter().write(sb.toString());
607 private static class Classes extends HttpHandler {
608 private final Res loader;
610 public Classes(Res loader) {
611 this.loader = loader;
615 public void service(Request request, Response response) throws Exception {
616 String res = request.getHttpHandlerPath();
617 if (res.startsWith("/")) {
618 res = res.substring(1);
620 InputStream is = null;
622 is = loader.get(res);
623 response.setContentType("text/javascript");
624 Writer w = response.getWriter();
626 for (int i = 0;; i++) {
640 w.append(Integer.toString(b));
643 } catch (IOException ex) {
644 response.setStatus(HttpStatus.NOT_FOUND_404);
646 response.setDetailMessage(ex.getMessage());