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 org.apidesign.bck2brwsr.core.JavaScriptBody;
32 * @author Jaroslav Tulach <jtulach@netbeans.org>
34 public class Console {
38 turnAssetionStatusOn();
41 @JavaScriptBody(args = {"id", "attr"}, body =
42 "return window.document.getElementById(id)[attr].toString();")
43 private static native Object getAttr(String id, String attr);
44 @JavaScriptBody(args = {"elem", "attr"}, body =
45 "return elem[attr].toString();")
46 private static native Object getAttr(Object elem, String attr);
48 @JavaScriptBody(args = {"id", "attr", "value"}, body =
49 "window.document.getElementById(id)[attr] = value;")
50 private static native void setAttr(String id, String attr, Object value);
51 @JavaScriptBody(args = {"elem", "attr", "value"}, body =
52 "elem[attr] = value;")
53 private static native void setAttr(Object id, String attr, Object value);
55 @JavaScriptBody(args = {}, body = "return; window.close();")
56 private static native void closeWindow();
58 private static Object textArea;
59 private static Object statusArea;
61 private static void log(String newText) {
62 if (textArea == null) {
65 String attr = "value";
66 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
67 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
70 private static void beginTest(Case c) {
71 Object[] arr = new Object[2];
72 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
77 private static void finishTest(Case c, Object res) {
78 if ("null".equals(res)) {
79 setAttr(statusArea, "innerHTML", "OK");
80 setAttr(statusArea, "href", null);
82 setAttr(statusArea, "innerHTML", "run again");
88 @JavaScriptBody(args = { "test", "c", "arr" }, body =
89 "var ul = window.document.getElementById('bck2brwsr.result');\n"
90 + "var li = window.document.createElement('li');\n"
91 + "var span = window.document.createElement('span');\n"
92 + "span.innerHTML = test + ' - ';\n"
93 + "var p = window.document.createElement('p');\n"
94 + "var status = window.document.createElement('a');\n"
95 + "status.innerHTML = 'running';"
96 + "status.href = '#';\n"
97 + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
98 + "var pre = window.document.createElement('textarea');\n"
99 + "pre.width = '90%';"
100 + "pre.height = 100;"
101 + "li.appendChild(span);\n"
102 + "li.appendChild(status);\n"
103 + "li.appendChild(p);\n"
104 + "p.appendChild(pre);\n"
105 + "ul.appendChild(li);\n"
107 + "arr[1] = status;\n"
109 private static native void beginTest(String test, Case c, Object[] arr);
111 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
112 + "var request = new XMLHttpRequest();\n"
113 + "request.open('GET', url, true);\n"
114 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
115 + "request.onreadystatechange = function() {\n"
116 + " if (this.readyState!==4) return;\n"
117 + " arr[0] = this.responseText;\n"
118 + " callback.run__V();\n"
122 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
124 public static void harness(String url) throws IOException {
125 log("Connecting to " + url);
126 Request r = new Request(url);
129 private static class Request implements Runnable {
130 private final String[] arr = { null };
131 private final String url;
134 private Request(String url) throws IOException {
136 loadText(url, this, arr);
138 private Request(String url, String u) throws IOException {
140 loadText(u, this, arr);
147 String data = arr[0];
148 log("\nGot \"" + data + "\"");
151 log("Some error exiting");
156 if (data.isEmpty()) {
157 log("No data, exiting");
162 c = Case.parseData(data);
165 Object result = c.runTest();
166 finishTest(c, result);
168 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
170 } catch (Exception ex) {
171 if (ex instanceof InterruptedException) {
175 log(ex.getClass().getName() + ":" + ex.getMessage());
180 private static String encodeURL(String r) throws UnsupportedEncodingException {
181 final String SPECIAL = "%$&+,/:;=?@";
182 StringBuilder sb = new StringBuilder();
183 byte[] utf8 = r.getBytes("UTF-8");
184 for (int i = 0; i < utf8.length; i++) {
185 int ch = utf8[i] & 0xff;
186 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
187 final String numbers = "0" + Integer.toHexString(ch);
188 sb.append("%").append(numbers.substring(numbers.length() - 2));
197 return sb.toString();
200 static String invoke(String clazz, String method) throws
201 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
202 InstantiationException, InterruptedException {
203 final Object r = new Case(null).invokeMethod(clazz, method);
204 return r == null ? "null" : r.toString().toString();
207 /** Helper method that inspects the classpath and loads given resource
208 * (usually a class file). Used while running tests in Rhino.
210 * @param name resource name to find
211 * @return the array of bytes in the given resource
212 * @throws IOException I/O in case something goes wrong
214 public static byte[] read(String name) throws IOException {
216 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
217 while (en.hasMoreElements()) {
218 u = en.nextElement();
221 throw new IOException("Can't find " + name);
223 try (InputStream is = u.openStream()) {
225 arr = new byte[is.available()];
227 while (offset < arr.length) {
228 int len = is.read(arr, offset, arr.length - offset);
230 throw new IOException("Can't read " + name);
238 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
239 private static void turnAssetionStatusOn() {
242 @JavaScriptBody(args = {"r", "time"}, body =
243 "return window.setInterval(function() { r.run__V(); }, time);")
244 private static native Object interval(Runnable r, int time);
246 private static final class Case {
247 private final Object data;
250 private Case(Object data) {
254 public static Case parseData(String s) {
255 return new Case(toJSON(s));
258 public String getMethodName() {
259 return value("methodName", data);
262 public String getClassName() {
263 return value("className", data);
266 public String getRequestId() {
267 return value("request", data);
270 public String getHtmlFragment() {
271 return value("html", data);
274 void again(Object[] arr) {
278 setAttr(textArea, "value", "");
280 } catch (Exception ex) {
281 log(ex.getClass().getName() + ":" + ex.getMessage());
285 private Object runTest() throws IllegalAccessException,
286 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
287 InvocationTargetException, InstantiationException, InterruptedException {
288 if (this.getHtmlFragment() != null) {
289 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
291 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
292 Object result = invokeMethod(this.getClassName(), this.getMethodName());
293 setAttr("bck2brwsr.fragment", "innerHTML", "");
294 log("Result: " + result);
295 result = encodeURL("" + result);
296 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
300 private Object invokeMethod(String clazz, String method)
301 throws ClassNotFoundException, InvocationTargetException,
302 InterruptedException, IllegalAccessException, IllegalArgumentException,
303 InstantiationException {
305 Class<?> c = Class.forName(clazz);
306 for (Method m : c.getMethods()) {
307 if (m.getName().equals(method)) {
314 if ((found.getModifiers() & Modifier.STATIC) != 0) {
315 res = found.invoke(null);
318 inst = c.newInstance();
320 res = found.invoke(inst);
322 } catch (Throwable ex) {
323 if (ex instanceof InvocationTargetException) {
324 ex = ((InvocationTargetException) ex).getTargetException();
326 if (ex instanceof InterruptedException) {
327 throw (InterruptedException)ex;
329 res = ex.getClass().getName() + ":" + ex.getMessage();
332 res = "Can't find method " + method + " in " + clazz;
337 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
338 private static native Object toJSON(String s);
340 @JavaScriptBody(args = {"p", "d"}, body =
342 + "if (typeof v === 'undefined') return null;\n"
343 + "return v.toString();"
345 private static native String value(String p, Object d);