Can execute tests in FX web view.
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 {
39 private static final JSObject CObject;
41 @JavaScriptBody(args = {"elem", "attr"}, body =
42 "return elem[attr].toString();")
43 private static Object getAttr(Object elem, String attr) {
44 return CObject.call("getAttr", elem, attr);
47 @JavaScriptBody(args = {"id", "attr", "value"}, body =
48 "window.document.getElementById(id)[attr] = value;")
49 private static void setAttr(String id, String attr, Object value) {
50 CObject.call("setAttrId", id, attr, value);
52 @JavaScriptBody(args = {"elem", "attr", "value"}, body =
53 "elem[attr] = value;")
54 private static void setAttr(Object id, String attr, Object value) {
55 CObject.call("setAttr", id, attr, value);
58 @JavaScriptBody(args = {}, body = "return; window.close();")
59 private static void closeWindow() {}
61 private static Object textArea;
62 private static Object statusArea;
64 private static void log(String newText) {
65 if (textArea == null) {
68 String attr = "value";
69 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
70 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
73 private static void beginTest(Case c) {
74 Object[] arr = new Object[2];
75 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
80 private static void finishTest(Case c, Object res) {
81 if ("null".equals(res)) {
82 setAttr(statusArea, "innerHTML", "Success");
84 setAttr(statusArea, "innerHTML", "Result " + res);
90 private static final String BEGIN_TEST =
91 "var ul = window.document.getElementById('bck2brwsr.result');\n"
92 + "var li = window.document.createElement('li');\n"
93 + "var span = window.document.createElement('span');"
94 + "span.innerHTML = test + ' - ';\n"
95 + "var details = window.document.createElement('a');\n"
96 + "details.innerHTML = 'Details';\n"
97 + "details.href = '#';\n"
98 + "var p = window.document.createElement('p');\n"
99 + "var status = window.document.createElement('a');\n"
100 + "status.innerHTML = 'running';"
101 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
102 + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
103 + "var pre = window.document.createElement('textarea');\n"
106 + "li.appendChild(span);\n"
107 + "li.appendChild(status);\n"
108 + "var span = window.document.createElement('span');"
109 + "span.innerHTML = ' ';\n"
110 + "li.appendChild(span);\n"
111 + "li.appendChild(details);\n"
112 + "p.appendChild(pre);\n"
113 + "ul.appendChild(li);\n"
115 + "arr[1] = status;\n";
117 @JavaScriptBody(args = { "test", "c", "arr" }, body = BEGIN_TEST)
118 private static void beginTest(String test, Case c, Object[] arr) {
119 CObject.call("beginTest", test, c, arr);
122 private static final String LOAD_TEXT =
123 "var request = new XMLHttpRequest();\n"
124 + "request.open('GET', url, true);\n"
125 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
126 + "request.onreadystatechange = function() {\n"
127 + " if (this.readyState!==4) return;\n"
129 + " arr[0] = this.responseText;\n"
130 + " callback.run();\n"
131 + " } catch (e) { alert(e); }"
134 @JavaScriptBody(args = { "url", "callback", "arr" }, body = LOAD_TEXT)
135 private static void loadText(String url, Runnable callback, String[] arr) throws IOException {
136 CObject.call("loadText", url, new Run(callback), arr);
139 public void harness(String url) throws IOException {
140 log("Connecting to " + url);
141 Request r = new Request(url);
144 private static class Request implements Runnable {
145 private final String[] arr = { null };
146 private final String url;
150 private Request(String url) throws IOException {
152 loadText(url, this, arr);
154 private Request(String url, String u) throws IOException {
156 loadText(u, this, arr);
163 String data = arr[0];
166 log("Some error exiting");
171 if (data.isEmpty()) {
172 log("No data, exiting");
177 c = Case.parseData(data);
179 log("Got \"" + data + "\"");
181 log("Processing \"" + arr[0] + "\" for " + retries + " time");
183 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
184 finishTest(c, result);
186 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
188 } catch (Exception ex) {
189 if (ex instanceof InterruptedException) {
190 log("Re-scheduling in 100ms");
194 log(ex.getClass().getName() + ":" + ex.getMessage());
199 private static String encodeURL(String r) throws UnsupportedEncodingException {
200 final String SPECIAL = "%$&+,/:;=?@";
201 StringBuilder sb = new StringBuilder();
202 byte[] utf8 = r.getBytes("UTF-8");
203 for (int i = 0; i < utf8.length; i++) {
204 int ch = utf8[i] & 0xff;
205 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
206 final String numbers = "0" + Integer.toHexString(ch);
207 sb.append("%").append(numbers.substring(numbers.length() - 2));
216 return sb.toString();
219 static String invoke(String clazz, String method) throws
220 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
221 InstantiationException, InterruptedException {
222 final Object r = new Case(null).invokeMethod(clazz, method);
223 return r == null ? "null" : r.toString().toString();
226 /** Helper method that inspects the classpath and loads given resource
227 * (usually a class file). Used while running tests in Rhino.
229 * @param name resource name to find
230 * @return the array of bytes in the given resource
231 * @throws IOException I/O in case something goes wrong
233 public static byte[] read(String name) throws IOException {
235 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
236 while (en.hasMoreElements()) {
237 u = en.nextElement();
240 throw new IOException("Can't find " + name);
242 try (InputStream is = u.openStream()) {
244 arr = new byte[is.available()];
246 while (offset < arr.length) {
247 int len = is.read(arr, offset, arr.length - offset);
249 throw new IOException("Can't read " + name);
257 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
258 private static void turnAssetionStatusOn() {
261 @JavaScriptBody(args = {"r", "time"}, body =
262 "return window.setTimeout(function() { r.run__V(); }, time);")
263 private static Object schedule(Runnable r, int time) {
264 return CObject.call("schedule", new Run(r), time);
267 private static final class Case {
268 private final Object data;
271 private Case(Object data) {
275 public static Case parseData(String s) {
276 return new Case(toJSON(s));
279 public String getMethodName() {
280 return (String) value("methodName", data);
283 public String getClassName() {
284 return (String) value("className", data);
287 public int getRequestId() {
288 return (int) value("request", data);
291 public String getHtmlFragment() {
292 return (String) value("html", data);
295 void again(Object[] arr) {
299 setAttr(textArea, "value", "");
301 } catch (Exception ex) {
302 log(ex.getClass().getName() + ":" + ex.getMessage());
306 private Object runTest() throws IllegalAccessException,
307 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
308 InvocationTargetException, InstantiationException, InterruptedException {
309 if (this.getHtmlFragment() != null) {
310 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
312 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
313 Object result = invokeMethod(this.getClassName(), this.getMethodName());
314 setAttr("bck2brwsr.fragment", "innerHTML", "");
315 log("Result: " + result);
316 result = encodeURL("" + result);
317 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
321 private Object invokeMethod(String clazz, String method)
322 throws ClassNotFoundException, InvocationTargetException,
323 InterruptedException, IllegalAccessException, IllegalArgumentException,
324 InstantiationException {
326 Class<?> c = Class.forName(clazz);
327 for (Method m : c.getMethods()) {
328 if (m.getName().equals(method)) {
335 if ((found.getModifiers() & Modifier.STATIC) != 0) {
336 res = found.invoke(null);
339 inst = c.newInstance();
341 res = found.invoke(inst);
343 } catch (Throwable ex) {
344 if (ex instanceof InvocationTargetException) {
345 ex = ((InvocationTargetException) ex).getTargetException();
347 if (ex instanceof InterruptedException) {
348 throw (InterruptedException)ex;
350 res = ex.getClass().getName() + ":" + ex.getMessage();
353 res = "Can't find method " + method + " in " + clazz;
358 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
359 private static Object toJSON(String s) {
360 return CObject.call("toJSON", s);
363 @JavaScriptBody(args = {"p", "d"}, body =
365 + "if (typeof v === 'undefined') return null;\n"
366 + "return v.toString();"
368 private static Object value(String p, Object d) {
369 return ((JSObject)d).getMember(p);
373 private static String safe(String txt) {
374 return "try {" + txt + "} catch (err) { alert(err); }";
378 turnAssetionStatusOn();
380 WebEngine web = (WebEngine) System.getProperties().get("webEngine");
381 CObject = (JSObject) web.executeScript("(function() {"
382 + "var CObject = {};"
384 + "CObject.getAttr = function(elem, attr) { return elem[attr].toString(); };"
386 + "CObject.setAttrId = function(id, attr, value) { window.document.getElementById(id)[attr] = value; };"
387 + "CObject.setAttr = function(elem, attr, value) { elem[attr] = value; };"
389 + "CObject.beginTest = function(test, c, arr) {" + safe(BEGIN_TEST) + "};"
391 + "CObject.loadText = function(url, callback, arr) {" + safe(LOAD_TEXT) + "};"
393 + "CObject.schedule = function(r, time) { return window.setTimeout(function() { r.run(); }, time); };"
395 + "CObject.toJSON = function(s) { return eval('(' + s + ')'); };"