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.BufferedReader;
21 import java.io.ByteArrayInputStream;
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.Method;
50 import org.glassfish.grizzly.http.server.HttpHandler;
51 import org.glassfish.grizzly.http.server.HttpServer;
52 import org.glassfish.grizzly.http.server.NetworkListener;
53 import org.glassfish.grizzly.http.server.Request;
54 import org.glassfish.grizzly.http.server.Response;
55 import org.glassfish.grizzly.http.server.ServerConfiguration;
56 import org.glassfish.grizzly.http.util.HttpStatus;
57 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
60 * Lightweight server to launch Bck2Brwsr applications and tests.
61 * Supports execution in native browser as well as Java's internal
64 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
65 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
66 private static final InvocationContext END = new InvocationContext(null, null, null);
67 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
68 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
70 private final Res resources = new Res();
71 private final String cmd;
72 private Object[] brwsr;
73 private HttpServer server;
74 private CountDownLatch wait;
76 public BaseHTTPLauncher(String cmd) {
78 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
83 InvocationContext runMethod(InvocationContext c) throws IOException {
84 loaders.add(c.clazz.getClassLoader());
88 } catch (InterruptedException ex) {
89 throw new IOException(ex);
94 public void setTimeout(long ms) {
98 public void addClassLoader(ClassLoader url) {
99 this.loaders.add(url);
102 ClassLoader[] loaders() {
103 return loaders.toArray(new ClassLoader[loaders.size()]);
106 public void showURL(String startpage) throws IOException {
107 if (!startpage.startsWith("/")) {
108 startpage = "/" + startpage;
110 HttpServer s = initServer(".", true);
111 int last = startpage.lastIndexOf('/');
112 String prefix = startpage.substring(0, last);
113 String simpleName = startpage.substring(last);
114 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
117 launchServerAndBrwsr(s, simpleName);
118 } catch (Exception ex) {
119 throw new IOException(ex);
123 void showDirectory(File dir, String startpage) throws IOException {
124 if (!startpage.startsWith("/")) {
125 startpage = "/" + startpage;
127 HttpServer s = initServer(dir.getPath(), false);
129 launchServerAndBrwsr(s, startpage);
130 } catch (Exception ex) {
131 throw new IOException(ex);
136 public void initialize() throws IOException {
139 } catch (InterruptedException ex) {
140 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
143 } catch (Exception ex) {
144 if (ex instanceof IOException) {
145 throw (IOException)ex;
147 if (ex instanceof RuntimeException) {
148 throw (RuntimeException)ex;
150 throw new IOException(ex);
154 private HttpServer initServer(String path, boolean addClasses) throws IOException {
155 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
157 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
158 setPoolName("Fx/Bck2 Brwsr").
161 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
162 setPoolName("Kernel Fx/Bck2").
165 for (NetworkListener nl : s.getListeners()) {
166 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
167 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
170 final ServerConfiguration conf = s.getServerConfiguration();
172 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
173 conf.addHttpHandler(new Classes(resources), "/classes/");
178 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
179 wait = new CountDownLatch(1);
180 server = initServer(".", true);
181 final ServerConfiguration conf = server.getServerConfiguration();
183 class DynamicResourceHandler extends HttpHandler {
184 private final InvocationContext ic;
185 private int resourcesCount;
186 public DynamicResourceHandler(InvocationContext ic) {
188 for (Resource r : ic.resources) {
189 conf.addHttpHandler(this, r.httpPath);
193 public void close() {
194 conf.removeHttpHandler(this);
198 public void service(Request request, Response response) throws Exception {
199 if ("/dynamic".equals(request.getRequestURI())) {
200 String mimeType = request.getParameter("mimeType");
201 List<String> params = new ArrayList<String>();
202 for (int i = 0; ; i++) {
203 String p = request.getParameter("param" + i);
209 final String cnt = request.getParameter("content");
210 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
211 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
212 URI url = registerResource(new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()])));
213 response.getWriter().write(url.toString());
214 response.getWriter().write("\n");
218 for (Resource r : ic.resources) {
219 if (r.httpPath.equals(request.getRequestURI())) {
220 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
221 response.setContentType(r.httpType);
222 r.httpContent.reset();
223 String[] params = null;
224 if (r.parameters.length != 0) {
225 params = new String[r.parameters.length];
226 for (int i = 0; i < r.parameters.length; i++) {
227 params[i] = request.getParameter(r.parameters[i]);
228 if (params[i] == null) {
229 if ("http.method".equals(r.parameters[i])) {
230 params[i] = request.getMethod().toString();
231 } else if ("http.requestBody".equals(r.parameters[i])) {
232 Reader rdr = request.getReader();
233 StringBuilder sb = new StringBuilder();
241 params[i] = sb.toString();
244 if (params[i] == null) {
250 copyStream(r.httpContent, response.getOutputStream(), null, params);
255 private URI registerResource(Resource r) {
256 if (!ic.resources.contains(r)) {
258 conf.addHttpHandler(this, r.httpPath);
260 return pageURL(server, r.httpPath);
264 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
266 conf.addHttpHandler(new HttpHandler() {
268 List<InvocationContext> cases = new ArrayList<InvocationContext>();
269 DynamicResourceHandler prev;
271 public void service(Request request, Response response) throws Exception {
272 String id = request.getParameter("request");
273 String value = request.getParameter("result");
274 if (value != null && value.indexOf((char)0xC5) != -1) {
275 value = toUTF8(value);
279 InvocationContext mi = null;
282 if (id != null && value != null) {
283 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
284 value = decodeURL(value);
285 int indx = Integer.parseInt(id);
286 cases.get(indx).result(value, null);
287 if (++indx < cases.size()) {
288 mi = cases.get(indx);
289 LOG.log(Level.INFO, "Re-executing case {0}", indx);
293 if (!cases.isEmpty()) {
294 LOG.info("Re-executing test cases");
310 response.getWriter().write("");
313 LOG.log(Level.INFO, "End of data reached. Exiting.");
317 prev = new DynamicResourceHandler(mi);
318 conf.addHttpHandler(prev, "/dynamic");
321 final String cn = mi.clazz.getName();
322 final String mn = mi.methodName;
323 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
324 response.getWriter().write("{"
325 + "className: '" + cn + "', "
326 + "methodName: '" + mn + "', "
327 + "request: " + caseNmbr
329 if (mi.html != null) {
330 response.getWriter().write(", html: '");
331 response.getWriter().write(encodeJSON(mi.html));
332 response.getWriter().write("'");
334 response.getWriter().write("}");
338 this.brwsr = launchServerAndBrwsr(server, "/execute");
341 private static String encodeJSON(String in) {
342 StringBuilder sb = new StringBuilder();
343 for (int i = 0; i < in.length(); i++) {
344 char ch = in.charAt(i);
345 if (ch < 32 || ch == '\'' || ch == '"') {
347 String hs = "0000" + Integer.toHexString(ch);
348 hs = hs.substring(hs.length() - 4);
354 return sb.toString();
358 public void shutdown() throws IOException {
361 int prev = methods.size();
363 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
366 } catch (InterruptedException ex) {
367 throw new IOException(ex);
369 if (prev == methods.size()) {
372 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
378 "Timeout, but tests got from {0} to {1}. Trying again.",
379 new Object[]{prev, methods.size()}
382 stopServerAndBrwsr(server, brwsr);
385 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
391 if (ch == '$' && params.length > 0) {
392 int cnt = is.read() - '0';
393 if (baseURL != null && cnt == 'U' - '0') {
394 os.write(baseURL.getBytes("UTF-8"));
396 if (cnt >= 0 && cnt < params.length) {
397 os.write(params[cnt].getBytes("UTF-8"));
409 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
411 URI uri = pageURL(server, page);
412 return showBrwsr(uri);
414 private static String toUTF8(String value) throws UnsupportedEncodingException {
415 byte[] arr = new byte[value.length()];
416 for (int i = 0; i < arr.length; i++) {
417 arr[i] = (byte)value.charAt(i);
419 return new String(arr, "UTF-8");
422 private static String decodeURL(String s) {
424 int pos = s.indexOf('%');
428 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
429 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
433 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
437 Process process = (Process)brwsr[0];
440 InputStream stdout = process.getInputStream();
441 InputStream stderr = process.getErrorStream();
442 drain("StdOut", stdout);
443 drain("StdErr", stderr);
447 res = process.waitFor();
448 } catch (InterruptedException ex) {
449 throw new IOException(ex);
451 LOG.log(Level.INFO, "Exit code: {0}", res);
453 deleteTree((File)brwsr[1]);
456 private static void drain(String name, InputStream is) throws IOException {
457 int av = is.available();
459 StringBuilder sb = new StringBuilder();
460 sb.append("v== ").append(name).append(" ==v\n");
462 sb.append((char)is.read());
464 sb.append("\n^== ").append(name).append(" ==^");
465 LOG.log(Level.INFO, sb.toString());
469 private void deleteTree(File file) {
473 File[] arr = file.listFiles();
483 public HttpServer call() throws Exception {
488 public void close() throws IOException {
492 protected Object[] showBrwsr(URI uri) throws IOException {
493 LOG.log(Level.INFO, "Showing {0}", uri);
496 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
497 System.getProperty("java.vm.name"),
498 System.getProperty("java.vm.vendor"),
499 System.getProperty("java.vm.version"),
501 java.awt.Desktop.getDesktop().browse(uri);
502 LOG.log(Level.INFO, "Desktop.browse successfully finished");
504 } catch (UnsupportedOperationException ex) {
505 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
506 LOG.log(Level.FINE, null, ex);
510 String cmdName = cmd == null ? "xdg-open" : cmd;
512 cmdName, uri.toString()
514 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
515 final Process process = Runtime.getRuntime().exec(cmdArr);
516 return new Object[] { process, null };
520 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
521 abstract String harnessResource();
523 private static URI pageURL(HttpServer server, final String page) {
524 NetworkListener listener = server.getListeners().iterator().next();
525 int port = listener.getPort();
527 return new URI("http://localhost:" + port + page);
528 } catch (URISyntaxException ex) {
529 throw new IllegalStateException(ex);
534 public InputStream get(String resource) throws IOException {
536 for (ClassLoader l : loaders) {
537 Enumeration<URL> en = l.getResources(resource);
538 while (en.hasMoreElements()) {
539 u = en.nextElement();
540 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
541 return u.openStream();
546 if (u.toExternalForm().contains("rt.jar")) {
547 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
549 return u.openStream();
551 throw new IOException("Can't find " + resource);
555 private static class Page extends HttpHandler {
556 final String resource;
557 private final String[] args;
558 private final Res res;
560 public Page(Res res, String resource, String... args) {
562 this.resource = resource;
563 this.args = args.length == 0 ? new String[] { "$0" } : args;
567 public void service(Request request, Response response) throws Exception {
568 String r = computePage(request);
569 if (r.startsWith("/")) {
572 String[] replace = {};
573 if (r.endsWith(".html")) {
574 response.setContentType("text/html");
575 LOG.info("Content type text/html");
578 if (r.endsWith(".xhtml")) {
579 response.setContentType("application/xhtml+xml");
580 LOG.info("Content type application/xhtml+xml");
583 OutputStream os = response.getOutputStream();
585 InputStream is = res.get(r);
586 copyStream(is, os, request.getRequestURL().toString(), replace);
587 } catch (IOException ex) {
588 response.setDetailMessage(ex.getLocalizedMessage());
590 response.setStatus(404);
594 protected String computePage(Request request) {
597 r = request.getHttpHandlerPath();
603 private static class SubTree extends Page {
605 public SubTree(Res res, String resource, String... args) {
606 super(res, resource, args);
610 protected String computePage(Request request) {
611 return resource + request.getHttpHandlerPath();
617 private class VM extends HttpHandler {
619 public void service(Request request, Response response) throws Exception {
620 response.setCharacterEncoding("UTF-8");
621 response.setContentType("text/javascript");
622 StringBuilder sb = new StringBuilder();
623 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
624 response.getWriter().write(sb.toString());
628 private static class Classes extends HttpHandler {
629 private final Res loader;
631 public Classes(Res loader) {
632 this.loader = loader;
636 public void service(Request request, Response response) throws Exception {
637 String res = request.getHttpHandlerPath();
638 if (res.startsWith("/")) {
639 res = res.substring(1);
641 InputStream is = null;
643 is = loader.get(res);
644 response.setContentType("text/javascript");
645 Writer w = response.getWriter();
647 for (int i = 0;; i++) {
661 w.append(Integer.toString(b));
664 } catch (IOException ex) {
665 response.setStatus(HttpStatus.NOT_FOUND_404);
667 response.setDetailMessage(ex.getMessage());