Can execute VMTest in browser, if it is annotated with @Exported annotation like the BooleanTest
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;
29 import java.net.JarURLConnection;
31 import java.net.URISyntaxException;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Enumeration;
36 import java.util.LinkedHashSet;
37 import java.util.List;
39 import java.util.concurrent.BlockingQueue;
40 import java.util.concurrent.Callable;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.LinkedBlockingQueue;
43 import java.util.concurrent.TimeUnit;
44 import java.util.jar.JarFile;
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;
59 * Lightweight server to launch Bck2Brwsr applications and tests.
60 * Supports execution in native browser as well as Java's internal
63 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
64 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
65 private static final InvocationContext END = new InvocationContext(null, null, null);
66 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
67 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<>();
69 private final Res resources = new Res();
70 private final String cmd;
71 private Object[] brwsr;
72 private HttpServer server;
73 private CountDownLatch wait;
75 public BaseHTTPLauncher(String cmd) {
77 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
82 InvocationContext runMethod(InvocationContext c) throws IOException {
83 loaders.add(c.clazz.getClassLoader());
87 } catch (InterruptedException ex) {
88 throw new IOException(ex);
93 public void setTimeout(long ms) {
97 public void addClassLoader(ClassLoader url) {
98 this.loaders.add(url);
101 ClassLoader[] loaders() {
102 return loaders.toArray(new ClassLoader[loaders.size()]);
105 public void showURL(String startpage) throws IOException {
106 if (!startpage.startsWith("/")) {
107 startpage = "/" + startpage;
109 HttpServer s = initServer(".", true);
110 int last = startpage.lastIndexOf('/');
111 String prefix = startpage.substring(0, last);
112 String simpleName = startpage.substring(last);
113 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
116 launchServerAndBrwsr(s, simpleName);
117 } catch (URISyntaxException | InterruptedException ex) {
118 throw new IOException(ex);
122 void showDirectory(File dir, String startpage) throws IOException {
123 if (!startpage.startsWith("/")) {
124 startpage = "/" + startpage;
126 HttpServer s = initServer(dir.getPath(), false);
128 launchServerAndBrwsr(s, startpage);
129 } catch (URISyntaxException | InterruptedException ex) {
130 throw new IOException(ex);
135 public void initialize() throws IOException {
138 } catch (InterruptedException ex) {
139 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
142 } catch (Exception ex) {
143 if (ex instanceof IOException) {
144 throw (IOException)ex;
146 if (ex instanceof RuntimeException) {
147 throw (RuntimeException)ex;
149 throw new IOException(ex);
153 private HttpServer initServer(String path, boolean addClasses) throws IOException {
154 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
156 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
157 setPoolName("Fx/Bck2 Brwsr").
160 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
161 setPoolName("Kernel Fx/Bck2").
164 for (NetworkListener nl : s.getListeners()) {
165 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
166 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
169 final ServerConfiguration conf = s.getServerConfiguration();
171 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
172 conf.addHttpHandler(new Classes(resources), "/classes/");
177 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
178 wait = new CountDownLatch(1);
179 server = initServer(".", true);
180 final ServerConfiguration conf = server.getServerConfiguration();
182 class DynamicResourceHandler extends HttpHandler {
183 private final InvocationContext ic;
184 public DynamicResourceHandler(InvocationContext ic) {
185 if (ic == null || ic.resources.isEmpty()) {
186 throw new NullPointerException();
189 for (Resource r : ic.resources) {
190 conf.addHttpHandler(this, r.httpPath);
194 public void close() {
195 conf.removeHttpHandler(this);
199 public void service(Request request, Response response) throws Exception {
200 for (Resource r : ic.resources) {
201 if (r.httpPath.equals(request.getRequestURI())) {
202 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
203 response.setContentType(r.httpType);
204 r.httpContent.reset();
205 String[] params = null;
206 if (r.parameters.length != 0) {
207 params = new String[r.parameters.length];
208 for (int i = 0; i < r.parameters.length; i++) {
209 params[i] = request.getParameter(r.parameters[i]);
210 if (params[i] == null) {
211 if ("http.method".equals(r.parameters[i])) {
212 params[i] = request.getMethod().toString();
213 } else if ("http.requestBody".equals(r.parameters[i])) {
214 Reader rdr = request.getReader();
215 StringBuilder sb = new StringBuilder();
223 params[i] = sb.toString();
226 if (params[i] == null) {
232 copyStream(r.httpContent, response.getOutputStream(), null, params);
238 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
240 conf.addHttpHandler(new HttpHandler() {
242 List<InvocationContext> cases = new ArrayList<>();
243 DynamicResourceHandler prev;
245 public void service(Request request, Response response) throws Exception {
246 String id = request.getParameter("request");
247 String value = request.getParameter("result");
248 if (value != null && value.indexOf((char)0xC5) != -1) {
249 value = toUTF8(value);
253 InvocationContext mi = null;
256 if (id != null && value != null) {
257 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
258 value = decodeURL(value);
259 int indx = Integer.parseInt(id);
260 cases.get(indx).result(value, null);
261 if (++indx < cases.size()) {
262 mi = cases.get(indx);
263 LOG.log(Level.INFO, "Re-executing case {0}", indx);
267 if (!cases.isEmpty()) {
268 LOG.info("Re-executing test cases");
284 response.getWriter().write("");
287 LOG.log(Level.INFO, "End of data reached. Exiting.");
291 if (!mi.resources.isEmpty()) {
292 prev = new DynamicResourceHandler(mi);
296 final String cn = mi.clazz.getName();
297 final String mn = mi.methodName;
298 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
299 response.getWriter().write("{"
300 + "className: '" + cn + "', "
301 + "methodName: '" + mn + "', "
302 + "request: " + caseNmbr
304 if (mi.html != null) {
305 response.getWriter().write(", html: '");
306 response.getWriter().write(encodeJSON(mi.html));
307 response.getWriter().write("'");
309 response.getWriter().write("}");
313 this.brwsr = launchServerAndBrwsr(server, "/execute");
316 private static String encodeJSON(String in) {
317 StringBuilder sb = new StringBuilder();
318 for (int i = 0; i < in.length(); i++) {
319 char ch = in.charAt(i);
320 if (ch < 32 || ch == '\'' || ch == '"') {
322 String hs = "0000" + Integer.toHexString(ch);
323 hs = hs.substring(hs.length() - 4);
329 return sb.toString();
333 public void shutdown() throws IOException {
336 int prev = methods.size();
338 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
341 } catch (InterruptedException ex) {
342 throw new IOException(ex);
344 if (prev == methods.size()) {
347 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
353 "Timeout, but tests got from {0} to {1}. Trying again.",
354 new Object[]{prev, methods.size()}
357 stopServerAndBrwsr(server, brwsr);
360 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
366 if (ch == '$' && params.length > 0) {
367 int cnt = is.read() - '0';
368 if (baseURL != null && cnt == 'U' - '0') {
369 os.write(baseURL.getBytes("UTF-8"));
371 if (cnt >= 0 && cnt < params.length) {
372 os.write(params[cnt].getBytes("UTF-8"));
384 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
386 NetworkListener listener = server.getListeners().iterator().next();
387 int port = listener.getPort();
389 URI uri = new URI("http://localhost:" + port + page);
390 return showBrwsr(uri);
392 private static String toUTF8(String value) throws UnsupportedEncodingException {
393 byte[] arr = new byte[value.length()];
394 for (int i = 0; i < arr.length; i++) {
395 arr[i] = (byte)value.charAt(i);
397 return new String(arr, "UTF-8");
400 private static String decodeURL(String s) {
402 int pos = s.indexOf('%');
406 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
407 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
411 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
415 Process process = (Process)brwsr[0];
418 InputStream stdout = process.getInputStream();
419 InputStream stderr = process.getErrorStream();
420 drain("StdOut", stdout);
421 drain("StdErr", stderr);
425 res = process.waitFor();
426 } catch (InterruptedException ex) {
427 throw new IOException(ex);
429 LOG.log(Level.INFO, "Exit code: {0}", res);
431 deleteTree((File)brwsr[1]);
434 private static void drain(String name, InputStream is) throws IOException {
435 int av = is.available();
437 StringBuilder sb = new StringBuilder();
438 sb.append("v== ").append(name).append(" ==v\n");
440 sb.append((char)is.read());
442 sb.append("\n^== ").append(name).append(" ==^");
443 LOG.log(Level.INFO, sb.toString());
447 private void deleteTree(File file) {
451 File[] arr = file.listFiles();
461 public HttpServer call() throws Exception {
466 public void close() throws IOException {
470 protected Object[] showBrwsr(URI uri) throws IOException {
471 LOG.log(Level.INFO, "Showing {0}", uri);
474 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
475 System.getProperty("java.vm.name"),
476 System.getProperty("java.vm.vendor"),
477 System.getProperty("java.vm.version"),
479 java.awt.Desktop.getDesktop().browse(uri);
480 LOG.log(Level.INFO, "Desktop.browse successfully finished");
482 } catch (UnsupportedOperationException ex) {
483 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
484 LOG.log(Level.FINE, null, ex);
488 String cmdName = cmd == null ? "xdg-open" : cmd;
490 cmdName, uri.toString()
492 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
493 final Process process = Runtime.getRuntime().exec(cmdArr);
494 return new Object[] { process, null };
498 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
499 abstract String harnessResource();
500 String compileJar(JarFile jar) throws IOException {
503 String compileFromClassPath(URL f) {
508 String compileJar(JarFile jar) throws IOException {
509 return BaseHTTPLauncher.this.compileJar(jar);
511 String compileFromClassPath(URL f) {
512 return BaseHTTPLauncher.this.compileFromClassPath(f);
514 public URL get(String resource) throws IOException {
516 for (ClassLoader l : loaders) {
517 Enumeration<URL> en = l.getResources(resource);
518 while (en.hasMoreElements()) {
519 u = en.nextElement();
520 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
526 if (u.toExternalForm().contains("rt.jar")) {
527 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
531 throw new IOException("Can't find " + resource);
535 private static class Page extends HttpHandler {
536 final String resource;
537 private final String[] args;
538 private final Res res;
540 public Page(Res res, String resource, String... args) {
542 this.resource = resource;
543 this.args = args.length == 0 ? new String[] { "$0" } : args;
547 public void service(Request request, Response response) throws Exception {
548 String r = computePage(request);
549 if (r.startsWith("/")) {
552 String[] replace = {};
553 if (r.endsWith(".html")) {
554 response.setContentType("text/html");
555 LOG.info("Content type text/html");
558 if (r.endsWith(".xhtml")) {
559 response.setContentType("application/xhtml+xml");
560 LOG.info("Content type application/xhtml+xml");
563 OutputStream os = response.getOutputStream();
564 try (InputStream is = res.get(r).openStream()) {
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 URL url = loader.get(res);
621 if (url.getProtocol().equals("jar")) {
622 JarURLConnection juc = (JarURLConnection) url.openConnection();
623 String s = loader.compileJar(juc.getJarFile());
625 Writer w = response.getWriter();
631 if (url.getProtocol().equals("file")) {
632 String s = loader.compileFromClassPath(url);
634 Writer w = response.getWriter();
640 Exception ex = new Exception("Won't server bytes of " + url);
642 try (InputStream is = url.openStream()) {
643 response.setContentType("text/javascript");
644 Writer w = response.getWriter();
646 for (int i = 0;; i++) {
660 w.append(Integer.toString(b));
663 } catch (IOException ex)
665 response.setStatus(HttpStatus.NOT_FOUND_404);
667 response.setDetailMessage(ex.getMessage());