rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 27 May 2014 12:25:41 +0200
branchclosure
changeset 1604 7665471a56c1
parent 1587 bf08bd96d408
child 1609 752f48257d4a
permissions -rw-r--r--
The static calculator demo needs to reference just a single application .js file from its main HTML page. The rest is loaded based on classpath attribute.
     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();
   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         b2b.generate(sb);
   194         ScriptEngineManager sem = new ScriptEngineManager();
   195         ScriptEngine js = sem.getEngineByExtension("js");
   196         if (eng != null) {
   197             eng[0] = js;
   198         }
   199         try {
   200             defineAtoB(js);
   201             
   202             Object res = js.eval(sb.toString());
   203             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   204             return new TestVM((Invocable) js, sb);
   205         } catch (Exception ex) {
   206             if (sb.length() > 2000) {
   207                 sb = dumpJS(sb);
   208             }
   209             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   210             return null;
   211         }
   212     }
   213 
   214     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   215         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   216     }
   217 
   218     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   219         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   220     }
   221     
   222     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   223         return code.invokeMethod(obj, method, params);
   224     }
   225 
   226     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   227         return code.invokeFunction(methodName, args);
   228     }
   229 
   230     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   231         File f = File.createTempFile("execution", ".js");
   232         FileWriter w = new FileWriter(f);
   233         w.append(sb);
   234         w.close();
   235         return new StringBuilder(f.getPath());
   236     }
   237 
   238     @Override
   239     public String toString() {
   240         try {
   241             return dumpJS(codeSeq).toString();
   242         } catch (IOException ex) {
   243             return ex.toString();
   244         }
   245     }
   246 
   247     final CharSequence codeSeq() {
   248         return codeSeq;
   249     }
   250     
   251     private static class EmulationResources implements Bck2Brwsr.Resources {
   252         @Override
   253         public InputStream get(String name) throws IOException {
   254             if ("java/net/URI.class".equals(name)) {
   255                 // skip
   256                 return null;
   257             }
   258             if ("java/net/URLConnection.class".equals(name)) {
   259                 // skip
   260                 return null;
   261             }
   262             if ("java/lang/System.class".equals(name)) {
   263                 // skip
   264                 return null;
   265             }
   266             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   267             URL u = null;
   268             while (en.hasMoreElements()) {
   269                 u = en.nextElement();
   270             }
   271             if (u == null) {
   272                 throw new IOException("Can't find " + name);
   273             }
   274             if (u.toExternalForm().contains("rt.jar!")) {
   275                 throw new IOException("No emulation for " + u);
   276             }
   277             return u.openStream();
   278         }
   279     }
   280 }