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.
jaroslav@708
     1
/**
jaroslav@708
     2
 * Back 2 Browser Bytecode Translator
jaroslav@708
     3
 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@708
     4
 *
jaroslav@708
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@708
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@708
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@708
     8
 *
jaroslav@708
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@708
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@708
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@708
    12
 * GNU General Public License for more details.
jaroslav@708
    13
 *
jaroslav@708
    14
 * You should have received a copy of the GNU General Public License
jaroslav@708
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@708
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@708
    17
 */
jaroslav@708
    18
package org.apidesign.vm4brwsr;
jaroslav@708
    19
jaroslav@1497
    20
import java.io.ByteArrayInputStream;
jaroslav@708
    21
import java.io.File;
jaroslav@708
    22
import java.io.FileWriter;
jaroslav@708
    23
import java.io.IOException;
jaroslav@708
    24
import java.io.InputStream;
jaroslav@708
    25
import java.net.URL;
jaroslav@708
    26
import java.util.Enumeration;
jaroslav@708
    27
import javax.script.Invocable;
jaroslav@1367
    28
import javax.script.ScriptContext;
jaroslav@708
    29
import javax.script.ScriptEngine;
jaroslav@708
    30
import javax.script.ScriptEngineManager;
jaroslav@708
    31
import javax.script.ScriptException;
jaroslav@708
    32
import static org.testng.Assert.*;
jaroslav@708
    33
jaroslav@1367
    34
public final class TestVM {
jaroslav@708
    35
    private final Invocable code;
jaroslav@708
    36
    private final CharSequence codeSeq;
jaroslav@708
    37
    private final Object bck2brwsr;
jaroslav@1367
    38
    private BytesLoader resources;
jaroslav@708
    39
    
jaroslav@708
    40
    
jaroslav@708
    41
    private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
jaroslav@708
    42
        this.code = code;
jaroslav@708
    43
        this.codeSeq = codeSeq;
jaroslav@1367
    44
        this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
jaroslav@1367
    45
        ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
jaroslav@708
    46
    }
jaroslav@708
    47
    
jaroslav@1367
    48
    public void register(BytesLoader res) {
jaroslav@1367
    49
        this.resources = res;
jaroslav@1367
    50
    }
jaroslav@1367
    51
    
jaroslav@1367
    52
    public byte[] get(String res) throws IOException {
jaroslav@1367
    53
        return resources != null ? resources.get(res) : null;
jaroslav@1367
    54
    }
jaroslav@708
    55
jaroslav@708
    56
    public Object execCode(
jaroslav@708
    57
        String msg, Class<?> clazz, String method, 
jaroslav@708
    58
        Object expRes, Object... args
jaroslav@708
    59
    ) throws Exception {
jaroslav@708
    60
        Object ret = null;
jaroslav@708
    61
        try {
jaroslav@708
    62
            ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
jaroslav@708
    63
            ret = code.invokeMethod(ret, method, args);
jaroslav@708
    64
        } catch (ScriptException ex) {
jaroslav@782
    65
            fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    66
        } catch (NoSuchMethodException ex) {
jaroslav@708
    67
            fail("Cannot find method in " + dumpJS(codeSeq), ex);
jaroslav@708
    68
        }
jaroslav@708
    69
        if (ret == null && expRes == null) {
jaroslav@708
    70
            return null;
jaroslav@708
    71
        }
jaroslav@747
    72
        if (expRes != null && expRes.equals(ret)) {
jaroslav@708
    73
            return null;
jaroslav@708
    74
        }
jaroslav@708
    75
        if (expRes instanceof Number) {
jaroslav@708
    76
            // in case of Long it is necessary convert it to number
jaroslav@708
    77
            // since the Long is represented by two numbers in JavaScript
jaroslav@708
    78
            try {
jaroslav@1392
    79
                final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
jaroslav@1392
    80
                if (ret instanceof Long) {
jaroslav@1392
    81
                    ret = code.invokeMethod(toFP, "call", ret);
jaroslav@1392
    82
                }
jaroslav@708
    83
                ret = code.invokeFunction("Number", ret);
jaroslav@708
    84
            } catch (ScriptException ex) {
jaroslav@784
    85
                fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    86
            } catch (NoSuchMethodException ex) {
jaroslav@784
    87
                fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    88
            }
jaroslav@708
    89
        }
jaroslav@708
    90
        return ret;
jaroslav@708
    91
    }
jaroslav@708
    92
    
jaroslav@708
    93
    void assertExec(
jaroslav@708
    94
        String msg, Class clazz, String method, Object expRes, Object... args
jaroslav@708
    95
    ) throws Exception {
jaroslav@708
    96
        Object ret = execCode(msg, clazz, method, expRes, args);
jaroslav@708
    97
        if (ret == null) {
jaroslav@708
    98
            return;
jaroslav@708
    99
        }
jaroslav@1392
   100
        if (expRes instanceof Integer && ret instanceof Double) {
jaroslav@1392
   101
            expRes = ((Integer)expRes).doubleValue();
jaroslav@1392
   102
        }
jaroslav@708
   103
        if (expRes != null && expRes.equals(ret)) {
jaroslav@708
   104
            return;
jaroslav@708
   105
        }
jaroslav@708
   106
        assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
jaroslav@708
   107
    }    
jaroslav@708
   108
jaroslav@708
   109
    static TestVM compileClass(String... names) throws ScriptException, IOException {
jaroslav@708
   110
        return compileClass(null, names);
jaroslav@708
   111
    }
jaroslav@708
   112
    
jaroslav@708
   113
    static TestVM compileClass(StringBuilder sb, String... names) throws ScriptException, IOException {
jaroslav@708
   114
        return compileClass(sb, null, names);
jaroslav@708
   115
    }
jaroslav@708
   116
jaroslav@708
   117
    static TestVM compileClass(StringBuilder sb, ScriptEngine[] eng, String... names) throws ScriptException, IOException {
jaroslav@708
   118
        if (sb == null) {
jaroslav@708
   119
            sb = new StringBuilder();
jaroslav@708
   120
        }
jaroslav@708
   121
        Bck2Brwsr.generate(sb, new EmulationResources(), names);
jaroslav@708
   122
        ScriptEngineManager sem = new ScriptEngineManager();
jaroslav@708
   123
        ScriptEngine js = sem.getEngineByExtension("js");
jaroslav@708
   124
        if (eng != null) {
jaroslav@708
   125
            eng[0] = js;
jaroslav@708
   126
        }
jaroslav@708
   127
        try {
jaroslav@708
   128
            Object res = js.eval(sb.toString());
jaroslav@708
   129
            assertTrue(js instanceof Invocable, "It is invocable object: " + res);
jaroslav@708
   130
            return new TestVM((Invocable) js, sb);
jaroslav@708
   131
        } catch (Exception ex) {
jaroslav@708
   132
            if (sb.length() > 2000) {
jaroslav@708
   133
                sb = dumpJS(sb);
jaroslav@708
   134
            }
jaroslav@840
   135
            fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
jaroslav@708
   136
            return null;
jaroslav@708
   137
        }
jaroslav@708
   138
    }
jaroslav@1487
   139
    
jaroslav@1497
   140
    static TestVM compileClassAsExtension(
jaroslav@1497
   141
        StringBuilder sb, ScriptEngine[] eng, 
jaroslav@1497
   142
        String name, final String resourceName, final String resourceContent
jaroslav@1497
   143
    ) throws ScriptException, IOException {
jaroslav@1487
   144
        if (sb == null) {
jaroslav@1487
   145
            sb = new StringBuilder();
jaroslav@1487
   146
        }
jaroslav@1497
   147
        if (eng[0] == null) {
jaroslav@1497
   148
            ScriptEngineManager sem = new ScriptEngineManager();
jaroslav@1497
   149
            ScriptEngine js = sem.getEngineByExtension("js");
jaroslav@1497
   150
            eng[0] = js;
jaroslav@1497
   151
            Bck2Brwsr.generate(sb, new EmulationResources());
jaroslav@1497
   152
        }
jaroslav@1487
   153
        Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
jaroslav@1497
   154
            resources(new EmulationResources() {
jaroslav@1497
   155
                @Override
jaroslav@1497
   156
                public InputStream get(String name) throws IOException {
jaroslav@1497
   157
                    if (name.equals(resourceName)) {
jaroslav@1497
   158
                        return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
jaroslav@1497
   159
                    }
jaroslav@1497
   160
                    return super.get(name);
jaroslav@1497
   161
                }
jaroslav@1497
   162
            }).
jaroslav@1558
   163
            addRootClasses(name).
jaroslav@1587
   164
            addResources("org/apidesign/vm4brwsr/obj.js").
jaroslav@1558
   165
            obfuscation(ObfuscationLevel.FULL).
jaroslav@1604
   166
            library();
jaroslav@1497
   167
        if (resourceName != null) {
jaroslav@1497
   168
            b2b = b2b.addResources(resourceName);
jaroslav@1497
   169
        }
jaroslav@1487
   170
        b2b.generate(sb);
jaroslav@1487
   171
        try {
jaroslav@1497
   172
            defineAtoB(eng[0]);
jaroslav@1497
   173
            Object res = eng[0].eval(sb.toString());
jaroslav@1497
   174
            assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
jaroslav@1497
   175
            return new TestVM((Invocable) eng[0], sb);
jaroslav@1487
   176
        } catch (Exception ex) {
jaroslav@1487
   177
            if (sb.length() > 2000) {
jaroslav@1487
   178
                sb = dumpJS(sb);
jaroslav@1487
   179
            }
jaroslav@1487
   180
            fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
jaroslav@1487
   181
            return null;
jaroslav@1487
   182
        }
jaroslav@1487
   183
    }
jaroslav@1493
   184
    
jaroslav@1493
   185
    static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
jaroslav@1493
   186
        if (sb == null) {
jaroslav@1493
   187
            sb = new StringBuilder();
jaroslav@1493
   188
        }
jaroslav@1493
   189
        Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
jaroslav@1493
   190
            resources(new EmulationResources()).
jaroslav@1493
   191
            addRootClasses(name).
jaroslav@1604
   192
            addResources(resources);
jaroslav@1493
   193
        b2b.generate(sb);
jaroslav@1493
   194
        ScriptEngineManager sem = new ScriptEngineManager();
jaroslav@1493
   195
        ScriptEngine js = sem.getEngineByExtension("js");
jaroslav@1493
   196
        if (eng != null) {
jaroslav@1493
   197
            eng[0] = js;
jaroslav@1493
   198
        }
jaroslav@1493
   199
        try {
jaroslav@1497
   200
            defineAtoB(js);
jaroslav@1495
   201
            
jaroslav@1493
   202
            Object res = js.eval(sb.toString());
jaroslav@1493
   203
            assertTrue(js instanceof Invocable, "It is invocable object: " + res);
jaroslav@1493
   204
            return new TestVM((Invocable) js, sb);
jaroslav@1493
   205
        } catch (Exception ex) {
jaroslav@1493
   206
            if (sb.length() > 2000) {
jaroslav@1493
   207
                sb = dumpJS(sb);
jaroslav@1493
   208
            }
jaroslav@1493
   209
            fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
jaroslav@1493
   210
            return null;
jaroslav@1493
   211
        }
jaroslav@1493
   212
    }
jaroslav@840
   213
jaroslav@1497
   214
    private static void defineAtoB(ScriptEngine js) throws ScriptException {
jaroslav@1538
   215
        js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
jaroslav@1497
   216
    }
jaroslav@708
   217
jaroslav@708
   218
    Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
jaroslav@708
   219
        return code.invokeMethod(bck2brwsr, "loadClass", Exceptions.class.getName());
jaroslav@708
   220
    }
jaroslav@708
   221
    
jaroslav@708
   222
    Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
jaroslav@708
   223
        return code.invokeMethod(obj, method, params);
jaroslav@708
   224
    }
jaroslav@708
   225
jaroslav@708
   226
    Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
jaroslav@708
   227
        return code.invokeFunction(methodName, args);
jaroslav@708
   228
    }
jaroslav@708
   229
jaroslav@708
   230
    static StringBuilder dumpJS(CharSequence sb) throws IOException {
jaroslav@708
   231
        File f = File.createTempFile("execution", ".js");
jaroslav@708
   232
        FileWriter w = new FileWriter(f);
jaroslav@708
   233
        w.append(sb);
jaroslav@708
   234
        w.close();
jaroslav@708
   235
        return new StringBuilder(f.getPath());
jaroslav@708
   236
    }
jaroslav@708
   237
jaroslav@708
   238
    @Override
jaroslav@708
   239
    public String toString() {
jaroslav@708
   240
        try {
jaroslav@708
   241
            return dumpJS(codeSeq).toString();
jaroslav@708
   242
        } catch (IOException ex) {
jaroslav@708
   243
            return ex.toString();
jaroslav@708
   244
        }
jaroslav@708
   245
    }
jaroslav@1453
   246
jaroslav@1453
   247
    final CharSequence codeSeq() {
jaroslav@1453
   248
        return codeSeq;
jaroslav@1453
   249
    }
jaroslav@708
   250
    
jaroslav@708
   251
    private static class EmulationResources implements Bck2Brwsr.Resources {
jaroslav@708
   252
        @Override
jaroslav@708
   253
        public InputStream get(String name) throws IOException {
jaroslav@1344
   254
            if ("java/net/URI.class".equals(name)) {
jaroslav@1344
   255
                // skip
jaroslav@1344
   256
                return null;
jaroslav@1344
   257
            }
jaroslav@1404
   258
            if ("java/net/URLConnection.class".equals(name)) {
jaroslav@1404
   259
                // skip
jaroslav@1404
   260
                return null;
jaroslav@1404
   261
            }
jaroslav@1344
   262
            if ("java/lang/System.class".equals(name)) {
jaroslav@1344
   263
                // skip
jaroslav@1344
   264
                return null;
jaroslav@1344
   265
            }
jaroslav@708
   266
            Enumeration<URL> en = StaticMethodTest.class.getClassLoader().getResources(name);
jaroslav@708
   267
            URL u = null;
jaroslav@708
   268
            while (en.hasMoreElements()) {
jaroslav@708
   269
                u = en.nextElement();
jaroslav@708
   270
            }
jaroslav@708
   271
            if (u == null) {
jaroslav@708
   272
                throw new IOException("Can't find " + name);
jaroslav@708
   273
            }
jaroslav@708
   274
            if (u.toExternalForm().contains("rt.jar!")) {
jaroslav@708
   275
                throw new IOException("No emulation for " + u);
jaroslav@708
   276
            }
jaroslav@708
   277
            return u.openStream();
jaroslav@708
   278
        }
jaroslav@708
   279
    }
jaroslav@708
   280
}