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);
45 @JavaScriptBody(args = {"id", "attr", "value"}, body =
46 "window.document.getElementById(id)[attr] = value;")
47 private static native void setAttr(String id, String attr, Object value);
49 @JavaScriptBody(args = {}, body = "return; window.close();")
50 private static native void closeWindow();
52 private static void log(String newText) {
53 String id = "bck2brwsr.result";
54 String attr = "value";
55 setAttr(id, attr, getAttr(id, attr) + "\n" + newText);
56 setAttr(id, "scrollTop", getAttr(id, "scrollHeight"));
59 public static void execute() throws Exception {
60 String clazz = (String) getAttr("clazz", "value");
61 String method = (String) getAttr("method", "value");
62 Object res = invokeMethod(clazz, method);
63 setAttr("bck2brwsr.result", "value", res);
66 @JavaScriptBody(args = { "url", "callback", "arr" }, body = ""
67 + "var request = new XMLHttpRequest();\n"
68 + "request.open('GET', url, true);\n"
69 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
70 + "request.onreadystatechange = function() {\n"
71 + " if (this.readyState!==4) return;\n"
72 + " arr[0] = this.responseText;\n"
73 + " callback.run__V();\n"
77 private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
79 public static void harness(String url) throws IOException {
80 log("Connecting to " + url);
81 Request r = new Request(url);
84 private static class Request implements Runnable {
85 private final String[] arr = { null };
86 private final String url;
88 private Request(String url) throws IOException {
90 loadText(url, this, arr);
97 log("\nGot \"" + data + "\"");
100 log("Some error exiting");
105 if (data.isEmpty()) {
106 log("No data, exiting");
111 Case c = Case.parseData(data);
112 if (c.getHtmlFragment() != null) {
113 setAttr("bck2brwsr.fragment", "innerHTML", c.getHtmlFragment());
115 log("Invoking " + c.getClassName() + '.' + c.getMethodName() + " as request: " + c.getRequestId());
117 Object result = invokeMethod(c.getClassName(), c.getMethodName());
119 setAttr("bck2brwsr.fragment", "innerHTML", "");
120 log("Result: " + result);
122 result = encodeURL("" + result);
124 log("Sending back: " + url + "?request=" + c.getRequestId() + "&result=" + result);
125 String u = url + "?request=" + c.getRequestId() + "&result=" + result;
127 loadText(u, this, arr);
129 } catch (Exception ex) {
130 log(ex.getClass().getName() + ":" + ex.getMessage());
135 private static String encodeURL(String r) throws UnsupportedEncodingException {
136 final String SPECIAL = "%$&+,/:;=?@";
137 StringBuilder sb = new StringBuilder();
138 byte[] utf8 = r.getBytes("UTF-8");
139 for (int i = 0; i < utf8.length; i++) {
140 int ch = utf8[i] & 0xff;
141 if (ch < 32 || ch > 127 || SPECIAL.indexOf(ch) >= 0) {
142 final String numbers = "0" + Integer.toHexString(ch);
143 sb.append("%").append(numbers.substring(numbers.length() - 2));
152 return sb.toString();
155 static String invoke(String clazz, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
156 final Object r = invokeMethod(clazz, method);
157 return r == null ? "null" : r.toString().toString();
160 /** Helper method that inspects the classpath and loads given resource
161 * (usually a class file). Used while running tests in Rhino.
163 * @param name resource name to find
164 * @return the array of bytes in the given resource
165 * @throws IOException I/O in case something goes wrong
167 public static byte[] read(String name) throws IOException {
169 Enumeration<URL> en = Console.class.getClassLoader().getResources(name);
170 while (en.hasMoreElements()) {
171 u = en.nextElement();
174 throw new IOException("Can't find " + name);
176 try (InputStream is = u.openStream()) {
178 arr = new byte[is.available()];
180 while (offset < arr.length) {
181 int len = is.read(arr, offset, arr.length - offset);
183 throw new IOException("Can't read " + name);
191 private static Object invokeMethod(String clazz, String method)
192 throws ClassNotFoundException, InvocationTargetException,
193 SecurityException, IllegalAccessException, IllegalArgumentException,
194 InstantiationException {
196 Class<?> c = Class.forName(clazz);
197 for (Method m : c.getMethods()) {
198 if (m.getName().equals(method)) {
205 if ((found.getModifiers() & Modifier.STATIC) != 0) {
206 res = found.invoke(null);
208 res = found.invoke(c.newInstance());
210 } catch (Throwable ex) {
211 res = ex.getClass().getName() + ":" + ex.getMessage();
214 res = "Can't find method " + method + " in " + clazz;
219 @JavaScriptBody(args = {}, body = "vm.desiredAssertionStatus = true;")
220 private static void turnAssetionStatusOn() {
223 private static final class Case {
224 private final Object data;
226 private Case(Object data) {
230 public static Case parseData(String s) {
231 return new Case(toJSON(s));
234 public String getMethodName() {
235 return value("methodName", data);
238 public String getClassName() {
239 return value("className", data);
242 public String getRequestId() {
243 return value("request", data);
246 public String getHtmlFragment() {
247 return value("html", data);
250 @JavaScriptBody(args = "s", body = "return eval('(' + s + ')');")
251 private static native Object toJSON(String s);
253 @JavaScriptBody(args = {"p", "d"}, body =
255 + "if (typeof v === 'undefined') return null;\n"
256 + "return v.toString();"
258 private static native String value(String p, Object d);