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.dynamic;
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.HashSet;
30 import java.util.List;
32 import javax.script.Invocable;
33 import javax.script.ScriptContext;
34 import javax.script.ScriptEngine;
35 import javax.script.ScriptEngineManager;
36 import javax.script.ScriptException;
37 import org.apidesign.vm4brwsr.Bck2Brwsr;
38 import org.apidesign.vm4brwsr.ObfuscationLevel;
39 import static org.testng.Assert.*;
41 public final class TestVM {
42 private final Invocable code;
43 private final CharSequence codeSeq;
44 private final Object bck2brwsr;
47 private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
49 this.codeSeq = codeSeq;
50 this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
51 ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
54 public Object execCode(
55 String msg, Class<?> clazz, String method,
56 Object expRes, Object... args
60 ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
61 List<Object> ma = new ArrayList<>();
63 ma.addAll(Arrays.asList(args));
64 ret = code.invokeMethod(ret, "invoke", ma.toArray());
65 } catch (ScriptException ex) {
66 fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
67 } catch (NoSuchMethodException ex) {
68 fail("Cannot find method in " + dumpJS(codeSeq), ex);
70 if (ret == null && expRes == null) {
73 if (expRes != null && expRes.equals(ret)) {
76 if (expRes instanceof Number) {
77 // in case of Long it is necessary convert it to number
78 // since the Long is represented by two numbers in JavaScript
80 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
81 if (ret instanceof Long) {
82 ret = code.invokeMethod(toFP, "call", ret);
84 ret = code.invokeFunction("Number", ret);
85 } catch (ScriptException ex) {
86 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
87 } catch (NoSuchMethodException ex) {
88 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
95 String msg, Class clazz, String method, Object expRes, Object... args
97 Object ret = execCode(msg, clazz, method, expRes, args);
101 if (expRes instanceof Integer && ret instanceof Double) {
102 expRes = ((Integer)expRes).doubleValue();
104 if (expRes != null && expRes.equals(ret)) {
107 assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
110 static TestVM compileClass(String... names) throws ScriptException, IOException {
111 return compileClass(null, names);
114 static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
115 return compileClass(sb, null, names);
118 static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
119 return compileClass(sb, eng, new EmulationResources(), names);
121 static TestVM compileClass(
124 Bck2Brwsr.Resources resources,
126 ) throws ScriptException, IOException {
128 sb = new StringBuilder();
130 Bck2Brwsr.generate(sb, resources, names);
131 ScriptEngineManager sem = new ScriptEngineManager();
132 ScriptEngine js = sem.getEngineByExtension("js");
137 Object res = js.eval(sb.toString());
138 assertTrue(js instanceof Invocable, "It is invocable object: " + res);
139 return new TestVM((Invocable) js, sb);
140 } catch (Exception ex) {
141 if (sb.length() > 2000) {
144 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
149 static TestVM compileClassAsExtension(
150 StringBuilder sb, ScriptEngine[] eng,
151 String name, final String resourceName, final String resourceContent
152 ) throws ScriptException, IOException {
153 return compileClassesAsExtension(sb, eng, resourceName, resourceContent, name);
155 static TestVM compileClassesAsExtension(
156 StringBuilder sb, ScriptEngine[] eng,
157 final String resourceName, final String resourceContent, String... names
158 ) throws ScriptException, IOException {
160 sb = new StringBuilder();
162 if (eng[0] == null) {
163 ScriptEngineManager sem = new ScriptEngineManager();
164 ScriptEngine js = sem.getEngineByExtension("js");
166 Bck2Brwsr.generate(sb, new EmulationResources());
168 Set<String> exp = new HashSet<String>();
169 for (String n : names) {
170 int last = n.lastIndexOf('/');
171 exp.add(n.substring(0, last + 1));
173 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
174 resources(new EmulationResources() {
176 public InputStream get(String name) throws IOException {
177 if (name.equals(resourceName)) {
178 return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
180 return super.get(name);
184 addResources("org/apidesign/vm4brwsr/obj.js").
185 addExported(exp.toArray(new String[0])).
186 obfuscation(ObfuscationLevel.FULL).
188 if (resourceName != null) {
189 b2b = b2b.addResources(resourceName);
194 Object res = eng[0].eval(sb.toString());
195 assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
196 return new TestVM((Invocable) eng[0], sb);
197 } catch (Exception ex) {
198 if (sb.length() > 2000) {
201 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
206 static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
208 sb = new StringBuilder();
210 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
211 resources(new EmulationResources()).
212 addRootClasses(name).
213 addResources(resources);
215 ScriptEngineManager sem = new ScriptEngineManager();
216 ScriptEngine js = sem.getEngineByExtension("js");
223 Object res = js.eval(sb.toString());
224 assertTrue(js instanceof Invocable, "It is invocable object: " + res);
225 return new TestVM((Invocable) js, sb);
226 } catch (Exception ex) {
227 if (sb.length() > 2000) {
230 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
235 private static void defineAtoB(ScriptEngine js) throws ScriptException {
236 js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
239 Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
240 return code.invokeMethod(obj, method, params);
243 Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
244 return code.invokeFunction(methodName, args);
247 static StringBuilder dumpJS(CharSequence sb) throws IOException {
248 File f = File.createTempFile("execution", ".js");
249 FileWriter w = new FileWriter(f);
252 return new StringBuilder(f.getPath());
256 public String toString() {
258 return dumpJS(codeSeq).toString();
259 } catch (IOException ex) {
260 return ex.toString();
264 final CharSequence codeSeq() {
268 private static class EmulationResources implements Bck2Brwsr.Resources {
270 public InputStream get(String name) throws IOException {
271 if ("java/net/URI.class".equals(name)) {
275 if ("java/net/URLConnection.class".equals(name)) {
279 if ("java/lang/System.class".equals(name)) {
283 Enumeration<URL> en = TestVM.class.getClassLoader().getResources(name);
285 while (en.hasMoreElements()) {
286 u = en.nextElement();
289 throw new IOException("Can't find " + name);
291 if (u.toExternalForm().contains("rt.jar!")) {
292 throw new IOException("No emulation for " + u);
294 return u.openStream();