rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 11 Oct 2013 09:58:03 +0200
changeset 1367 6193e735f4d1
parent 1344 bb1e59f5cff3
child 1392 da9e5973e699
permissions -rw-r--r--
If a class is not available during Ahead-Of-Time compilation it needs to be ready for dynamic loading
     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.File;
    21 import java.io.FileWriter;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.net.URL;
    25 import java.util.Enumeration;
    26 import javax.script.Invocable;
    27 import javax.script.ScriptContext;
    28 import javax.script.ScriptEngine;
    29 import javax.script.ScriptEngineManager;
    30 import javax.script.ScriptException;
    31 import static org.testng.Assert.*;
    32 
    33 public final class TestVM {
    34     private final Invocable code;
    35     private final CharSequence codeSeq;
    36     private final Object bck2brwsr;
    37     private BytesLoader resources;
    38     
    39     
    40     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    41         this.code = code;
    42         this.codeSeq = codeSeq;
    43         this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
    44         ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
    45     }
    46     
    47     public void register(BytesLoader res) {
    48         this.resources = res;
    49     }
    50     
    51     public byte[] get(String res) throws IOException {
    52         return resources != null ? resources.get(res) : null;
    53     }
    54 
    55     public Object execCode(
    56         String msg, Class<?> clazz, String method, 
    57         Object expRes, Object... args
    58     ) throws Exception {
    59         Object ret = null;
    60         try {
    61             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    62             ret = code.invokeMethod(ret, method, args);
    63         } catch (ScriptException ex) {
    64             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    65         } catch (NoSuchMethodException ex) {
    66             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    67         }
    68         if (ret == null && expRes == null) {
    69             return null;
    70         }
    71         if (expRes != null && expRes.equals(ret)) {
    72             return null;
    73         }
    74         if (expRes instanceof Number) {
    75             // in case of Long it is necessary convert it to number
    76             // since the Long is represented by two numbers in JavaScript
    77             try {
    78                 ret = code.invokeMethod(ret, "toFP");
    79                 ret = code.invokeFunction("Number", ret);
    80             } catch (ScriptException ex) {
    81                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    82             } catch (NoSuchMethodException ex) {
    83                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    84             }
    85         }
    86         return ret;
    87     }
    88     
    89     void assertExec(
    90         String msg, Class clazz, String method, Object expRes, Object... args
    91     ) throws Exception {
    92         Object ret = execCode(msg, clazz, method, expRes, args);
    93         if (ret == null) {
    94             return;
    95         }
    96         if (expRes != null && expRes.equals(ret)) {
    97             return;
    98         }
    99         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
   100     }    
   101 
   102     static TestVM compileClass(String... names) throws ScriptException, IOException {
   103         return compileClass(null, names);
   104     }
   105     
   106     static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
   107         return compileClass(sb, null, names);
   108     }
   109 
   110     static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
   111         if (sb == null) {
   112             sb = new StringBuilder();
   113         }
   114         Bck2Brwsr.generate(sb, new EmulationResources(), names);
   115         ScriptEngineManager sem = new ScriptEngineManager();
   116         ScriptEngine js = sem.getEngineByExtension("js");
   117         if (eng != null) {
   118             eng[0] = js;
   119         }
   120         try {
   121             Object res = js.eval(sb.toString());
   122             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   123             return new TestVM((Invocable) js, sb);
   124         } catch (Exception ex) {
   125             if (sb.length() > 2000) {
   126                 sb = dumpJS(sb);
   127             }
   128             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   129             return null;
   130         }
   131     }
   132 
   133     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   134         return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
   135     }
   136     
   137     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   138         return code.invokeMethod(obj, method, params);
   139     }
   140 
   141     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   142         return code.invokeFunction(methodName, args);
   143     }
   144 
   145     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   146         File f = File.createTempFile("execution", ".js");
   147         FileWriter w = new FileWriter(f);
   148         w.append(sb);
   149         w.close();
   150         return new StringBuilder(f.getPath());
   151     }
   152 
   153     @Override
   154     public String toString() {
   155         try {
   156             return dumpJS(codeSeq).toString();
   157         } catch (IOException ex) {
   158             return ex.toString();
   159         }
   160     }
   161     
   162     
   163     private static class EmulationResources implements Bck2Brwsr.Resources {
   164         @Override
   165         public InputStream get(String name) throws IOException {
   166             if ("java/net/URI.class".equals(name)) {
   167                 // skip
   168                 return null;
   169             }
   170             if ("java/lang/System.class".equals(name)) {
   171                 // skip
   172                 return null;
   173             }
   174             Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
   175             URL u = null;
   176             while (en.hasMoreElements()) {
   177                 u = en.nextElement();
   178             }
   179             if (u == null) {
   180                 throw new IOException("Can't find " + name);
   181             }
   182             if (u.toExternalForm().contains("rt.jar!")) {
   183                 throw new IOException("No emulation for " + u);
   184             }
   185             return u.openStream();
   186         }
   187     }
   188 }