rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 28 May 2014 13:38:29 +0200
branchclosure
changeset 1610 a6f807104d8e
parent 1609 752f48257d4a
child 1611 d0df418a5993
permissions -rw-r--r--
Make sure Object is always available in each VM and each extension.
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    13  *
    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.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.ByteArrayInputStream;
    21 import java.io.File;
    22 import java.io.FileWriter;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.net.URL;
    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.*;
    36 
    37 public final class TestVM {
    38     private final Invocable code;
    39     private final CharSequence codeSeq;
    40     private final Object bck2brwsr;
    41     private BytesLoader resources;
    42     
    43     
    44     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    45         this.code = code;
    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);
    49     }
    50     
    51     public void register(BytesLoader res) {
    52         this.resources = res;
    53     }
    54     
    55     public byte[] get(String res) throws IOException {
    56         return resources != null ? resources.get(res) : null;
    57     }
    58 
    59     public Object execCode(
    60         String msg, Class<?> clazz, String method, 
    61         Object expRes, Object... args
    62     ) throws Exception {
    63         Object ret = null;
    64         try {
    65             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    66             List<Object> ma = new ArrayList<>();
    67             ma.add(method);
    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);
    74         }
    75         if (ret == null && expRes == null) {
    76             return null;
    77         }
    78         if (expRes != null && expRes.equals(ret)) {
    79             return null;
    80         }
    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
    84             try {
    85                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    86                 if (ret instanceof Long) {
    87                     ret = code.invokeMethod(toFP, "call", ret);
    88                 }
    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);
    94             }
    95         }
    96         return ret;
    97     }
    98     
    99     void assertExec(
   100         String msg, Class clazz, String method, Object expRes, Object... args
   101     ) throws Exception {
   102         Object ret = execCode(msg, clazz, method, expRes, args);
   103         if (ret == null) {
   104             return;
   105         }
   106         if (expRes instanceof Integer && ret instanceof Double) {
   107             expRes = ((Integer)expRes).doubleValue();
   108         }
   109         if (expRes != null && expRes.equals(ret)) {
   110             return;
   111         }
   112         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
   113     }    
   114 
   115     static TestVM compileClass(String... names) throws ScriptException, IOException {
   116         return compileClass(null, names);
   117     }
   118     
   119     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   120         return compileClass(sb, null, names);
   121     }
   122 
   123     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   124         if (sb == null) {
   125             sb = new StringBuilder();
   126         }
   127         Bck2Brwsr.generate(sb, new EmulationResources(), names);
   128         ScriptEngineManager sem = new ScriptEngineManager();
   129         ScriptEngine js = sem.getEngineByExtension("js");
   130         if (eng != null) {
   131             eng[0] = js;
   132         }
   133         try {
   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) {
   139                 sb = dumpJS(sb);
   140             }
   141             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   142             return null;
   143         }
   144     }
   145     
   146     static TestVM compileClassAsExtension(
   147         StringBuilder sb, ScriptEngine[] eng, 
   148         String name, final String resourceName, final String resourceContent
   149     ) throws ScriptException, IOException {
   150         return compileClassesAsExtension(sb, eng, resourceName, resourceContent, name);
   151     }
   152     static TestVM compileClassesAsExtension(
   153         StringBuilder sb, ScriptEngine[] eng, 
   154         final String resourceName, final String resourceContent, String... names
   155     ) throws ScriptException, IOException {
   156         if (sb == null) {
   157             sb = new StringBuilder();
   158         }
   159         if (eng[0] == null) {
   160             ScriptEngineManager sem = new ScriptEngineManager();
   161             ScriptEngine js = sem.getEngineByExtension("js");
   162             eng[0] = js;
   163             Bck2Brwsr.generate(sb, new EmulationResources());
   164         }
   165         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   166             resources(new EmulationResources() {
   167                 @Override
   168                 public InputStream get(String name) throws IOException {
   169                     if (name.equals(resourceName)) {
   170                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   171                     }
   172                     return super.get(name);
   173                 }
   174             }).
   175             addClasses(names).
   176             addResources("org/apidesign/vm4brwsr/obj.js").
   177             addExported("org/apidesign/vm4brwsr/").
   178             obfuscation(ObfuscationLevel.FULL).
   179             library();
   180         if (resourceName != null) {
   181             b2b = b2b.addResources(resourceName);
   182         }
   183         b2b.generate(sb);
   184         try {
   185             defineAtoB(eng[0]);
   186             Object res = eng[0].eval(sb.toString());
   187             assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
   188             return new TestVM((Invocable) eng[0], sb);
   189         } catch (Exception ex) {
   190             if (sb.length() > 2000) {
   191                 sb = dumpJS(sb);
   192             }
   193             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   194             return null;
   195         }
   196     }
   197     
   198     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   199         if (sb == null) {
   200             sb = new StringBuilder();
   201         }
   202         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   203             resources(new EmulationResources()).
   204             addRootClasses(name).
   205             addResources(resources);
   206         b2b.generate(sb);
   207         ScriptEngineManager sem = new ScriptEngineManager();
   208         ScriptEngine js = sem.getEngineByExtension("js");
   209         if (eng != null) {
   210             eng[0] = js;
   211         }
   212         try {
   213             defineAtoB(js);
   214             
   215             Object res = js.eval(sb.toString());
   216             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   217             return new TestVM((Invocable) js, sb);
   218         } catch (Exception ex) {
   219             if (sb.length() > 2000) {
   220                 sb = dumpJS(sb);
   221             }
   222             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   223             return null;
   224         }
   225     }
   226 
   227     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   228         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   229     }
   230 
   231     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   232         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   233     }
   234     
   235     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   236         return code.invokeMethod(obj, method, params);
   237     }
   238 
   239     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   240         return code.invokeFunction(methodName, args);
   241     }
   242 
   243     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   244         File f = File.createTempFile("execution", ".js");
   245         FileWriter w = new FileWriter(f);
   246         w.append(sb);
   247         w.close();
   248         return new StringBuilder(f.getPath());
   249     }
   250 
   251     @Override
   252     public String toString() {
   253         try {
   254             return dumpJS(codeSeq).toString();
   255         } catch (IOException ex) {
   256             return ex.toString();
   257         }
   258     }
   259 
   260     final CharSequence codeSeq() {
   261         return codeSeq;
   262     }
   263     
   264     private static class EmulationResources implements Bck2Brwsr.Resources {
   265         @Override
   266         public InputStream get(String name) throws IOException {
   267             if ("java/net/URI.class".equals(name)) {
   268                 // skip
   269                 return null;
   270             }
   271             if ("java/net/URLConnection.class".equals(name)) {
   272                 // skip
   273                 return null;
   274             }
   275             if ("java/lang/System.class".equals(name)) {
   276                 // skip
   277                 return null;
   278             }
   279             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   280             URL u = null;
   281             while (en.hasMoreElements()) {
   282                 u = en.nextElement();
   283             }
   284             if (u == null) {
   285                 throw new IOException("Can't find " + name);
   286             }
   287             if (u.toExternalForm().contains("rt.jar!")) {
   288                 throw new IOException("No emulation for " + u);
   289             }
   290             return u.openStream();
   291         }
   292     }
   293 }