rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 28 May 2014 10:47:18 +0200
branchclosure
changeset 1609 752f48257d4a
parent 1604 7665471a56c1
child 1610 a6f807104d8e
permissions -rw-r--r--
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.
     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         if (sb == null) {
   151             sb = new StringBuilder();
   152         }
   153         if (eng[0] == null) {
   154             ScriptEngineManager sem = new ScriptEngineManager();
   155             ScriptEngine js = sem.getEngineByExtension("js");
   156             eng[0] = js;
   157             Bck2Brwsr.generate(sb, new EmulationResources());
   158         }
   159         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   160             resources(new EmulationResources() {
   161                 @Override
   162                 public InputStream get(String name) throws IOException {
   163                     if (name.equals(resourceName)) {
   164                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   165                     }
   166                     return super.get(name);
   167                 }
   168             }).
   169             addRootClasses(name).
   170             addResources("org/apidesign/vm4brwsr/obj.js").
   171             obfuscation(ObfuscationLevel.FULL).
   172             library();
   173         if (resourceName != null) {
   174             b2b = b2b.addResources(resourceName);
   175         }
   176         b2b.generate(sb);
   177         try {
   178             defineAtoB(eng[0]);
   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) {
   184                 sb = dumpJS(sb);
   185             }
   186             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   187             return null;
   188         }
   189     }
   190     
   191     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   192         if (sb == null) {
   193             sb = new StringBuilder();
   194         }
   195         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   196             resources(new EmulationResources()).
   197             addRootClasses(name).
   198             addResources(resources);
   199         b2b.generate(sb);
   200         ScriptEngineManager sem = new ScriptEngineManager();
   201         ScriptEngine js = sem.getEngineByExtension("js");
   202         if (eng != null) {
   203             eng[0] = js;
   204         }
   205         try {
   206             defineAtoB(js);
   207             
   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) {
   213                 sb = dumpJS(sb);
   214             }
   215             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   216             return null;
   217         }
   218     }
   219 
   220     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   221         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   222     }
   223 
   224     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   225         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   226     }
   227     
   228     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   229         return code.invokeMethod(obj, method, params);
   230     }
   231 
   232     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   233         return code.invokeFunction(methodName, args);
   234     }
   235 
   236     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   237         File f = File.createTempFile("execution", ".js");
   238         FileWriter w = new FileWriter(f);
   239         w.append(sb);
   240         w.close();
   241         return new StringBuilder(f.getPath());
   242     }
   243 
   244     @Override
   245     public String toString() {
   246         try {
   247             return dumpJS(codeSeq).toString();
   248         } catch (IOException ex) {
   249             return ex.toString();
   250         }
   251     }
   252 
   253     final CharSequence codeSeq() {
   254         return codeSeq;
   255     }
   256     
   257     private static class EmulationResources implements Bck2Brwsr.Resources {
   258         @Override
   259         public InputStream get(String name) throws IOException {
   260             if ("java/net/URI.class".equals(name)) {
   261                 // skip
   262                 return null;
   263             }
   264             if ("java/net/URLConnection.class".equals(name)) {
   265                 // skip
   266                 return null;
   267             }
   268             if ("java/lang/System.class".equals(name)) {
   269                 // skip
   270                 return null;
   271             }
   272             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   273             URL u = null;
   274             while (en.hasMoreElements()) {
   275                 u = en.nextElement();
   276             }
   277             if (u == null) {
   278                 throw new IOException("Can't find " + name);
   279             }
   280             if (u.toExternalForm().contains("rt.jar!")) {
   281                 throw new IOException("No emulation for " + u);
   282             }
   283             return u.openStream();
   284         }
   285     }
   286 }