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);
151 String data = arr[0];
154 log("Some error exiting");
159 if (data.isEmpty()) {
160 log("No data, exiting");
165 c = Case.parseData(data);
167 log("Got \"" + data + "\"");
169 log("Processing \"" + arr[0] + "\" for " + retries + " time");
171 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
172 finishTest(c, result);
174 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
176 } catch (Exception ex) {
177 if (ex instanceof InterruptedException) {
178 log("Re-scheduling in 100ms");
179 schedule(new Run(this), 100);
182 log(ex.getClass().getName() + ":" + ex.getMessage());
187 private static String encodeURL(String r) throws UnsupportedEncodingException {
188 final String SPECIAL = "%$&+,/:;=?@";
189 StringBuilder sb = new StringBuilder();
190 byte[] utf8 = r.getBytes("UTF-8");
191 for (int i = 0; i < utf8.length; i++) {
192 int ch = utf8[i] & 0xff;
193 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
194 final String numbers = "0" + Integer.toHexString(ch);
195 sb.append("%").append(numbers.substring(numbers.length() - 2));
204 return sb.toString();
207 static String invoke(String clazz, String method) throws
208 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
209 InstantiationException, InterruptedException {
210 final Object r = new Case(null).invokeMethod(clazz, method);
211 return r == null ? "null" : r.toString().toString();
214 /** Helper method that inspects the classpath and loads given resource
215 * (usually a class file). Used while running tests in Rhino.
217 * @param name resource name to find
218 * @return the array of bytes in the given resource
219 * @throws IOException I/O in case something goes wrong
221 public static byte[] read(String name) throws IOException {
223 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
224 while (en.hasMoreElements()) {
225 u = en.nextElement();
228 throw new IOException("Can't find " + name);
230 InputStream is = null;
234 arr = new byte[is.available()];
236 while (offset < arr.length) {
237 int len = is.read(arr, offset, arr.length - offset);
239 throw new IOException("Can't read " + name);
245 if (is != null) is.close();
249 private static void turnAssetionStatusOn() {
252 @JavaScriptBody(args = { "r", "time" }, body = "return window.setTimeout(function() { r.run(); }, time);")
253 private static native Object schedule(Runnable r, int time);
255 private static final class Case {
256 private final Object data;
259 private Case(Object data) {
263 public static Case parseData(String s) {
264 return new Case(toJSON(s));
267 public String getMethodName() {
268 return (String) value("methodName", data);
271 public String getClassName() {
272 return (String) value("className", data);
275 public int getRequestId() {
276 Object v = value("request", data);
277 if (v instanceof Number) {
278 return ((Number)v).intValue();
280 return Integer.parseInt(v.toString());
283 public String getHtmlFragment() {
284 return (String) value("html", data);
287 void again(Object[] arr) {
291 setAttr(textArea, "value", "");
293 } catch (Exception ex) {
294 log(ex.getClass().getName() + ":" + ex.getMessage());
298 private Object runTest() throws IllegalAccessException,
299 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
300 InvocationTargetException, InstantiationException, InterruptedException {
301 if (this.getHtmlFragment() != null) {
302 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
304 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
305 Object result = invokeMethod(this.getClassName(), this.getMethodName());
306 setAttr("bck2brwsr.fragment", "innerHTML", "");
307 log("Result: " + result);
308 result = encodeURL("" + result);
309 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
313 private Object invokeMethod(String clazz, String method)
314 throws ClassNotFoundException, InvocationTargetException,
315 InterruptedException, IllegalAccessException, IllegalArgumentException,
316 InstantiationException {
318 Class<?> c = Class.forName(clazz);
319 for (Method m : c.getMethods()) {
320 if (m.getName().equals(method)) {
327 if ((found.getModifiers() & Modifier.STATIC) != 0) {
328 res = found.invoke(null);
331 inst = c.newInstance();
333 res = found.invoke(inst);
335 } catch (Throwable ex) {
336 if (ex instanceof InvocationTargetException) {
337 ex = ((InvocationTargetException) ex).getTargetException();
339 if (ex instanceof InterruptedException) {
340 throw (InterruptedException)ex;
342 res = ex.getClass().getName() + ":" + ex.getMessage();
345 res = "Can't find method " + method + " in " + clazz;
350 @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
351 private static native Object toJSON(String s);
353 private static Object value(String p, Object d) {
354 return ((JSObject)d).getMember(p);
359 turnAssetionStatusOn();