Execution time reported by TestNG reflect the time it took to run the query inside of a browser
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;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InterruptedIOException;
24 import java.io.OutputStream;
25 import java.io.Writer;
27 import java.net.URISyntaxException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Enumeration;
32 import java.util.LinkedHashSet;
33 import java.util.List;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.LinkedBlockingQueue;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import org.apidesign.vm4brwsr.Bck2Brwsr;
42 import org.glassfish.grizzly.PortRange;
43 import org.glassfish.grizzly.http.server.HttpHandler;
44 import org.glassfish.grizzly.http.server.HttpServer;
45 import org.glassfish.grizzly.http.server.NetworkListener;
46 import org.glassfish.grizzly.http.server.Request;
47 import org.glassfish.grizzly.http.server.Response;
48 import org.glassfish.grizzly.http.server.ServerConfiguration;
51 * Lightweight server to launch Bck2Brwsr applications and tests.
52 * Supports execution in native browser as well as Java's internal
55 public class Bck2BrwsrLauncher {
56 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
57 private static final MethodInvocation END = new MethodInvocation(null, null);
58 private Set<ClassLoader> loaders = new LinkedHashSet<>();
59 private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
61 private final Res resources = new Res();
62 private Object[] brwsr;
63 private HttpServer server;
64 private CountDownLatch wait;
67 public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
68 loaders.add(clazz.getClassLoader());
69 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
73 } catch (InterruptedException ex) {
74 throw new IOException(ex);
79 public void setTimeout(long ms) {
83 public void addClassLoader(ClassLoader url) {
84 this.loaders.add(url);
87 public static void main( String[] args ) throws Exception {
88 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher();
89 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
90 l.showURL("org/apidesign/bck2brwsr/launcher/console.xhtml");
94 public void showURL(String startpage) throws URISyntaxException, InterruptedException, IOException {
95 if (!startpage.startsWith("/")) {
96 startpage = "/" + startpage;
98 HttpServer s = initServer();
99 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
100 launchServerAndBrwsr(s, startpage);
103 public void initialize() throws IOException {
106 } catch (InterruptedException ex) {
107 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
110 } catch (Exception ex) {
111 if (ex instanceof IOException) {
112 throw (IOException)ex;
114 if (ex instanceof RuntimeException) {
115 throw (RuntimeException)ex;
117 throw new IOException(ex);
121 private HttpServer initServer() {
122 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
124 final ServerConfiguration conf = s.getServerConfiguration();
125 conf.addHttpHandler(new Page(resources,
126 "org/apidesign/bck2brwsr/launcher/console.xhtml",
127 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
129 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
130 conf.addHttpHandler(new VMInit(), "/vm.js");
131 conf.addHttpHandler(new Classes(resources), "/classes/");
135 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
136 wait = new CountDownLatch(1);
137 server = initServer();
138 ServerConfiguration conf = server.getServerConfiguration();
139 conf.addHttpHandler(new Page(resources,
140 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
142 conf.addHttpHandler(new HttpHandler() {
144 List<MethodInvocation> cases = new ArrayList<>();
146 public void service(Request request, Response response) throws Exception {
147 String id = request.getParameter("request");
148 String value = request.getParameter("result");
150 if (id != null && value != null) {
151 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
152 value = value.replace("%20", " ");
153 cases.get(Integer.parseInt(id)).result(value, null);
156 MethodInvocation mi = methods.take();
158 response.getWriter().write("");
161 LOG.log(Level.INFO, "End of data reached. Exiting.");
166 final String cn = mi.className;
167 final String mn = mi.methodName;
168 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
169 response.getWriter().write("{"
170 + "className: '" + cn + "', "
171 + "methodName: '" + mn + "', "
178 this.brwsr = launchServerAndBrwsr(server, "/execute");
181 public void shutdown() throws InterruptedException, IOException {
184 int prev = methods.size();
185 if (wait.await(timeOut, TimeUnit.MILLISECONDS)) {
188 if (prev == methods.size()) {
191 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
197 "Timeout, but tests got from {0} to {1}. Trying again.",
198 new Object[]{prev, methods.size()}
201 stopServerAndBrwsr(server, brwsr);
204 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
211 int cnt = is.read() - '0';
212 if (cnt == 'U' - '0') {
213 os.write(baseURL.getBytes());
215 if (cnt < params.length) {
216 os.write(params[cnt].getBytes());
224 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
226 NetworkListener listener = server.getListeners().iterator().next();
227 int port = listener.getPort();
229 URI uri = new URI("http://localhost:" + port + page);
230 LOG.log(Level.INFO, "Showing {0}", uri);
232 // Desktop.getDesktop().browse(uri);
234 // } catch (UnsupportedOperationException ex)
236 // File dir = File.createTempFile("chrome", ".dir");
240 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
242 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
243 // final Process process = Runtime.getRuntime().exec(cmd);
244 // return new Object[] { process, dir };
248 "xdg-open", uri.toString()
250 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
251 final Process process = Runtime.getRuntime().exec(cmd);
252 return new Object[] { process, null };
256 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException, InterruptedException {
257 Process process = (Process)brwsr[0];
260 InputStream stdout = process.getInputStream();
261 InputStream stderr = process.getErrorStream();
262 drain("StdOut", stdout);
263 drain("StdErr", stderr);
265 int res = process.waitFor();
266 LOG.log(Level.INFO, "Exit code: {0}", res);
268 deleteTree((File)brwsr[1]);
271 private static void drain(String name, InputStream is) throws IOException {
272 int av = is.available();
274 StringBuilder sb = new StringBuilder();
275 sb.append("v== ").append(name).append(" ==v\n");
277 sb.append((char)is.read());
279 sb.append("\n^== ").append(name).append(" ==^");
280 LOG.log(Level.INFO, sb.toString());
284 private void deleteTree(File file) {
288 File[] arr = file.listFiles();
297 private class Res implements Bck2Brwsr.Resources {
299 public InputStream get(String resource) throws IOException {
300 for (ClassLoader l : loaders) {
302 Enumeration<URL> en = l.getResources(resource);
303 while (en.hasMoreElements()) {
304 u = en.nextElement();
307 return u.openStream();
310 throw new IOException("Can't find " + resource);
314 private static class Page extends HttpHandler {
315 private final String resource;
316 private final String[] args;
317 private final Res res;
319 public Page(Res res, String resource, String... args) {
321 this.resource = resource;
326 public void service(Request request, Response response) throws Exception {
329 r = request.getHttpHandlerPath();
330 if (r.startsWith("/")) {
334 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
335 response.setContentType("text/html");
337 OutputStream os = response.getOutputStream();
338 try (InputStream is = res.get(r)) {
339 copyStream(is, os, request.getRequestURL().toString(), args);
340 } catch (IOException ex) {
341 response.setDetailMessage(ex.getLocalizedMessage());
343 response.setStatus(404);
348 private static class VM extends HttpHandler {
349 private final Res loader;
351 public VM(Res loader) {
352 this.loader = loader;
356 public void service(Request request, Response response) throws Exception {
357 response.setCharacterEncoding("UTF-8");
358 response.setContentType("text/javascript");
359 Bck2Brwsr.generate(response.getWriter(), loader);
362 private static class VMInit extends HttpHandler {
367 public void service(Request request, Response response) throws Exception {
368 response.setCharacterEncoding("UTF-8");
369 response.setContentType("text/javascript");
370 response.getWriter().append(
371 "function ldCls(res) {\n"
372 + " var request = new XMLHttpRequest();\n"
373 + " request.open('GET', '/classes/' + res, false);\n"
374 + " request.send();\n"
375 + " var arr = eval('(' + request.responseText + ')');\n"
378 + "var vm = new bck2brwsr(ldCls);\n");
382 private static class Classes extends HttpHandler {
383 private final Res loader;
385 public Classes(Res loader) {
386 this.loader = loader;
390 public void service(Request request, Response response) throws Exception {
391 String res = request.getHttpHandlerPath();
392 if (res.startsWith("/")) {
393 res = res.substring(1);
395 try (InputStream is = loader.get(res)) {
396 response.setContentType("text/javascript");
397 Writer w = response.getWriter();
399 for (int i = 0;; i++) {
413 w.append(Integer.toString(b));
416 } catch (IOException ex) {
418 response.setDetailMessage(ex.getMessage());