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.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 @org.apidesign.bck2brwsr.core.Exported
35 public class Console {
39 turnAssetionStatusOn();
42 @JavaScriptBody(args = {"id", "attr"}, body =
43 "var e = window.document.getElementById(id);" +
44 "return e ? e[attr].toString() : null;"
46 private static native Object getAttr(String id, String attr);
47 @JavaScriptBody(args = {"elem", "attr"}, body =
48 "return elem ? elem[attr].toString() : null;")
49 private static native Object getAttr(Object elem, String attr);
51 @JavaScriptBody(args = {"id", "attr", "value"}, body =
52 "var e = window.document.getElementById(id);\n"
53 + "if (e) e[attr] = value;"
55 private static native void setAttr(String id, String attr, Object value);
56 @JavaScriptBody(args = {"elem", "attr", "value"}, body =
57 "if (elem) elem[attr] = value;")
58 private static native void setAttr(Object id, String attr, Object value);
60 @net.java.html.js.JavaScriptBody(args = {}, body = "return new Date().getTime()")
61 private static native double getTime();
63 @net.java.html.js.JavaScriptBody(args = { }, body =
64 "if (!document.getElementById('bck2brwsr.fragment')) return;\n"
65 + "var a = document.createElement('a');\n"
66 + "a.innerHTML = 'Cancel: closing in 10s...';\n"
68 + "var closing = window.setTimeout(function() { window.close(); }, 10000);\n"
69 + "a.onclick = function() { clearTimeout(closing); document.body.removeChild(a); };\n"
70 + "document.body.appendChild(a);\n" +
73 static native void closeWindow();
75 private static Object textArea;
76 private static Object statusArea;
78 private static void log(String newText) {
79 if (textArea == null) {
82 String attr = "value";
83 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
84 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
87 private static void beginTest(Case c) {
88 Object[] arr = new Object[2];
90 String[] args = c.getArgs();
91 if (args == null || args.length == 0) {
92 testName = c.getClassName() + "." + c.getMethodName();
95 for (int i = 1; i < args.length; i++) {
96 testName = testName + ',' + args[i];
99 beginTest(testName, c, arr);
104 private static void finishTest(Case c, Object res) {
105 if ("null".equals(res)) {
106 setAttr(statusArea, "innerHTML", "Success");
108 setAttr(statusArea, "innerHTML", "Result " + res);
114 @JavaScriptBody(args = { "test", "c", "arr" }, body =
115 "var ul = window.document.getElementById('bck2brwsr.result');\n"
116 + "var li = window.document.createElement('li');\n"
117 + "var span = window.document.createElement('span');"
118 + "span.innerHTML = test + ' - ';\n"
119 + "var details = window.document.createElement('a');\n"
120 + "details.innerHTML = 'Details';\n"
121 + "details.href = '#';\n"
122 + "var p = window.document.createElement('p');\n"
123 + "var status = window.document.createElement('a');\n"
124 + "status.innerHTML = 'running';"
125 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
126 + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
127 + "var pre = window.document.createElement('textarea');\n"
130 + "li.appendChild(span);\n"
131 + "li.appendChild(status);\n"
132 + "var span = window.document.createElement('span');"
133 + "span.innerHTML = ' ';\n"
134 + "li.appendChild(span);\n"
135 + "li.appendChild(details);\n"
136 + "p.appendChild(pre);\n"
137 + "if (ul) ul.appendChild(li);\n"
139 + "arr[1] = status;\n"
141 private static native void beginTest(String test, Case c, Object[] arr);
143 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
144 + "var request = new XMLHttpRequest();\n"
145 + "request.open('GET', url, true);\n"
146 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
147 + "request.onreadystatechange = function() {\n"
148 + " if (this.readyState!==4) return;\n"
149 + " arr[0] = this.responseText;\n"
150 + " callback.run__V();\n"
154 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
156 public static void harness(String url) throws IOException {
157 log("Connecting to " + url);
158 Request r = new Request(url);
161 private static class Request implements Runnable {
162 private final String[] arr = { null };
163 private final String url;
167 private Request(String url) throws IOException {
169 loadText(url, this, arr);
171 private Request(String url, String u) throws IOException {
173 loadText(u, this, arr);
180 String data = arr[0];
183 log("Some error exiting");
188 if (data.isEmpty()) {
189 log("No data, exiting");
194 c = Case.parseData(data);
196 log("Got \"" + data + "\"");
198 log("Processing \"" + arr[0] + "\" for " + retries + " time");
200 Object result = retries++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
201 String reply = "?request=" + c.getRequestId() + "&time=" + c.time + "&result=" + result;
202 log("Sending back: ..." + reply);
203 finishTest(c, result);
205 String u = url + reply;
207 } catch (Exception ex) {
208 if (ex instanceof InterruptedException) {
209 log("Re-scheduling in 100ms");
213 log(ex.getClass().getName() + ":" + ex.getMessage());
218 private static String encodeURL(String r) throws UnsupportedEncodingException {
219 final String SPECIAL = "%$&+,/:;=?@";
220 StringBuilder sb = new StringBuilder();
221 byte[] utf8 = r.getBytes("UTF-8");
222 for (int i = 0; i < utf8.length; i++) {
223 int ch = utf8[i] & 0xff;
224 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
225 final String numbers = "0" + Integer.toHexString(ch);
226 sb.append("%").append(numbers.substring(numbers.length() - 2));
235 return sb.toString();
238 static String invoke(String clazz, String method) throws
239 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
240 InstantiationException, InterruptedException {
241 final Object r = new Case(null).invokeMethod(clazz, method, null);
242 return r == null ? "null" : r.toString().toString();
245 /** Helper method that inspects the classpath and loads given resource
246 * (usually a class file). Used while running tests in Rhino.
248 * @param name resource name to find
249 * @return the array of bytes in the given resource
250 * @throws IOException I/O in case something goes wrong
252 public static byte[] read(String name, int skip) throws IOException {
254 if (!name.endsWith(".class")) {
255 u = getResource(name, skip);
257 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
258 while (en.hasMoreElements()) {
259 u = en.nextElement();
263 if (name.endsWith(".class")) {
264 throw new IOException("Can't find " + name);
269 try (InputStream is = u.openStream()) {
271 arr = new byte[is.available()];
273 while (offset < arr.length) {
274 int len = is.read(arr, offset, arr.length - offset);
276 throw new IOException("Can't read " + name);
284 private static URL getResource(String resource, int skip) throws IOException {
286 Enumeration<URL> en = Console.class.getClassLoader().getResources(resource);
287 while (en.hasMoreElements()) {
288 final URL now = en.nextElement();
297 @JavaScriptBody(args = {}, body = "vm['java_lang_Class'](false)['desiredAssertionStatus'] = true;")
298 private static void turnAssetionStatusOn() {
301 @JavaScriptBody(args = {"r", "time"}, body =
302 "return window.setTimeout(function() { r.run__V(); }, time);")
303 private static native Object schedule(Runnable r, int time);
305 private static final class Case {
306 private final Object data;
310 private Case(Object data) {
314 public static Case parseData(String s) {
315 return new Case(toJSON(s));
318 public String getMethodName() {
319 return value("methodName", data);
322 public String getClassName() {
323 return value("className", data);
326 public String getRequestId() {
327 return value("request", data);
330 public String getHtmlFragment() {
331 return value("html", data);
334 public String[] getArgs() {
335 return values("args", data);
338 void again(Object[] arr) {
342 setAttr(textArea, "value", "");
344 } catch (Exception ex) {
345 log(ex.getClass().getName() + ":" + ex.getMessage());
349 private Object runTest() throws IllegalAccessException,
350 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
351 InvocationTargetException, InstantiationException, InterruptedException {
352 if (this.getHtmlFragment() != null) {
353 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
355 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
356 Object result = invokeMethod(this.getClassName(), this.getMethodName(), this.getArgs());
357 setAttr("bck2brwsr.fragment", "innerHTML", "");
358 log("Result: " + result);
359 result = encodeURL("" + result);
363 private Object invokeMethod(String clazz, String method, String[] args)
364 throws ClassNotFoundException, InvocationTargetException,
365 InterruptedException, IllegalAccessException, IllegalArgumentException,
366 InstantiationException {
369 args = new String[0];
371 Class<?> c = Class.forName(clazz);
372 for (Method m : c.getMethods()) {
373 if (m.getName().equals(method) && m.getParameterTypes().length == args.length) {
381 if ((found.getModifiers() & Modifier.STATIC) != 0) {
383 res = found.invoke(null, (Object[]) args);
386 inst = c.newInstance();
389 res = found.invoke(inst, (Object[]) args);
391 double took = Math.round((float)(getTime() - now));
393 } catch (Throwable ex) {
394 if (ex instanceof InvocationTargetException) {
395 ex = ((InvocationTargetException) ex).getTargetException();
397 if (ex instanceof InterruptedException) {
398 throw (InterruptedException)ex;
400 res = ex.getClass().getName() + ":" + ex.getMessage();
403 res = "Can't find method " + method + " in " + clazz;
408 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
409 private static native Object toJSON(String s);
411 @JavaScriptBody(args = {"p", "d"}, body =
413 + "if (typeof v === 'undefined') return null;\n"
414 + "return v.toString();"
416 private static native String value(String p, Object d);
418 @JavaScriptBody(args = {"p", "d"}, body =
420 + "if (typeof v === 'undefined') return null;\n"
423 private static native String[] values(String p, Object d);