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 public static void execute() throws Exception {
112 String clazz = (String) getAttr("clazz", "value");
113 String method = (String) getAttr("method", "value");
114 Object res = invokeMethod(clazz, method);
115 setAttr("bck2brwsr.result", "value", res);
118 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
119 + "var request = new XMLHttpRequest();\n"
120 + "request.open('GET', url, true);\n"
121 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
122 + "request.onreadystatechange = function() {\n"
123 + " if (this.readyState!==4) return;\n"
124 + " arr[0] = this.responseText;\n"
125 + " callback.run__V();\n"
129 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
131 public static void harness(String url) throws IOException {
132 log("Connecting to " + url);
133 Request r = new Request(url);
136 private static class Request implements Runnable {
137 private final String[] arr = { null };
138 private final String url;
140 private Request(String url) throws IOException {
142 loadText(url, this, arr);
148 String data = arr[0];
149 log("\nGot \"" + data + "\"");
152 log("Some error exiting");
157 if (data.isEmpty()) {
158 log("No data, exiting");
163 Case c = Case.parseData(data);
165 Object result = c.runTest();
166 finishTest(c, result);
167 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
169 loadText(u, this, arr);
171 } catch (Exception ex) {
172 log(ex.getClass().getName() + ":" + ex.getMessage());
177 private static String encodeURL(String r) throws UnsupportedEncodingException {
178 final String SPECIAL = "%$&+,/:;=?@";
179 StringBuilder sb = new StringBuilder();
180 byte[] utf8 = r.getBytes("UTF-8");
181 for (int i = 0; i < utf8.length; i++) {
182 int ch = utf8[i] & 0xff;
183 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
184 final String numbers = "0" + Integer.toHexString(ch);
185 sb.append("%").append(numbers.substring(numbers.length() - 2));
194 return sb.toString();
197 static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
198 final Object r = invokeMethod(clazz, method);
199 return r == null ? "null" : r.toString().toString();
202 /** Helper method that inspects the classpath and loads given resource
203 * (usually a class file). Used while running tests in Rhino.
205 * @param name resource name to find
206 * @return the array of bytes in the given resource
207 * @throws IOException I/O in case something goes wrong
209 public static byte[] read(String name) throws IOException {
211 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
212 while (en.hasMoreElements()) {
213 u = en.nextElement();
216 throw new IOException("Can't find " + name);
218 try (InputStream is = u.openStream()) {
220 arr = new byte[is.available()];
222 while (offset < arr.length) {
223 int len = is.read(arr, offset, arr.length - offset);
225 throw new IOException("Can't read " + name);
233 private static Object invokeMethod(String clazz, String method)
234 throws ClassNotFoundException, InvocationTargetException,
235 SecurityException, IllegalAccessException, IllegalArgumentException,
236 InstantiationException {
238 Class<?> c = Class.forName(clazz);
239 for (Method m : c.getMethods()) {
240 if (m.getName().equals(method)) {
247 if ((found.getModifiers() & Modifier.STATIC) != 0) {
248 res = found.invoke(null);
250 res = found.invoke(c.newInstance());
252 } catch (Throwable ex) {
253 res = ex.getClass().getName() + ":" + ex.getMessage();
256 res = "Can't find method " + method + " in " + clazz;
261 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
262 private static void turnAssetionStatusOn() {
265 private static final class Case {
266 private final Object data;
268 private Case(Object data) {
272 public static Case parseData(String s) {
273 return new Case(toJSON(s));
276 public String getMethodName() {
277 return value("methodName", data);
280 public String getClassName() {
281 return value("className", data);
284 public String getRequestId() {
285 return value("request", data);
288 public String getHtmlFragment() {
289 return value("html", data);
292 void again(Object[] arr) {
296 setAttr(textArea, "value", "");
298 } catch (Exception ex) {
299 log(ex.getClass().getName() + ":" + ex.getMessage());
303 private Object runTest() throws IllegalAccessException, IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException, InvocationTargetException, InstantiationException, SecurityException {
304 if (this.getHtmlFragment() != null) {
305 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
307 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
308 Object result = invokeMethod(this.getClassName(), this.getMethodName());
309 setAttr("bck2brwsr.fragment", "innerHTML", "");
310 log("Result: " + result);
311 result = encodeURL("" + result);
312 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
316 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
317 private static native Object toJSON(String s);
319 @JavaScriptBody(args = {"p", "d"}, body =
321 + "if (typeof v === 'undefined') return null;\n"
322 + "return v.toString();"
324 private static native String value(String p, Object d);