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