Automatically close the browser windows unless such action gets canceled.
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 "return window.document.getElementById(id)[attr].toString();")
44 private static native Object getAttr(String id, String attr);
45 @JavaScriptBody(args = {"elem", "attr"}, body =
46 "return elem[attr].toString();")
47 private static native Object getAttr(Object elem, String attr);
49 @JavaScriptBody(args = {"id", "attr", "value"}, body =
50 "window.document.getElementById(id)[attr] = value;")
51 private static native void setAttr(String id, String attr, Object value);
52 @JavaScriptBody(args = {"elem", "attr", "value"}, body =
53 "elem[attr] = value;")
54 private static native void setAttr(Object id, String attr, Object value);
56 @net.java.html.js.JavaScriptBody(args = { }, body =
57 "var a = document.createElement('a');"
58 + "a.innerHTML = 'Cancel: closing in 10s...';\n"
60 + "var closing = window.setTimeout(function() { window.close(); }, 10000);\n"
61 + "a.onclick = function() { clearTimeout(closing); document.body.removeChild(a); };\n"
62 + "document.body.appendChild(a);\n" +
65 static native void closeWindow();
67 private static Object textArea;
68 private static Object statusArea;
70 private static void log(String newText) {
71 if (textArea == null) {
74 String attr = "value";
75 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
76 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
79 private static void beginTest(Case c) {
80 Object[] arr = new Object[2];
81 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
86 private static void finishTest(Case c, Object res) {
87 if ("null".equals(res)) {
88 setAttr(statusArea, "innerHTML", "Success");
90 setAttr(statusArea, "innerHTML", "Result " + res);
96 @JavaScriptBody(args = { "test", "c", "arr" }, body =
97 "var ul = window.document.getElementById('bck2brwsr.result');\n"
98 + "var li = window.document.createElement('li');\n"
99 + "var span = window.document.createElement('span');"
100 + "span.innerHTML = test + ' - ';\n"
101 + "var details = window.document.createElement('a');\n"
102 + "details.innerHTML = 'Details';\n"
103 + "details.href = '#';\n"
104 + "var p = window.document.createElement('p');\n"
105 + "var status = window.document.createElement('a');\n"
106 + "status.innerHTML = 'running';"
107 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
108 + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
109 + "var pre = window.document.createElement('textarea');\n"
112 + "li.appendChild(span);\n"
113 + "li.appendChild(status);\n"
114 + "var span = window.document.createElement('span');"
115 + "span.innerHTML = ' ';\n"
116 + "li.appendChild(span);\n"
117 + "li.appendChild(details);\n"
118 + "p.appendChild(pre);\n"
119 + "ul.appendChild(li);\n"
121 + "arr[1] = status;\n"
123 private static native void beginTest(String test, Case c, Object[] arr);
125 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
126 + "var request = new XMLHttpRequest();\n"
127 + "request.open('GET', url, true);\n"
128 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
129 + "request.onreadystatechange = function() {\n"
130 + " if (this.readyState!==4) return;\n"
131 + " arr[0] = this.responseText;\n"
132 + " callback.run__V();\n"
136 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
138 public static void harness(String url) throws IOException {
139 log("Connecting to " + url);
140 Request r = new Request(url);
143 private static class Request implements Runnable {
144 private final String[] arr = { null };
145 private final String url;
149 private Request(String url) throws IOException {
151 loadText(url, this, arr);
153 private Request(String url, String u) throws IOException {
155 loadText(u, this, arr);
162 String data = arr[0];
165 log("Some error exiting");
170 if (data.isEmpty()) {
171 log("No data, exiting");
176 c = Case.parseData(data);
178 log("Got \"" + data + "\"");
180 log("Processing \"" + arr[0] + "\" for " + retries + " time");
182 Object result = retries++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
183 finishTest(c, result);
185 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
187 } catch (Exception ex) {
188 if (ex instanceof InterruptedException) {
189 log("Re-scheduling in 100ms");
193 log(ex.getClass().getName() + ":" + ex.getMessage());
198 private static String encodeURL(String r) throws UnsupportedEncodingException {
199 final String SPECIAL = "%$&+,/:;=?@";
200 StringBuilder sb = new StringBuilder();
201 byte[] utf8 = r.getBytes("UTF-8");
202 for (int i = 0; i < utf8.length; i++) {
203 int ch = utf8[i] & 0xff;
204 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
205 final String numbers = "0" + Integer.toHexString(ch);
206 sb.append("%").append(numbers.substring(numbers.length() - 2));
215 return sb.toString();
218 static String invoke(String clazz, String method) throws
219 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
220 InstantiationException, InterruptedException {
221 final Object r = new Case(null).invokeMethod(clazz, method);
222 return r == null ? "null" : r.toString().toString();
225 /** Helper method that inspects the classpath and loads given resource
226 * (usually a class file). Used while running tests in Rhino.
228 * @param name resource name to find
229 * @return the array of bytes in the given resource
230 * @throws IOException I/O in case something goes wrong
232 public static byte[] read(String name, int skip) throws IOException {
234 if (!name.endsWith(".class")) {
235 u = getResource(name, skip);
237 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
238 while (en.hasMoreElements()) {
239 u = en.nextElement();
243 if (name.endsWith(".class")) {
244 throw new IOException("Can't find " + name);
249 try (InputStream is = u.openStream()) {
251 arr = new byte[is.available()];
253 while (offset < arr.length) {
254 int len = is.read(arr, offset, arr.length - offset);
256 throw new IOException("Can't read " + name);
264 private static URL getResource(String resource, int skip) throws IOException {
266 Enumeration<URL> en = Console.class.getClassLoader().getResources(resource);
267 while (en.hasMoreElements()) {
268 final URL now = en.nextElement();
277 @JavaScriptBody(args = {}, body = "vm['java_lang_Class'](false)['desiredAssertionStatus'] = true;")
278 private static void turnAssetionStatusOn() {
281 @JavaScriptBody(args = {"r", "time"}, body =
282 "return window.setTimeout(function() { r.run__V(); }, time);")
283 private static native Object schedule(Runnable r, int time);
285 private static final class Case {
286 private final Object data;
289 private Case(Object data) {
293 public static Case parseData(String s) {
294 return new Case(toJSON(s));
297 public String getMethodName() {
298 return value("methodName", data);
301 public String getClassName() {
302 return value("className", data);
305 public String getRequestId() {
306 return value("request", data);
309 public String getHtmlFragment() {
310 return value("html", data);
313 void again(Object[] arr) {
317 setAttr(textArea, "value", "");
319 } catch (Exception ex) {
320 log(ex.getClass().getName() + ":" + ex.getMessage());
324 private Object runTest() throws IllegalAccessException,
325 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
326 InvocationTargetException, InstantiationException, InterruptedException {
327 if (this.getHtmlFragment() != null) {
328 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
330 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
331 Object result = invokeMethod(this.getClassName(), this.getMethodName());
332 setAttr("bck2brwsr.fragment", "innerHTML", "");
333 log("Result: " + result);
334 result = encodeURL("" + result);
335 log("Sending back: ...?request=" + this.getRequestId() + "&result=" + result);
339 private Object invokeMethod(String clazz, String method)
340 throws ClassNotFoundException, InvocationTargetException,
341 InterruptedException, IllegalAccessException, IllegalArgumentException,
342 InstantiationException {
344 Class<?> c = Class.forName(clazz);
345 for (Method m : c.getMethods()) {
346 if (m.getName().equals(method)) {
353 if ((found.getModifiers() & Modifier.STATIC) != 0) {
354 res = found.invoke(null);
357 inst = c.newInstance();
359 res = found.invoke(inst);
361 } catch (Throwable ex) {
362 if (ex instanceof InvocationTargetException) {
363 ex = ((InvocationTargetException) ex).getTargetException();
365 if (ex instanceof InterruptedException) {
366 throw (InterruptedException)ex;
368 res = ex.getClass().getName() + ":" + ex.getMessage();
371 res = "Can't find method " + method + " in " + clazz;
376 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
377 private static native Object toJSON(String s);
379 @JavaScriptBody(args = {"p", "d"}, body =
381 + "if (typeof v === 'undefined') return null;\n"
382 + "return v.toString();"
384 private static native String value(String p, Object d);