rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 09 Jan 2015 20:46:35 +0100
changeset 1762 293838e72201
parent 1722 fd3a354d6e8f
child 1787 ea12a3bb4b33
permissions -rw-r--r--
Always write down the JavaScript file in UTF-8 encoding
     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.FileOutputStream;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.io.OutputStreamWriter;
    26 import java.io.Writer;
    27 import java.net.URL;
    28 import java.util.ArrayList;
    29 import java.util.Arrays;
    30 import java.util.Enumeration;
    31 import java.util.HashSet;
    32 import java.util.List;
    33 import java.util.Set;
    34 import javax.script.Invocable;
    35 import javax.script.ScriptContext;
    36 import javax.script.ScriptEngine;
    37 import javax.script.ScriptEngineManager;
    38 import javax.script.ScriptException;
    39 import static org.testng.Assert.*;
    40 
    41 public final class TestVM {
    42     private final Invocable code;
    43     private final CharSequence codeSeq;
    44     private final Object bck2brwsr;
    45     private BytesLoader resources;
    46     
    47     
    48     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    49         this.code = code;
    50         this.codeSeq = codeSeq;
    51         this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
    52         ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
    53     }
    54     
    55     public void register(BytesLoader res) {
    56         this.resources = res;
    57     }
    58     
    59     public byte[] get(String res) throws IOException {
    60         return resources != null ? resources.get(res) : null;
    61     }
    62 
    63     public Object execCode(
    64         String msg, Class<?> clazz, String method, 
    65         Object expRes, Object... args
    66     ) throws Exception {
    67         Object ret = null;
    68         try {
    69             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    70             List<Object> ma = new ArrayList<>();
    71             ma.add(method);
    72             ma.addAll(Arrays.asList(args));
    73             ret = code.invokeMethod(ret, "invoke", ma.toArray());
    74         } catch (ScriptException ex) {
    75             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    76         } catch (NoSuchMethodException ex) {
    77             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    78         }
    79         if (ret == null && expRes == null) {
    80             return null;
    81         }
    82         if (expRes != null && expRes.equals(ret)) {
    83             return null;
    84         }
    85         if (expRes instanceof Number) {
    86             // in case of Long it is necessary convert it to number
    87             // since the Long is represented by two numbers in JavaScript
    88             try {
    89                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    90                 if (ret instanceof Long) {
    91                     ret = code.invokeMethod(toFP, "call", ret);
    92                 }
    93                 ret = code.invokeFunction("Number", ret);
    94             } catch (ScriptException ex) {
    95                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    96             } catch (NoSuchMethodException ex) {
    97                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    98             }
    99         }
   100         return ret;
   101     }
   102     
   103     void assertExec(
   104         String msg, Class clazz, String method, Object expRes, Object... args
   105     ) throws Exception {
   106         Object ret = execCode(msg, clazz, method, expRes, args);
   107         if (ret == null) {
   108             return;
   109         }
   110         if (expRes instanceof Integer && ret instanceof Double) {
   111             expRes = ((Integer)expRes).doubleValue();
   112         }
   113         if (expRes != null && expRes.equals(ret)) {
   114             return;
   115         }
   116         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
   117     }    
   118 
   119     static TestVM compileClass(String... names) throws ScriptException, IOException {
   120         return compileClass(null, names);
   121     }
   122     
   123     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   124         return compileClass(sb, null, names);
   125     }
   126 
   127     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   128         return compileClass(sb, eng, new EmulationResources(), names);
   129     }
   130     static TestVM compileClass(
   131         StringBuilder sb, 
   132         ScriptEngine[] eng, 
   133         Bck2Brwsr.Resources resources, 
   134         String... names
   135     ) throws ScriptException, IOException {
   136         if (sb == null) {
   137             sb = new StringBuilder();
   138         }
   139         Bck2Brwsr.generate(sb, resources, names);
   140         ScriptEngineManager sem = new ScriptEngineManager();
   141         ScriptEngine js = sem.getEngineByExtension("js");
   142         if (eng != null) {
   143             eng[0] = js;
   144         }
   145         try {
   146             Object res = js.eval(sb.toString());
   147             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   148             return new TestVM((Invocable) js, sb);
   149         } catch (Exception ex) {
   150             if (sb.length() > 2000) {
   151                 sb = dumpJS(sb);
   152             }
   153             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   154             return null;
   155         }
   156     }
   157     
   158     static TestVM compileClassAsExtension(
   159         StringBuilder sb, ScriptEngine[] eng, 
   160         String name, final String resourceName, final String resourceContent
   161     ) throws ScriptException, IOException {
   162         return compileClassesAsExtension(sb, eng, resourceName, resourceContent, name);
   163     }
   164     static TestVM compileClassesAsExtension(
   165         StringBuilder sb, ScriptEngine[] eng, 
   166         final String resourceName, final String resourceContent, String... names
   167     ) throws ScriptException, IOException {
   168         if (sb == null) {
   169             sb = new StringBuilder();
   170         }
   171         if (eng[0] == null) {
   172             ScriptEngineManager sem = new ScriptEngineManager();
   173             ScriptEngine js = sem.getEngineByExtension("js");
   174             eng[0] = js;
   175             Bck2Brwsr.newCompiler().resources(new EmulationResources())
   176                 .obfuscation(ObfuscationLevel.NONE).generate(sb);
   177         }
   178         Set<String> exp = new HashSet<String>();
   179         for (String n : names) {
   180             int last = n.lastIndexOf('/');
   181             exp.add(n.substring(0, last + 1));
   182         }
   183         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   184             resources(new EmulationResources() {
   185                 @Override
   186                 public InputStream get(String name) throws IOException {
   187                     if (name.equals(resourceName)) {
   188                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   189                     }
   190                     return super.get(name);
   191                 }
   192             }).
   193             addClasses(names).
   194             addResources("org/apidesign/vm4brwsr/obj.js").
   195             addExported(exp.toArray(new String[0])).
   196             obfuscation(ObfuscationLevel.FULL).
   197             library();
   198         if (resourceName != null) {
   199             b2b = b2b.addResources(resourceName);
   200         }
   201         b2b.generate(sb);
   202         try {
   203             defineAtoB(eng[0]);
   204             Object res = eng[0].eval(sb.toString());
   205             assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
   206             return new TestVM((Invocable) eng[0], sb);
   207         } catch (Exception ex) {
   208             if (sb.length() > 2000) {
   209                 sb = dumpJS(sb);
   210             }
   211             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   212             return null;
   213         }
   214     }
   215     
   216     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   217         if (sb == null) {
   218             sb = new StringBuilder();
   219         }
   220         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   221             resources(new EmulationResources()).
   222             addRootClasses(name).
   223             addResources(resources);
   224         b2b.generate(sb);
   225         ScriptEngineManager sem = new ScriptEngineManager();
   226         ScriptEngine js = sem.getEngineByExtension("js");
   227         if (eng != null) {
   228             eng[0] = js;
   229         }
   230         try {
   231             defineAtoB(js);
   232             
   233             Object res = js.eval(sb.toString());
   234             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   235             return new TestVM((Invocable) js, sb);
   236         } catch (Exception ex) {
   237             if (sb.length() > 2000) {
   238                 sb = dumpJS(sb);
   239             }
   240             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   241             return null;
   242         }
   243     }
   244 
   245     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   246         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   247     }
   248 
   249     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   250         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   251     }
   252     
   253     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   254         return code.invokeMethod(obj, method, params);
   255     }
   256 
   257     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   258         return code.invokeFunction(methodName, args);
   259     }
   260 
   261     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   262         File f = File.createTempFile("execution", ".js");
   263         Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
   264         w.append(sb);
   265         w.close();
   266         return new StringBuilder(f.getPath());
   267     }
   268 
   269     @Override
   270     public String toString() {
   271         try {
   272             return dumpJS(codeSeq).toString();
   273         } catch (IOException ex) {
   274             return ex.toString();
   275         }
   276     }
   277 
   278     final CharSequence codeSeq() {
   279         return codeSeq;
   280     }
   281     
   282     private static class EmulationResources implements Bck2Brwsr.Resources {
   283         @Override
   284         public InputStream get(String name) throws IOException {
   285             if ("java/net/URI.class".equals(name)) {
   286                 // skip
   287                 return null;
   288             }
   289             if ("java/net/URLConnection.class".equals(name)) {
   290                 // skip
   291                 return null;
   292             }
   293             if ("java/lang/System.class".equals(name)) {
   294                 // skip
   295                 return null;
   296             }
   297             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   298             URL u = null;
   299             while (en.hasMoreElements()) {
   300                 u = en.nextElement();
   301             }
   302             if (u == null) {
   303                 throw new IOException("Can't find " + name);
   304             }
   305             if (u.toExternalForm().contains("rt.jar!")) {
   306                 throw new IOException("No emulation for " + u);
   307             }
   308             return u.openStream();
   309         }
   310     }
   311 }