2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 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 net.java.html.js.JavaScriptBody;
29 import netscape.javascript.JSObject;
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 = "\n"
43 + "var e = window.document.getElementById(id);\n"
44 + "if (e) e[attr] = value;\n"
46 private static native void setAttr(String id, String attr, Object value);
48 @JavaScriptBody(args = { "elem", "attr", "value" }, body = "elem[attr] = value;")
49 private static native void setAttr(Object elem, String attr, Object value);
51 @JavaScriptBody(args = {}, body = "return new Date().getTime()")
52 private static native double getTime();
54 private static void closeWindow() {}
56 private static Object textArea;
57 private static Object statusArea;
59 private static void log(String newText) {
60 if (textArea == null) {
63 String attr = "value";
64 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
65 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
68 private static void beginTest(Case c) {
69 Object[] arr = beginTest(c.getClassName() + "." + c.getMethodName(), c, new Object[2]);
74 private static void finishTest(Case c, Object res) {
75 if ("null".equals(res)) {
76 setAttr(statusArea, "innerHTML", "Success");
78 setAttr(statusArea, "innerHTML", "Result " + res);
84 @JavaScriptBody(args = { "test", "c", "arr" }, body =
85 "var ul = window.document.getElementById('bck2brwsr.result');\n"
86 + "var li = window.document.createElement('li');\n"
87 + "var span = window.document.createElement('span');"
88 + "span.innerHTML = test + ' - ';\n"
89 + "var details = window.document.createElement('a');\n"
90 + "details.innerHTML = 'Details';\n"
91 + "details.href = '#';\n"
92 + "var p = window.document.createElement('p');\n"
93 + "var status = window.document.createElement('a');\n"
94 + "status.innerHTML = 'running';"
95 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
96 + "status.onclick = function() { c.again(arr); }\n"
97 + "var pre = window.document.createElement('textarea');\n"
100 + "li.appendChild(span);\n"
101 + "li.appendChild(status);\n"
102 + "var span = window.document.createElement('span');"
103 + "span.innerHTML = ' ';\n"
104 + "li.appendChild(span);\n"
105 + "li.appendChild(details);\n"
106 + "p.appendChild(pre);\n"
107 + "if (ul) ul.appendChild(li);\n"
109 + "arr[1] = status;\n"
112 private static native Object[] beginTest(String test, Case c, Object[] arr);
114 @JavaScriptBody(args = { "url", "callback" }, javacall = true, body =
115 "var request = new XMLHttpRequest();\n"
116 + "request.open('GET', url, true);\n"
117 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
118 + "request.onreadystatechange = function() {\n"
119 + " if (this.readyState!==4) return;\n"
121 + " callback.@org.apidesign.bck2brwsr.launcher.fximpl.OnMessage::onMessage(Ljava/lang/String;)(this.responseText);\n"
122 + " } catch (e) { alert(e); }\n"
124 + "request.send();\n"
126 private static native void loadText(String url, OnMessage callback) throws IOException;
128 public static void runHarness(String url) throws IOException {
129 new Console().harness(url);
132 public void harness(String url) throws IOException {
133 log("Connecting to " + url);
134 Request r = new Request(url);
137 private static class Request implements Runnable, OnMessage {
138 private final String[] arr = { null };
139 private final String url;
143 private Request(String url) throws IOException {
147 private Request(String url, String u) throws IOException {
153 public void onMessage(String msg) {
160 Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
163 String data = arr[0];
166 log("Some error exiting");
171 if (data.isEmpty()) {
172 log("No data, exiting");
177 c = Case.parseData(data);
179 log("Got \"" + data + "\"");
181 log("Processing \"" + arr[0] + "\" for " + retries + " time");
183 Object result = retries++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
184 String reply = "?request=" + c.getRequestId() + "&time=" + c.time + "&result=" + result;
185 log("Sending back: ..." + reply);
186 finishTest(c, result);
188 String u = url + reply;
190 } catch (Exception ex) {
191 if (ex instanceof InterruptedException) {
192 log("Re-scheduling in 100ms");
196 log(ex.getClass().getName() + ":" + ex.getMessage());
201 private static String encodeURL(String r) throws UnsupportedEncodingException {
202 final String SPECIAL = "%$&+,/:;=?@";
203 StringBuilder sb = new StringBuilder();
204 byte[] utf8 = r.getBytes("UTF-8");
205 for (int i = 0; i < utf8.length; i++) {
206 int ch = utf8[i] & 0xff;
207 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
208 final String numbers = "0" + Integer.toHexString(ch);
209 sb.append("%").append(numbers.substring(numbers.length() - 2));
218 return sb.toString();
221 static String invoke(String clazz, String method) throws
222 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
223 InstantiationException, InterruptedException {
224 final Object r = new Case(null).invokeMethod(clazz, method);
225 return r == null ? "null" : r.toString().toString();
228 /** Helper method that inspects the classpath and loads given resource
229 * (usually a class file). Used while running tests in Rhino.
231 * @param name resource name to find
232 * @return the array of bytes in the given resource
233 * @throws IOException I/O in case something goes wrong
235 public static byte[] read(String name) throws IOException {
237 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
238 while (en.hasMoreElements()) {
239 u = en.nextElement();
242 throw new IOException("Can't find " + name);
244 InputStream is = null;
248 arr = new byte[is.available()];
250 while (offset < arr.length) {
251 int len = is.read(arr, offset, arr.length - offset);
253 throw new IOException("Can't read " + name);
259 if (is != null) is.close();
263 private static void turnAssetionStatusOn() {
266 @JavaScriptBody(args = { "r", "time" }, javacall = true, body =
267 "return window.setTimeout(function() { "
268 + "r.@java.lang.Runnable::run()(); "
271 private static native Object schedule(Runnable r, int time);
273 private static final class Case {
274 private final Object data;
278 private Case(Object data) {
282 public static Case parseData(String s) {
283 return new Case(toJSON(s));
286 public String getMethodName() {
287 return (String) value("methodName", data);
290 public String getClassName() {
291 return (String) value("className", data);
294 public int getRequestId() {
295 Object v = value("request", data);
296 if (v instanceof Number) {
297 return ((Number)v).intValue();
299 return Integer.parseInt(v.toString());
302 public String getHtmlFragment() {
303 return (String) value("html", data);
306 void again(Object[] arr) {
310 setAttr(textArea, "value", "");
312 } catch (Exception ex) {
313 log(ex.getClass().getName() + ":" + ex.getMessage());
317 private Object runTest() throws IllegalAccessException,
318 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
319 InvocationTargetException, InstantiationException, InterruptedException {
320 if (this.getHtmlFragment() != null) {
321 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
323 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
324 Object result = invokeMethod(this.getClassName(), this.getMethodName());
325 setAttr("bck2brwsr.fragment", "innerHTML", "");
326 log("Result: " + result);
327 log("Time: " + time + " ms");
328 result = encodeURL("" + result);
332 private Object invokeMethod(String clazz, String method)
333 throws ClassNotFoundException, InvocationTargetException,
334 InterruptedException, IllegalAccessException, IllegalArgumentException,
335 InstantiationException {
337 Class<?> c = Class.forName(clazz);
338 for (Method m : c.getMethods()) {
339 if (m.getName().equals(method)) {
346 if ((found.getModifiers() & Modifier.STATIC) != 0) {
347 res = found.invoke(null);
350 inst = c.newInstance();
352 double now = getTime();
353 res = found.invoke(inst);
354 double took = Math.round(getTime() - now);
356 log("Execution took " + took + " ms");
358 } catch (Throwable ex) {
359 if (ex instanceof InvocationTargetException) {
360 ex = ((InvocationTargetException) ex).getTargetException();
362 if (ex instanceof InterruptedException) {
363 throw (InterruptedException)ex;
365 res = ex.getClass().getName() + ":" + ex.getMessage();
368 res = "Can't find method " + method + " in " + clazz;
373 @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
374 private static native Object toJSON(String s);
376 private static Object value(String p, Object d) {
377 return ((JSObject)d).getMember(p);
382 turnAssetionStatusOn();