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;
135 private Request(String url) throws IOException {
137 loadText(url, this, arr);
139 private Request(String url, String u) throws IOException {
141 loadText(u, this, arr);
148 String data = arr[0];
151 log("Some error exiting");
156 if (data.isEmpty()) {
157 log("No data, exiting");
162 c = Case.parseData(data);
164 log("Got \"" + data + "\"");
166 log("Processing \"" + arr[0] + "\" for " + retries + " time");
168 Object result = retries++ >= 10 ? "java.lang.InterruptedException:timeout" : c.runTest();
169 finishTest(c, result);
171 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
173 } catch (Exception ex) {
174 if (ex instanceof InterruptedException) {
175 log("Re-scheduling in 100ms");
179 log(ex.getClass().getName() + ":" + ex.getMessage());
184 private static String encodeURL(String r) throws UnsupportedEncodingException {
185 final String SPECIAL = "%$&+,/:;=?@";
186 StringBuilder sb = new StringBuilder();
187 byte[] utf8 = r.getBytes("UTF-8");
188 for (int i = 0; i < utf8.length; i++) {
189 int ch = utf8[i] & 0xff;
190 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
191 final String numbers = "0" + Integer.toHexString(ch);
192 sb.append("%").append(numbers.substring(numbers.length() - 2));
201 return sb.toString();
204 static String invoke(String clazz, String method) throws
205 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
206 InstantiationException, InterruptedException {
207 final Object r = new Case(null).invokeMethod(clazz, method);
208 return r == null ? "null" : r.toString().toString();
211 /** Helper method that inspects the classpath and loads given resource
212 * (usually a class file). Used while running tests in Rhino.
214 * @param name resource name to find
215 * @return the array of bytes in the given resource
216 * @throws IOException I/O in case something goes wrong
218 public static byte[] read(String name) throws IOException {
220 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
221 while (en.hasMoreElements()) {
222 u = en.nextElement();
225 throw new IOException("Can't find " + name);
227 try (InputStream is = u.openStream()) {
229 arr = new byte[is.available()];
231 while (offset < arr.length) {
232 int len = is.read(arr, offset, arr.length - offset);
234 throw new IOException("Can't read " + name);
242 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
243 private static void turnAssetionStatusOn() {
246 @JavaScriptBody(args = {"r", "time"}, body =
247 "return window.setTimeout(function() { r.run__V(); }, time);")
248 private static native Object schedule(Runnable r, int time);
250 private static final class Case {
251 private final Object data;
254 private Case(Object data) {
258 public static Case parseData(String s) {
259 return new Case(toJSON(s));
262 public String getMethodName() {
263 return value("methodName", data);
266 public String getClassName() {
267 return value("className", data);
270 public String getRequestId() {
271 return value("request", data);
274 public String getHtmlFragment() {
275 return value("html", data);
278 void again(Object[] arr) {
282 setAttr(textArea, "value", "");
284 } catch (Exception ex) {
285 log(ex.getClass().getName() + ":" + ex.getMessage());
289 private Object runTest() throws IllegalAccessException,
290 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
291 InvocationTargetException, InstantiationException, InterruptedException {
292 if (this.getHtmlFragment() != null) {
293 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
295 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
296 Object result = invokeMethod(this.getClassName(), this.getMethodName());
297 setAttr("bck2brwsr.fragment", "innerHTML", "");
298 log("Result: " + result);
299 result = encodeURL("" + result);
300 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
304 private Object invokeMethod(String clazz, String method)
305 throws ClassNotFoundException, InvocationTargetException,
306 InterruptedException, IllegalAccessException, IllegalArgumentException,
307 InstantiationException {
309 Class<?> c = Class.forName(clazz);
310 for (Method m : c.getMethods()) {
311 if (m.getName().equals(method)) {
318 if ((found.getModifiers() & Modifier.STATIC) != 0) {
319 res = found.invoke(null);
322 inst = c.newInstance();
324 res = found.invoke(inst);
326 } catch (Throwable ex) {
327 if (ex instanceof InvocationTargetException) {
328 ex = ((InvocationTargetException) ex).getTargetException();
330 if (ex instanceof InterruptedException) {
331 throw (InterruptedException)ex;
333 res = ex.getClass().getName() + ":" + ex.getMessage();
336 res = "Can't find method " + method + " in " + clazz;
341 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
342 private static native Object toJSON(String s);
344 @JavaScriptBody(args = {"p", "d"}, body =
346 + "if (typeof v === 'undefined') return null;\n"
347 + "return v.toString();"
349 private static native String value(String p, Object d);