First updates to run with forthcoming version 0.5 - WebSockets in FX launcher and etc.
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.fximpl;
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 netscape.javascript.JSObject;
29 import org.apidesign.bck2brwsr.core.JavaScriptBody;
33 * @author Jaroslav Tulach <jtulach@netbeans.org>
35 public final class Console {
39 @JavaScriptBody(args = { "elem", "attr" }, body = "return elem[attr].toString();")
40 private static native Object getAttr(Object elem, String attr);
42 @JavaScriptBody(args = { "id", "attr", "value" }, body = "window.document.getElementById(id)[attr] = value;")
43 private static native void setAttr(String id, String attr, Object value);
45 @JavaScriptBody(args = { "elem", "attr", "value" }, body = "elem[attr] = value;")
46 private static native void setAttr(Object id, String attr, Object value);
48 private static void closeWindow() {}
50 private static Object textArea;
51 private static Object statusArea;
53 private static void log(String newText) {
54 if (textArea == null) {
57 String attr = "value";
58 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
59 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
62 private static void beginTest(Case c) {
63 Object[] arr = new Object[2];
64 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
69 private static void finishTest(Case c, Object res) {
70 if ("null".equals(res)) {
71 setAttr(statusArea, "innerHTML", "Success");
73 setAttr(statusArea, "innerHTML", "Result " + res);
79 @JavaScriptBody(args = { "test", "c", "arr" }, body =
80 "var ul = window.document.getElementById('bck2brwsr.result');\n"
81 + "var li = window.document.createElement('li');\n"
82 + "var span = window.document.createElement('span');"
83 + "span.innerHTML = test + ' - ';\n"
84 + "var details = window.document.createElement('a');\n"
85 + "details.innerHTML = 'Details';\n"
86 + "details.href = '#';\n"
87 + "var p = window.document.createElement('p');\n"
88 + "var status = window.document.createElement('a');\n"
89 + "status.innerHTML = 'running';"
90 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
91 + "status.onclick = function() { c.again(arr); }\n"
92 + "var pre = window.document.createElement('textarea');\n"
95 + "li.appendChild(span);\n"
96 + "li.appendChild(status);\n"
97 + "var span = window.document.createElement('span');"
98 + "span.innerHTML = ' ';\n"
99 + "li.appendChild(span);\n"
100 + "li.appendChild(details);\n"
101 + "p.appendChild(pre);\n"
102 + "ul.appendChild(li);\n"
104 + "arr[1] = status;\n"
106 private static native void beginTest(String test, Case c, Object[] arr);
108 @JavaScriptBody(args = { "url", "callback", "arr" }, body =
109 "var request = new XMLHttpRequest();\n"
110 + "request.open('GET', url, true);\n"
111 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
112 + "request.onreadystatechange = function() {\n"
113 + " if (this.readyState!==4) return;\n"
115 + " arr[0] = this.responseText;\n"
116 + " callback.run();\n"
117 + " } catch (e) { alert(e); }\n"
119 + "request.send();\n"
121 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
123 public static void runHarness(String url) throws IOException {
124 new Console().harness(url);
127 public void harness(String url) throws IOException {
128 log("Connecting to " + url);
129 Request r = new Request(url);
132 private static class Request implements Runnable {
133 private final String[] arr = { null };
134 private final String url;
138 private Request(String url) throws IOException {
140 loadText(url, new Run(this), arr);
142 private Request(String url, String u) throws IOException {
144 loadText(u, new Run(this), arr);
149 Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
152 String data = arr[0];
155 log("Some error exiting");
160 if (data.isEmpty()) {
161 log("No data, exiting");
166 c = Case.parseData(data);
168 log("Got \"" + data + "\"");
170 log("Processing \"" + arr[0] + "\" for " + retries + " time");
172 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
173 finishTest(c, result);
175 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
177 } catch (Exception ex) {
178 if (ex instanceof InterruptedException) {
179 log("Re-scheduling in 100ms");
180 schedule(new Run(this), 100);
183 log(ex.getClass().getName() + ":" + ex.getMessage());
188 private static String encodeURL(String r) throws UnsupportedEncodingException {
189 final String SPECIAL = "%$&+,/:;=?@";
190 StringBuilder sb = new StringBuilder();
191 byte[] utf8 = r.getBytes("UTF-8");
192 for (int i = 0; i < utf8.length; i++) {
193 int ch = utf8[i] & 0xff;
194 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
195 final String numbers = "0" + Integer.toHexString(ch);
196 sb.append("%").append(numbers.substring(numbers.length() - 2));
205 return sb.toString();
208 static String invoke(String clazz, String method) throws
209 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
210 InstantiationException, InterruptedException {
211 final Object r = new Case(null).invokeMethod(clazz, method);
212 return r == null ? "null" : r.toString().toString();
215 /** Helper method that inspects the classpath and loads given resource
216 * (usually a class file). Used while running tests in Rhino.
218 * @param name resource name to find
219 * @return the array of bytes in the given resource
220 * @throws IOException I/O in case something goes wrong
222 public static byte[] read(String name) throws IOException {
224 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
225 while (en.hasMoreElements()) {
226 u = en.nextElement();
229 throw new IOException("Can't find " + name);
231 InputStream is = null;
235 arr = new byte[is.available()];
237 while (offset < arr.length) {
238 int len = is.read(arr, offset, arr.length - offset);
240 throw new IOException("Can't read " + name);
246 if (is != null) is.close();
250 private static void turnAssetionStatusOn() {
253 @JavaScriptBody(args = { "r", "time" }, body = "return window.setTimeout(function() { r.run(); }, time);")
254 private static native Object schedule(Runnable r, int time);
256 private static final class Case {
257 private final Object data;
260 private Case(Object data) {
264 public static Case parseData(String s) {
265 return new Case(toJSON(s));
268 public String getMethodName() {
269 return (String) value("methodName", data);
272 public String getClassName() {
273 return (String) value("className", data);
276 public int getRequestId() {
277 Object v = value("request", data);
278 if (v instanceof Number) {
279 return ((Number)v).intValue();
281 return Integer.parseInt(v.toString());
284 public String getHtmlFragment() {
285 return (String) value("html", data);
288 void again(Object[] arr) {
292 setAttr(textArea, "value", "");
294 } catch (Exception ex) {
295 log(ex.getClass().getName() + ":" + ex.getMessage());
299 private Object runTest() throws IllegalAccessException,
300 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
301 InvocationTargetException, InstantiationException, InterruptedException {
302 if (this.getHtmlFragment() != null) {
303 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
305 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
306 Object result = invokeMethod(this.getClassName(), this.getMethodName());
307 setAttr("bck2brwsr.fragment", "innerHTML", "");
308 log("Result: " + result);
309 result = encodeURL("" + result);
310 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
314 private Object invokeMethod(String clazz, String method)
315 throws ClassNotFoundException, InvocationTargetException,
316 InterruptedException, IllegalAccessException, IllegalArgumentException,
317 InstantiationException {
319 Class<?> c = Class.forName(clazz);
320 for (Method m : c.getMethods()) {
321 if (m.getName().equals(method)) {
328 if ((found.getModifiers() & Modifier.STATIC) != 0) {
329 res = found.invoke(null);
332 inst = c.newInstance();
334 res = found.invoke(inst);
336 } catch (Throwable ex) {
337 if (ex instanceof InvocationTargetException) {
338 ex = ((InvocationTargetException) ex).getTargetException();
340 if (ex instanceof InterruptedException) {
341 throw (InterruptedException)ex;
343 res = ex.getClass().getName() + ":" + ex.getMessage();
346 res = "Can't find method " + method + " in " + clazz;
351 @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
352 private static native Object toJSON(String s);
354 private static Object value(String p, Object d) {
355 return ((JSObject)d).getMember(p);
360 turnAssetionStatusOn();