JavaScript in a browser can be at most three times slower than HotSpot when computing five or ten thousands of prime numbers
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 = "return new Date().getTime()")
57 private static native double getTime();
59 @net.java.html.js.JavaScriptBody(args = { }, body =
60 "var a = document.createElement('a');"
61 + "a.innerHTML = 'Cancel: closing in 10s...';\n"
63 + "var closing = window.setTimeout(function() { window.close(); }, 10000);\n"
64 + "a.onclick = function() { clearTimeout(closing); document.body.removeChild(a); };\n"
65 + "document.body.appendChild(a);\n" +
68 static native void closeWindow();
70 private static Object textArea;
71 private static Object statusArea;
73 private static void log(String newText) {
74 if (textArea == null) {
77 String attr = "value";
78 setAttr(textArea, attr, getAttr(textArea, attr) + "\n" + newText);
79 setAttr(textArea, "scrollTop", getAttr(textArea, "scrollHeight"));
82 private static void beginTest(Case c) {
83 Object[] arr = new Object[2];
84 beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
89 private static void finishTest(Case c, Object res) {
90 if ("null".equals(res)) {
91 setAttr(statusArea, "innerHTML", "Success");
93 setAttr(statusArea, "innerHTML", "Result " + res);
99 @JavaScriptBody(args = { "test", "c", "arr" }, body =
100 "var ul = window.document.getElementById('bck2brwsr.result');\n"
101 + "var li = window.document.createElement('li');\n"
102 + "var span = window.document.createElement('span');"
103 + "span.innerHTML = test + ' - ';\n"
104 + "var details = window.document.createElement('a');\n"
105 + "details.innerHTML = 'Details';\n"
106 + "details.href = '#';\n"
107 + "var p = window.document.createElement('p');\n"
108 + "var status = window.document.createElement('a');\n"
109 + "status.innerHTML = 'running';"
110 + "details.onclick = function() { li.appendChild(p); li.removeChild(details); status.innerHTML = 'Run Again'; status.href = '#'; };\n"
111 + "status.onclick = function() { c.again__V_3Ljava_lang_Object_2(arr); }\n"
112 + "var pre = window.document.createElement('textarea');\n"
115 + "li.appendChild(span);\n"
116 + "li.appendChild(status);\n"
117 + "var span = window.document.createElement('span');"
118 + "span.innerHTML = ' ';\n"
119 + "li.appendChild(span);\n"
120 + "li.appendChild(details);\n"
121 + "p.appendChild(pre);\n"
122 + "ul.appendChild(li);\n"
124 + "arr[1] = status;\n"
126 private static native void beginTest(String test, Case c, Object[] arr);
128 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
129 + "var request = new XMLHttpRequest();\n"
130 + "request.open('GET', url, true);\n"
131 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
132 + "request.onreadystatechange = function() {\n"
133 + " if (this.readyState!==4) return;\n"
134 + " arr[0] = this.responseText;\n"
135 + " callback.run__V();\n"
139 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
141 public static void harness(String url) throws IOException {
142 log("Connecting to " + url);
143 Request r = new Request(url);
146 private static class Request implements Runnable {
147 private final String[] arr = { null };
148 private final String url;
152 private Request(String url) throws IOException {
154 loadText(url, this, arr);
156 private Request(String url, String u) throws IOException {
158 loadText(u, this, arr);
165 String data = arr[0];
168 log("Some error exiting");
173 if (data.isEmpty()) {
174 log("No data, exiting");
179 c = Case.parseData(data);
181 log("Got \"" + data + "\"");
183 log("Processing \"" + arr[0] + "\" for " + retries + " time");
185 Object result = retries++ >= 100 ? "java.lang.InterruptedException:timeout(" + retries + ")" : c.runTest();
186 String reply = "?request=" + c.getRequestId() + "&time=" + c.time + "&result=" + result;
187 log("Sending back: ..." + reply);
188 finishTest(c, result);
190 String u = url + reply;
192 } catch (Exception ex) {
193 if (ex instanceof InterruptedException) {
194 log("Re-scheduling in 100ms");
198 log(ex.getClass().getName() + ":" + ex.getMessage());
203 private static String encodeURL(String r) throws UnsupportedEncodingException {
204 final String SPECIAL = "%$&+,/:;=?@";
205 StringBuilder sb = new StringBuilder();
206 byte[] utf8 = r.getBytes("UTF-8");
207 for (int i = 0; i < utf8.length; i++) {
208 int ch = utf8[i] & 0xff;
209 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
210 final String numbers = "0" + Integer.toHexString(ch);
211 sb.append("%").append(numbers.substring(numbers.length() - 2));
220 return sb.toString();
223 static String invoke(String clazz, String method) throws
224 ClassNotFoundException, InvocationTargetException, IllegalAccessException,
225 InstantiationException, InterruptedException {
226 final Object r = new Case(null).invokeMethod(clazz, method);
227 return r == null ? "null" : r.toString().toString();
230 /** Helper method that inspects the classpath and loads given resource
231 * (usually a class file). Used while running tests in Rhino.
233 * @param name resource name to find
234 * @return the array of bytes in the given resource
235 * @throws IOException I/O in case something goes wrong
237 public static byte[] read(String name, int skip) throws IOException {
239 if (!name.endsWith(".class")) {
240 u = getResource(name, skip);
242 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
243 while (en.hasMoreElements()) {
244 u = en.nextElement();
248 if (name.endsWith(".class")) {
249 throw new IOException("Can't find " + name);
254 try (InputStream is = u.openStream()) {
256 arr = new byte[is.available()];
258 while (offset < arr.length) {
259 int len = is.read(arr, offset, arr.length - offset);
261 throw new IOException("Can't read " + name);
269 private static URL getResource(String resource, int skip) throws IOException {
271 Enumeration<URL> en = Console.class.getClassLoader().getResources(resource);
272 while (en.hasMoreElements()) {
273 final URL now = en.nextElement();
282 @JavaScriptBody(args = {}, body = "vm['java_lang_Class'](false)['desiredAssertionStatus'] = true;")
283 private static void turnAssetionStatusOn() {
286 @JavaScriptBody(args = {"r", "time"}, body =
287 "return window.setTimeout(function() { r.run__V(); }, time);")
288 private static native Object schedule(Runnable r, int time);
290 private static final class Case {
291 private final Object data;
295 private Case(Object data) {
299 public static Case parseData(String s) {
300 return new Case(toJSON(s));
303 public String getMethodName() {
304 return value("methodName", data);
307 public String getClassName() {
308 return value("className", data);
311 public String getRequestId() {
312 return value("request", data);
315 public String getHtmlFragment() {
316 return value("html", data);
319 void again(Object[] arr) {
323 setAttr(textArea, "value", "");
325 } catch (Exception ex) {
326 log(ex.getClass().getName() + ":" + ex.getMessage());
330 private Object runTest() throws IllegalAccessException,
331 IllegalArgumentException, ClassNotFoundException, UnsupportedEncodingException,
332 InvocationTargetException, InstantiationException, InterruptedException {
333 if (this.getHtmlFragment() != null) {
334 setAttr("bck2brwsr.fragment", "innerHTML", this.getHtmlFragment());
336 log("Invoking " + this.getClassName() + '.' + this.getMethodName() + " as request: " + this.getRequestId());
337 Object result = invokeMethod(this.getClassName(), this.getMethodName());
338 setAttr("bck2brwsr.fragment", "innerHTML", "");
339 log("Result: " + result);
340 result = encodeURL("" + result);
344 private Object invokeMethod(String clazz, String method)
345 throws ClassNotFoundException, InvocationTargetException,
346 InterruptedException, IllegalAccessException, IllegalArgumentException,
347 InstantiationException {
349 Class<?> c = Class.forName(clazz);
350 for (Method m : c.getMethods()) {
351 if (m.getName().equals(method)) {
359 if ((found.getModifiers() & Modifier.STATIC) != 0) {
361 res = found.invoke(null);
364 inst = c.newInstance();
367 res = found.invoke(inst);
369 double took = Math.round((float)(getTime() - now));
371 } catch (Throwable ex) {
372 if (ex instanceof InvocationTargetException) {
373 ex = ((InvocationTargetException) ex).getTargetException();
375 if (ex instanceof InterruptedException) {
376 throw (InterruptedException)ex;
378 res = ex.getClass().getName() + ":" + ex.getMessage();
381 res = "Can't find method " + method + " in " + clazz;
386 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
387 private static native Object toJSON(String s);
389 @JavaScriptBody(args = {"p", "d"}, body =
391 + "if (typeof v === 'undefined') return null;\n"
392 + "return v.toString();"
394 private static native String value(String p, Object d);