All classes loaded through the 'vm' object will have 'invoke' method that can be used to invoke static methods like main(String[]), so our examples no longer need to rely on initialization in static initializers.
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.vm4brwsr;
20 import java.io.ByteArrayInputStream;
22 import java.io.FileWriter;
23 import java.io.IOException;
24 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Enumeration;
29 import java.util.List;
30 import javax.script.Invocable;
31 import javax.script.ScriptContext;
32 import javax.script.ScriptEngine;
33 import javax.script.ScriptEngineManager;
34 import javax.script.ScriptException;
35 import static org.testng.Assert.*;
37 public final class TestVM {
38 private final Invocable code;
39 private final CharSequence codeSeq;
40 private final Object bck2brwsr;
41 private BytesLoader resources;
44 private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
46 this.codeSeq = codeSeq;
47 this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
48 ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
51 public void register(BytesLoader res) {
55 public byte[] get(String res) throws IOException {
56 return resources != null ? resources.get(res) : null;
59 public Object execCode(
60 String msg, Class<?> clazz, String method,
61 Object expRes, Object... args
65 ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
66 List<Object> ma = new ArrayList<>();
68 ma.addAll(Arrays.asList(args));
69 ret = code.invokeMethod(ret, "invoke", ma.toArray());
70 } catch (ScriptException ex) {
71 fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
72 } catch (NoSuchMethodException ex) {
73 fail("Cannot find method in " + dumpJS(codeSeq), ex);
75 if (ret == null && expRes == null) {
78 if (expRes != null && expRes.equals(ret)) {
81 if (expRes instanceof Number) {
82 // in case of Long it is necessary convert it to number
83 // since the Long is represented by two numbers in JavaScript
85 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
86 if (ret instanceof Long) {
87 ret = code.invokeMethod(toFP, "call", ret);
89 ret = code.invokeFunction("Number", ret);
90 } catch (ScriptException ex) {
91 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
92 } catch (NoSuchMethodException ex) {
93 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
100 String msg, Class clazz, String method, Object expRes, Object... args
102 Object ret = execCode(msg, clazz, method, expRes, args);
106 if (expRes instanceof Integer && ret instanceof Double) {
107 expRes = ((Integer)expRes).doubleValue();
109 if (expRes != null && expRes.equals(ret)) {
112 assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
115 static TestVM compileClass(String... names) throws ScriptException, IOException {
116 return compileClass(null, names);
119 static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
120 return compileClass(sb, null, names);
123 static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
125 sb = new StringBuilder();
127 Bck2Brwsr.generate(sb, new EmulationResources(), names);
128 ScriptEngineManager sem = new ScriptEngineManager();
129 ScriptEngine js = sem.getEngineByExtension("js");
134 Object res = js.eval(sb.toString());
135 assertTrue(js instanceof Invocable, "It is invocable object: " + res);
136 return new TestVM((Invocable) js, sb);
137 } catch (Exception ex) {
138 if (sb.length() > 2000) {
141 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
146 static TestVM compileClassAsExtension(
147 StringBuilder sb, ScriptEngine[] eng,
148 String name, final String resourceName, final String resourceContent
149 ) throws ScriptException, IOException {
151 sb = new StringBuilder();
153 if (eng[0] == null) {
154 ScriptEngineManager sem = new ScriptEngineManager();
155 ScriptEngine js = sem.getEngineByExtension("js");
157 Bck2Brwsr.generate(sb, new EmulationResources());
159 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
160 resources(new EmulationResources() {
162 public InputStream get(String name) throws IOException {
163 if (name.equals(resourceName)) {
164 return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
166 return super.get(name);
169 addRootClasses(name).
170 addResources("org/apidesign/vm4brwsr/obj.js").
171 obfuscation(ObfuscationLevel.FULL).
173 if (resourceName != null) {
174 b2b = b2b.addResources(resourceName);
179 Object res = eng[0].eval(sb.toString());
180 assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
181 return new TestVM((Invocable) eng[0], sb);
182 } catch (Exception ex) {
183 if (sb.length() > 2000) {
186 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
191 static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
193 sb = new StringBuilder();
195 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
196 resources(new EmulationResources()).
197 addRootClasses(name).
198 addResources(resources);
200 ScriptEngineManager sem = new ScriptEngineManager();
201 ScriptEngine js = sem.getEngineByExtension("js");
208 Object res = js.eval(sb.toString());
209 assertTrue(js instanceof Invocable, "It is invocable object: " + res);
210 return new TestVM((Invocable) js, sb);
211 } catch (Exception ex) {
212 if (sb.length() > 2000) {
215 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
220 private static void defineAtoB(ScriptEngine js) throws ScriptException {
221 js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
224 Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
225 return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
228 Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
229 return code.invokeMethod(obj, method, params);
232 Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
233 return code.invokeFunction(methodName, args);
236 static StringBuilder dumpJS(CharSequence sb) throws IOException {
237 File f = File.createTempFile("execution", ".js");
238 FileWriter w = new FileWriter(f);
241 return new StringBuilder(f.getPath());
245 public String toString() {
247 return dumpJS(codeSeq).toString();
248 } catch (IOException ex) {
249 return ex.toString();
253 final CharSequence codeSeq() {
257 private static class EmulationResources implements Bck2Brwsr.Resources {
259 public InputStream get(String name) throws IOException {
260 if ("java/net/URI.class".equals(name)) {
264 if ("java/net/URLConnection.class".equals(name)) {
268 if ("java/lang/System.class".equals(name)) {
272 Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
274 while (en.hasMoreElements()) {
275 u = en.nextElement();
278 throw new IOException("Can't find " + name);
280 if (u.toExternalForm().contains("rt.jar!")) {
281 throw new IOException("No emulation for " + u);
283 return u.openStream();