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<>();
65 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
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 (URISyntaxException | InterruptedException 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 (URISyntaxException | InterruptedException 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 {
181 private final InvocationContext ic;
182 public DynamicResourceHandler(InvocationContext ic) {
183 if (ic == null || ic.resources.isEmpty()) {
184 throw new NullPointerException();
187 for (Resource r : ic.resources) {
188 conf.addHttpHandler(this, r.httpPath);
192 public void close() {
193 conf.removeHttpHandler(this);
197 public void service(Request request, Response response) throws Exception {
198 for (Resource r : ic.resources) {
199 if (r.httpPath.equals(request.getRequestURI())) {
200 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
201 response.setContentType(r.httpType);
202 r.httpContent.reset();
203 String[] params = null;
204 if (r.parameters.length != 0) {
205 params = new String[r.parameters.length];
206 for (int i = 0; i < r.parameters.length; i++) {
207 params[i] = request.getParameter(r.parameters[i]);
208 if (params[i] == null) {
209 if ("http.method".equals(r.parameters[i])) {
210 params[i] = request.getMethod().toString();
211 } else if ("http.requestBody".equals(r.parameters[i])) {
212 Reader rdr = request.getReader();
213 StringBuilder sb = new StringBuilder();
221 params[i] = sb.toString();
224 if (params[i] == null) {
230 copyStream(r.httpContent, response.getOutputStream(), null, params);
236 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
238 conf.addHttpHandler(new HttpHandler() {
240 List<InvocationContext> cases = new ArrayList<>();
241 DynamicResourceHandler prev;
243 public void service(Request request, Response response) throws Exception {
244 String id = request.getParameter("request");
245 String value = request.getParameter("result");
246 if (value != null && value.indexOf((char)0xC5) != -1) {
247 value = toUTF8(value);
251 InvocationContext mi = null;
254 if (id != null && value != null) {
255 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
256 value = decodeURL(value);
257 int indx = Integer.parseInt(id);
258 cases.get(indx).result(value, null);
259 if (++indx < cases.size()) {
260 mi = cases.get(indx);
261 LOG.log(Level.INFO, "Re-executing case {0}", indx);
265 if (!cases.isEmpty()) {
266 LOG.info("Re-executing test cases");
282 response.getWriter().write("");
285 LOG.log(Level.INFO, "End of data reached. Exiting.");
289 if (!mi.resources.isEmpty()) {
290 prev = new DynamicResourceHandler(mi);
294 final String cn = mi.clazz.getName();
295 final String mn = mi.methodName;
296 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
297 response.getWriter().write("{"
298 + "className: '" + cn + "', "
299 + "methodName: '" + mn + "', "
300 + "request: " + caseNmbr
302 if (mi.html != null) {
303 response.getWriter().write(", html: '");
304 response.getWriter().write(encodeJSON(mi.html));
305 response.getWriter().write("'");
307 response.getWriter().write("}");
311 this.brwsr = launchServerAndBrwsr(server, "/execute");
314 private static String encodeJSON(String in) {
315 StringBuilder sb = new StringBuilder();
316 for (int i = 0; i < in.length(); i++) {
317 char ch = in.charAt(i);
318 if (ch < 32 || ch == '\'' || ch == '"') {
320 String hs = "0000" + Integer.toHexString(ch);
321 hs = hs.substring(hs.length() - 4);
327 return sb.toString();
331 public void shutdown() throws IOException {
334 int prev = methods.size();
336 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
339 } catch (InterruptedException ex) {
340 throw new IOException(ex);
342 if (prev == methods.size()) {
345 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
351 "Timeout, but tests got from {0} to {1}. Trying again.",
352 new Object[]{prev, methods.size()}
355 stopServerAndBrwsr(server, brwsr);
358 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
364 if (ch == '$' && params.length > 0) {
365 int cnt = is.read() - '0';
366 if (baseURL != null && cnt == 'U' - '0') {
367 os.write(baseURL.getBytes("UTF-8"));
369 if (cnt >= 0 && cnt < params.length) {
370 os.write(params[cnt].getBytes("UTF-8"));
382 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
384 NetworkListener listener = server.getListeners().iterator().next();
385 int port = listener.getPort();
387 URI uri = new URI("http://localhost:" + port + page);
388 return showBrwsr(uri);
390 private static String toUTF8(String value) throws UnsupportedEncodingException {
391 byte[] arr = new byte[value.length()];
392 for (int i = 0; i < arr.length; i++) {
393 arr[i] = (byte)value.charAt(i);
395 return new String(arr, "UTF-8");
398 private static String decodeURL(String s) {
400 int pos = s.indexOf('%');
404 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
405 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
409 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
413 Process process = (Process)brwsr[0];
416 InputStream stdout = process.getInputStream();
417 InputStream stderr = process.getErrorStream();
418 drain("StdOut", stdout);
419 drain("StdErr", stderr);
423 res = process.waitFor();
424 } catch (InterruptedException ex) {
425 throw new IOException(ex);
427 LOG.log(Level.INFO, "Exit code: {0}", res);
429 deleteTree((File)brwsr[1]);
432 private static void drain(String name, InputStream is) throws IOException {
433 int av = is.available();
435 StringBuilder sb = new StringBuilder();
436 sb.append("v== ").append(name).append(" ==v\n");
438 sb.append((char)is.read());
440 sb.append("\n^== ").append(name).append(" ==^");
441 LOG.log(Level.INFO, sb.toString());
445 private void deleteTree(File file) {
449 File[] arr = file.listFiles();
459 public HttpServer call() throws Exception {
464 public void close() throws IOException {
468 protected Object[] showBrwsr(URI uri) throws IOException {
469 LOG.log(Level.INFO, "Showing {0}", uri);
472 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
473 System.getProperty("java.vm.name"),
474 System.getProperty("java.vm.vendor"),
475 System.getProperty("java.vm.version"),
477 java.awt.Desktop.getDesktop().browse(uri);
478 LOG.log(Level.INFO, "Desktop.browse successfully finished");
480 } catch (UnsupportedOperationException ex) {
481 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
482 LOG.log(Level.FINE, null, ex);
486 String cmdName = cmd == null ? "xdg-open" : cmd;
488 cmdName, uri.toString()
490 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
491 final Process process = Runtime.getRuntime().exec(cmdArr);
492 return new Object[] { process, null };
496 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
497 abstract String harnessResource();
500 public InputStream get(String resource) throws IOException {
502 for (ClassLoader l : loaders) {
503 Enumeration<URL> en = l.getResources(resource);
504 while (en.hasMoreElements()) {
505 u = en.nextElement();
506 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
507 return u.openStream();
512 if (u.toExternalForm().contains("rt.jar")) {
513 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
515 return u.openStream();
517 throw new IOException("Can't find " + resource);
521 private static class Page extends HttpHandler {
522 final String resource;
523 private final String[] args;
524 private final Res res;
526 public Page(Res res, String resource, String... args) {
528 this.resource = resource;
529 this.args = args.length == 0 ? new String[] { "$0" } : args;
533 public void service(Request request, Response response) throws Exception {
534 String r = computePage(request);
535 if (r.startsWith("/")) {
538 String[] replace = {};
539 if (r.endsWith(".html")) {
540 response.setContentType("text/html");
541 LOG.info("Content type text/html");
544 if (r.endsWith(".xhtml")) {
545 response.setContentType("application/xhtml+xml");
546 LOG.info("Content type application/xhtml+xml");
549 OutputStream os = response.getOutputStream();
550 try (InputStream is = res.get(r)) {
551 copyStream(is, os, request.getRequestURL().toString(), replace);
552 } catch (IOException ex) {
553 response.setDetailMessage(ex.getLocalizedMessage());
555 response.setStatus(404);
559 protected String computePage(Request request) {
562 r = request.getHttpHandlerPath();
568 private static class SubTree extends Page {
570 public SubTree(Res res, String resource, String... args) {
571 super(res, resource, args);
575 protected String computePage(Request request) {
576 return resource + request.getHttpHandlerPath();
582 private class VM extends HttpHandler {
584 public void service(Request request, Response response) throws Exception {
585 response.setCharacterEncoding("UTF-8");
586 response.setContentType("text/javascript");
587 StringBuilder sb = new StringBuilder();
588 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
589 response.getWriter().write(sb.toString());
593 private static class Classes extends HttpHandler {
594 private final Res loader;
596 public Classes(Res loader) {
597 this.loader = loader;
601 public void service(Request request, Response response) throws Exception {
602 String res = request.getHttpHandlerPath();
603 if (res.startsWith("/")) {
604 res = res.substring(1);
606 try (InputStream is = loader.get(res)) {
607 response.setContentType("text/javascript");
608 Writer w = response.getWriter();
610 for (int i = 0;; i++) {
624 w.append(Integer.toString(b));
627 } catch (IOException ex) {
628 response.setStatus(HttpStatus.NOT_FOUND_404);
630 response.setDetailMessage(ex.getMessage());