Can execute 'dual' tests: bck2brwsr can use regular launcher, javaquery.api can use FX Web View one
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.impl;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.UnsupportedEncodingException;
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.lang.reflect.Modifier;
27 import java.util.Enumeration;
28 import javafx.scene.web.WebEngine;
29 import netscape.javascript.JSObject;
30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
34 * @author Jaroslav Tulach <jtulach@netbeans.org>
36 public final class Console {
40 @JavaScriptBody(args = {"elem", "attr"}, body =
41 "return elem[attr].toString();")
42 private static Object getAttr(Object elem, String attr) {
43 return InvokeJS.CObject.call("getAttr", elem, attr);
46 @JavaScriptBody(args = {"id", "attr", "value"}, body =
47 "window.document.getElementById(id)[attr] = value;")
48 private static void setAttr(String id, String attr, Object value) {
49 InvokeJS.CObject.call("setAttrId", id, attr, value);
51 @JavaScriptBody(args = {"elem", "attr", "value"}, body =
52 "elem[attr] = value;")
53 private static void setAttr(Object id, String attr, Object value) {
54 InvokeJS.CObject.call("setAttr", id, attr, value);
57 @JavaScriptBody(args = {}, body = "return; window.close();")
58 private static void closeWindow() {}
60 private static Object textArea;
61 private static Object statusArea;
63 private static void log(String newText) {
64 if (textArea == null) {
67 String attr = "value";
68 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
69 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
72 private static void beginTest(Case c) {
73 Object[] arr = new Object[2];
74 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
79 private static void finishTest(Case c, Object res) {
80 if ("null".equals(res)) {
81 setAttr(statusArea, "innerHTML", "Success");
83 setAttr(statusArea, "innerHTML", "Result " + res);
89 private static final String BEGIN_TEST =
90 "var ul = window.document.getElementById('bck2brwsr.result');\n"
91 + "var li = window.document.createElement('li');\n"
92 + "var span = window.document.createElement('span');"
93 + "span.innerHTML = test + ' - ';\n"
94 + "var details = window.document.createElement('a');\n"
95 + "details.innerHTML = 'Details';\n"
96 + "details.href = '#';\n"
97 + "var p = window.document.createElement('p');\n"
98 + "var status = window.document.createElement('a');\n"
99 + "status.innerHTML = 'running';"
100 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
101 + "status.onclick = function() { c.again(arr); }\n"
102 + "var pre = window.document.createElement('textarea');\n"
105 + "li.appendChild(span);\n"
106 + "li.appendChild(status);\n"
107 + "var span = window.document.createElement('span');"
108 + "span.innerHTML = ' ';\n"
109 + "li.appendChild(span);\n"
110 + "li.appendChild(details);\n"
111 + "p.appendChild(pre);\n"
112 + "ul.appendChild(li);\n"
114 + "arr[1] = status;\n";
116 @JavaScriptBody(args = { "test", "c", "arr" }, body = BEGIN_TEST)
117 private static void beginTest(String test, Case c, Object[] arr) {
118 InvokeJS.CObject.call("beginTest", test, c, arr);
121 private static final String LOAD_TEXT =
122 "var request = new XMLHttpRequest();\n"
123 + "request.open('GET', url, true);\n"
124 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
125 + "request.onreadystatechange = function() {\n"
126 + " if (this.readyState!==4) return;\n"
128 + " arr[0] = this.responseText;\n"
129 + " callback.run__V();\n"
130 + " } catch (e) { alert(e); }"
133 @JavaScriptBody(args = { "url", "callback", "arr" }, body = LOAD_TEXT)
134 private static void loadText(String url, Runnable callback, String[] arr) throws IOException {
135 InvokeJS.CObject.call("loadText", url, new Run(callback), arr);
138 public static void runHarness(String url) throws IOException {
139 new Console().harness(url);
142 public void harness(String url) throws IOException {
143 log("Connecting to " + url);
144 Request r = new Request(url);
147 private static class Request implements Runnable {
148 private final String[] arr = { null };
149 private final String url;
153 private Request(String url) throws IOException {
155 loadText(url, this, arr);
157 private Request(String url, String u) throws IOException {
159 loadText(u, this, arr);
166 String data = arr[0];
169 log("Some error exiting");
174 if (data.isEmpty()) {
175 log("No data, exiting");
180 c = Case.parseData(data);
182 log("Got \"" + data + "\"");
184 log("Processing \"" + arr[0] + "\" for " + retries + " time");
186 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
187 finishTest(c, result);
189 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
191 } catch (Exception ex) {
192 if (ex instanceof InterruptedException) {
193 log("Re-scheduling in 100ms");
197 log(ex.getClass().getName() + ":" + ex.getMessage());
202 private static String encodeURL(String r) throws UnsupportedEncodingException {
203 final String SPECIAL = "%$&+,/:;=?@";
204 StringBuilder sb = new StringBuilder();
205 byte[] utf8 = r.getBytes("UTF-8");
206 for (int i = 0; i < utf8.length; i++) {
207 int ch = utf8[i] & 0xff;
208 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
209 final String numbers = "0" + Integer.toHexString(ch);
210 sb.append("%").append(numbers.substring(numbers.length() - 2));
219 return sb.toString();
222 static String invoke(String clazz, String method) throws
223 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
224 InstantiationException, InterruptedException {
225 final Object r = new Case(null).invokeMethod(clazz, method);
226 return r == null ? "null" : r.toString().toString();
229 /** Helper method that inspects the classpath and loads given resource
230 * (usually a class file). Used while running tests in Rhino.
232 * @param name resource name to find
233 * @return the array of bytes in the given resource
234 * @throws IOException I/O in case something goes wrong
236 public static byte[] read(String name) throws IOException {
238 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
239 while (en.hasMoreElements()) {
240 u = en.nextElement();
243 throw new IOException("Can't find " + name);
245 try (InputStream is = u.openStream()) {
247 arr = new byte[is.available()];
249 while (offset < arr.length) {
250 int len = is.read(arr, offset, arr.length - offset);
252 throw new IOException("Can't read " + name);
260 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
261 private static void turnAssetionStatusOn() {
264 @JavaScriptBody(args = {"r", "time"}, body =
265 "return window.setTimeout(function() { r.run__V(); }, time);")
266 private static Object schedule(Runnable r, int time) {
267 return InvokeJS.CObject.call("schedule", new Run(r), time);
270 private static final class Case {
271 private final Object data;
274 private Case(Object data) {
278 public static Case parseData(String s) {
279 return new Case(toJSON(s));
282 public String getMethodName() {
283 return (String) value("methodName", data);
286 public String getClassName() {
287 return (String) value("className", data);
290 public int getRequestId() {
291 Object v = value("request", data);
292 if (v instanceof Number) {
293 return ((Number)v).intValue();
295 return Integer.parseInt(v.toString());
298 public String getHtmlFragment() {
299 return (String) value("html", data);
302 void again(Object[] arr) {
306 setAttr(textArea, "value", "");
308 } catch (Exception ex) {
309 log(ex.getClass().getName() + ":" + ex.getMessage());
313 private Object runTest() throws IllegalAccessException,
314 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
315 InvocationTargetException, InstantiationException, InterruptedException {
316 if (this.getHtmlFragment() != null) {
317 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
319 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
320 Object result = invokeMethod(this.getClassName(), this.getMethodName());
321 setAttr("bck2brwsr.fragment", "innerHTML", "");
322 log("Result: " + result);
323 result = encodeURL("" + result);
324 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
328 private Object invokeMethod(String clazz, String method)
329 throws ClassNotFoundException, InvocationTargetException,
330 InterruptedException, IllegalAccessException, IllegalArgumentException,
331 InstantiationException {
333 Class<?> c = Class.forName(clazz);
334 for (Method m : c.getMethods()) {
335 if (m.getName().equals(method)) {
342 if ((found.getModifiers() & Modifier.STATIC) != 0) {
343 res = found.invoke(null);
346 inst = c.newInstance();
348 res = found.invoke(inst);
350 } catch (Throwable ex) {
351 if (ex instanceof InvocationTargetException) {
352 ex = ((InvocationTargetException) ex).getTargetException();
354 if (ex instanceof InterruptedException) {
355 throw (InterruptedException)ex;
357 res = ex.getClass().getName() + ":" + ex.getMessage();
360 res = "Can't find method " + method + " in " + clazz;
365 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
366 private static Object toJSON(String s) {
367 return InvokeJS.CObject.call("toJSON", s);
370 @JavaScriptBody(args = {"p", "d"}, body =
372 + "if (typeof v === 'undefined') return null;\n"
373 + "return v.toString();"
375 private static Object value(String p, Object d) {
376 return ((JSObject)d).getMember(p);
380 private static String safe(String txt) {
381 return "try {" + txt + "} catch (err) { alert(err); }";
385 turnAssetionStatusOn();
388 private static final class InvokeJS {
389 static final JSObject CObject = initJS();
391 @JavaScriptBody(args = { }, body = "return null;")
392 private static JSObject initJS() {
393 WebEngine web = (WebEngine) System.getProperties().get("webEngine");
394 return (JSObject) web.executeScript("(function() {"
395 + "var CObject = {};"
397 + "CObject.getAttr = function(elem, attr) { return elem[attr].toString(); };"
399 + "CObject.setAttrId = function(id, attr, value) { window.document.getElementById(id)[attr] = value; };"
400 + "CObject.setAttr = function(elem, attr, value) { elem[attr] = value; };"
402 + "CObject.beginTest = function(test, c, arr) {" + safe(BEGIN_TEST) + "};"
404 + "CObject.loadText = function(url, callback, arr) {" + safe(LOAD_TEXT.replace("run__V", "run")) + "};"
406 + "CObject.schedule = function(r, time) { return window.setTimeout(function() { r.run(); }, time); };"
408 + "CObject.toJSON = function(s) { return eval('(' + s + ')'); };"