Java 类javax.script.ScriptEngine 实例源码

项目:crawler    文件:CrawlerUtils.java   
public Object executeJs(String js,@Nullable String funcName,Object... args){
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
        Object res=engine.eval(js);
        if(StringUtils.isNotBlank(funcName)){
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable) engine;
                res = invoke.invokeFunction(funcName, args);
            }
        }
        return res;
    } catch (Exception e) {
        log.error("",e);
    }
    return null;
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:react-native-console    文件:TestParseIOSDevices.java   
@Test
    public void testJS() {
        // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
            engine.put("line", "刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]");
//            engine.put("regex", )
            String regex = "/(.*?) \\((.*?)\\) \\[(.*?)\\]/";
            String[] value = (String[])engine.eval("Java.to(line.match(" + regex + "),\"java.lang.String[]\" );");
            System.out.println(value.length);
            System.out.println(value[1]);
            String[] result = {"刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]",
                    "刘长炯 微信号weblogic", "10.3.2", "46a5432f8fdea99a6186a927e8da5db7a51854ac"};
            Assert.assertArrayEquals("result shold match", result, value);
//            Collection<Object> val = value.values();
//            if(value.isArray()) {
//                System.out.println(value.getMember("1"));
//            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that calling method on mirror created by another engine results in
 * IllegalArgumentException.
 */
public void invokeMethodMixEnginesTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine1 = m.getEngineByName("nashorn");
    final ScriptEngine engine2 = m.getEngineByName("nashorn");

    try {
        final Object obj = engine1.eval("({ run: function() {} })");
        // pass object from engine1 to engine2 as 'thiz' for invokeMethod
        ((Invocable) engine2).invokeMethod(obj, "run");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:EatDubbo    文件:ScriptRouter.java   
public ScriptRouter(URL url) {
    this.url = url;
    String type = url.getParameter(Constants.TYPE_KEY);
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
    if (type == null || type.length() == 0){
        type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
    }
    if (rule == null || rule.length() == 0){
        throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule));
    }
    ScriptEngine engine = engines.get(type);
    if (engine == null){
        engine = new ScriptEngineManager().getEngineByName(type);
        if (engine == null) {
            throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule));
        }
        engines.put(type, engine);
    }
    this.engine = engine;
    this.rule = rule;
}
项目:Java-9-Cookbook    文件:EmbeddedNashornDemo.java   
public static void main(String[] args) throws Exception{

    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine("--language=es6");

    //Javascript function
    engine.eval("function sum(a, b) { return a + b; }");
    System.out.println(engine.eval("sum(1, 2);"));

    //Template strings
    engine.eval("let name = 'Sanaulla'");
    System.out.println(engine.eval("print(`Hello Mr. ${name}`)"));

    //Set
    engine.eval("var s = new Set(); s.add(1).add(2).add(3).add(4).add(5).add(6);");
    System.out.println("Set elements");
    engine.eval("for (let e of s) { print(e); }");

    //Reading Javascript source
    engine.eval(new FileReader("src/embedded.nashorn/com/packt/embeddable.js"));
    int difference = (int)engine.eval("difference(1, 2);");
    System.out.println("Difference between 1, 2 is: " + difference);
}
项目:slardar    文件:TestMain.java   
public static void main(String[] args) {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine engine = engineManager.getEngineByName("javascript");
        try {
//            UserVO user = new UserVO();
//            user.setId(1000);
//            user.setUsername("xingtianyu");
//            Map<String,Object> usermap = new HashMap<>();
//            usermap.put("id",user.getId());
//            usermap.put("username",user.getUsername());
            JSContext context = new JSContext();
            engine.put(JSContext.CONTEXT,context.getCtx());
            engine.eval(new FileReader("/home/code4j/IDEAWorkspace/myutils/myutils-slardar/src/main/resources/mapper/usermapper.js"));
            Invocable func = (Invocable)engine;
//            Map<String,Object> resultMap = (Map<String, Object>) func.invokeFunction("findUserByCondition",usermap);
//            Map<String,Object> paramMap = (Map<String, Object>) resultMap.get("param");
//            System.out.println(resultMap.get("sql"));
//            System.out.println(paramMap.get("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
项目:JShellScriptEngine    文件:JShellScriptEngineFactory.java   
@Override
public Object getParameter(String key) {
    switch(key) {
        case ScriptEngine.ENGINE:
            return getEngineName();
        case ScriptEngine.ENGINE_VERSION:
            return getEngineVersion();
        case ScriptEngine.LANGUAGE:
            return getLanguageName();
        case ScriptEngine.LANGUAGE_VERSION:
            return getLanguageVersion();
        case ScriptEngine.NAME:
            return getNames().get(0);
        default:
            return null;
    }
}
项目:uppercore    文件:ScriptRegistry.java   
protected static ScriptId load(Plugin plugin, String id, String script, String ext) throws ScriptException {
    ScriptManager manager = scripts();
    final String engineName = manager.getExtensionsToEngineName().get(ext);
    if (engineName == null)
        throw new IllegalArgumentException("Cannot find engine for \"" + ext + "\"");
    ScriptEngine engine;
    {//Load the engine
        final Thread currentThread = Thread.currentThread();
        final ClassLoader oldLoader = currentThread.getContextClassLoader();
        try {
            currentThread.setContextClassLoader(manager.getClassLoader());
            engine = manager.getEngineManager().getEngineByName(engineName);
        } finally {
            currentThread.setContextClassLoader(oldLoader);
        }
    }
    if (engine == null)
        throw new IllegalStateException("Cannot find engine \"" + engineName + "\"");
    return new ScriptId(plugin, id, Script.of(engine, script));
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void argumentsWithTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    final String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        final Object arg0 = e.eval("var imports = new JavaImporter(java.io); " +
                " with(imports) { arguments[0] }");
        final Object arg1 = e.eval("var imports = new JavaImporter(java.util, java.io); " +
                " with(imports) { arguments[1] }");
        assertEquals(args[0], arg0);
        assertEquals(args[1], arg1);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that invokeMethod throws NoSuchMethodException on missing method.
 */
public void invokeMethodMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, "nonExistentMethod");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void argumentsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    final String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        final Object arg0 = e.eval("arguments[0]");
        final Object arg1 = e.eval("arguments[1]");
        assertEquals(args[0], arg0);
        assertEquals(args[1], arg1);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:incubator-netbeans    文件:NbPacScriptEvaluator.java   
private boolean isJsFunctionAvailable(ScriptEngine eng, String functionName, boolean doDeepTest) {
    // We want to test if the function is there, but without actually 
    // invoking it.        
    Object obj = eng.get(functionName);

    if (!doDeepTest && obj != null) {  
        // Shallow test. We've established that there's
        // "something" in the ENGINE_SCOPE with a name like
        // functionName, and we *hope* it is a function, but we really don't
        // know, therefore we call it a shallow test.
        return true;
    }

    // For Nashorn post JDK8u40 we can do even deeper validation
    // using the ScriptObjectMirror class. This will not work for Rhino.
    if (doDeepTest && obj != null) {
        if (obj instanceof ScriptObjectMirror) {
                ScriptObjectMirror  som = (ScriptObjectMirror) obj;
                if (som.isFunction()) {
                    return true;
                }
        }
    }        
    return false;
}
项目:openjdk-jdk10    文件:ScriptObjectMirrorTest.java   
@Test
public void mapScriptObjectMirrorCallsiteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("nashorn");
    final String TEST_SCRIPT = "typeof obj.foo";

    final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    engine.eval("var obj = java.util.Collections.emptyMap()");
    // this will drive callsite "obj.foo" of TEST_SCRIPT
    // to use "obj instanceof Map" as it's guard
    engine.eval(TEST_SCRIPT, global);
    // redefine 'obj' to be a script object
    engine.eval("obj = {}");

    final Bindings newGlobal = engine.createBindings();
    // transfer 'obj' from default global to new global
    // new global will get a ScriptObjectMirror wrapping 'obj'
    newGlobal.put("obj", global.get("obj"));

    // Every ScriptObjectMirror is a Map! If callsite "obj.foo"
    // does not see the new 'obj' is a ScriptObjectMirror, it'll
    // continue to use Map's get("obj.foo") instead of ScriptObjectMirror's
    // getMember("obj.foo") - thereby getting null instead of undefined
    assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal));
}
项目:openjdk-jdk10    文件:TrustedScriptEngineTest.java   
@Test
public void globalPerEngineTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final String[] options = new String[] { "--global-per-engine" };
    final ScriptEngine e = fac.getScriptEngine(options);

    e.eval("function foo() {}");

    final ScriptContext newCtx = new SimpleScriptContext();
    newCtx.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);

    // all global definitions shared and so 'foo' should be
    // visible in new Bindings as well.
    assertTrue(e.eval("typeof foo", newCtx).equals("function"));

    e.eval("function bar() {}", newCtx);

    // bar should be visible in default context
    assertTrue(e.eval("typeof bar").equals("function"));
}
项目:Nadia    文件:IterateLine_1.java   
private void forwardChaining(int nodeIndex, ScriptEngine nashorn) 
{
    IntStream.range(0, nodeIndex+1).forEach(i -> {

            Node node = this.iterativeTopoSortedList.get(nodeIndex-i);

            if(this.iterativeInclusiveList.contains(node.getNodeName()))
            {
                backPropagation(nodeIndex-i, nashorn);
            }


        if(this.iterateWorkingMemory.containsKey(node.getVariableName()) || this.iterateWorkingMemory.containsKey(node.getNodeName()))
        {
                addParentIntoInclusiveList(node); // adding all parents rules into the 'inclusiveList' if there is any
        }

    });     
}
项目:manifold    文件:JavascriptTemplate.java   
public static String renderToStringImpl(ScriptEngine engine, JSTNode templateNode, Object... args) {
  try {
    //make argument list including the raw string list
    Object[] argsWithStrings = Arrays.copyOf(args, args.length + 1);

    List rawStrings = templateNode.getChildren(RawStringNode.class)
      .stream()
      .map(node -> node.genCode())
      .collect(Collectors.toList());

    argsWithStrings[argsWithStrings.length - 1] = rawStrings;

    String ret = (String) ((Invocable) engine).invokeFunction("renderToString", argsWithStrings);
    return ret;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:v8-adapter    文件:V8ScriptingEngineFactory.java   
@Override
public Object getParameter(String key) {
    if (key.equals(ScriptEngine.ENGINE)) {
        return getEngineName();
    } else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
        return getEngineVersion();
    } else if (key.equals(ScriptEngine.LANGUAGE)) {
        return getLanguageName();
    } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
        return getLanguageVersion();
    } else if (key.equals(ScriptEngine.NAME)) {
        return getNames().get(0);
    } else if (key.equals("THREADING")) {

        // TODO:
        return "MULTITHREADED";
    }

    return null;
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void createBindingsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    b.put("foo", 42.0);
    Object res = null;
    try {
        res = e.eval("foo == 42.0", b);
    } catch (final ScriptException | NullPointerException se) {
        se.printStackTrace();
        fail(se.getMessage());
    }

    assertEquals(res, Boolean.TRUE);
}
项目:openjdk-jdk10    文件:ScopeTest.java   
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
项目:mo-vnfcp    文件:Main.java   
public static void testScriptEngine() throws Exception {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine js = sem.getEngineByName("JavaScript");
    js.eval("blubb = 1\n" +
            "muh = blubb + 2\n" +
            "// just a comment...\n" +
            "crap = \"asd\"");
    System.out.println(js.get("muh").getClass());

    System.out.println("Testing ScriptEngine Performance...");
    long start = System.currentTimeMillis();
    Config c = Config.getInstance(new FileInputStream("res/customConfig.js"));
    double[] d = new double[]{1.0, 7.5, 1.3+2.5+6.3+3.1, 6.0};;
    for (int i = 0; i < 100000; i++) {
        //c.pReassignVnf(i);
        //d = new double[]{d[0] + 1.0, d[1] - 0.5, d[0] + d[1], d[3] * 1.1};
        c.objectiveVector(new double[Solution.Vals.values().length]);
    }
    System.out.println(Arrays.toString(d));
    long dur = System.currentTimeMillis() - start;
    System.out.println("Duration: " + dur + "ms");
    System.out.println(c.topologyFile.toAbsolutePath().toString());
}
项目:openjdk-jdk10    文件:TrustedScriptEngineTest.java   
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that calling method on null 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(null, "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
private L2ScriptEngineManager()
{
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
    if (USE_COMPILED_CACHE)
        _cache = this.loadCompiledScriptCache();
    else
        _cache = null;
    _log.info("Initializing Script Engine Manager");
    for (ScriptEngineFactory factory : factories)
        try
        {
            ScriptEngine engine = factory.getScriptEngine();
            boolean reg = false;
            for (String name : factory.getNames())
            {
                ScriptEngine existentEngine = _nameEngines.get(name);
                if (existentEngine != null)
                {
                    double engineVer = Double.parseDouble(factory.getEngineVersion());
                    double existentEngVer = Double.parseDouble(existentEngine.getFactory().getEngineVersion());
                    if (engineVer <= existentEngVer)
                        continue;
                }
                reg = true;
                _nameEngines.put(name, engine);
            }
            if (reg)
                _log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion() + " - Language: " + factory.getLanguageName() + " - Language Version: " + factory.getLanguageVersion());
            for (String ext : factory.getExtensions())
                if (!ext.equals("java") || factory.getLanguageName().equals("java"))
                    _extEngines.put(ext, engine);
        }
        catch (Exception e)
        {
            _log.warning("Failed initializing factory. ");
            e.printStackTrace();
        }
    this.preConfigure();
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void redefineEchoTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var echo = {}; if (typeof echo !== 'object') { throw 'echo is a '+typeof echo; }");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
public void executeScript(File file) throws ScriptException, FileNotFoundException
{
    String name = file.getName();
    int lastIndex = name.lastIndexOf('.');
    String extension;
    if (lastIndex != -1)
        extension = name.substring(lastIndex + 1);
    else
        throw new ScriptException("Script file (" + name + ") doesnt has an extension that identifies the ScriptEngine to be used.");
    ScriptEngine engine = this.getEngineByExtension(extension);
    if (engine == null)
        throw new ScriptException("No engine registered for extension (" + extension + ")");
    else
        this.executeScript(engine, file);
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void exposeGlobalTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.put("y", "foo");
        e.eval("print(y)");
    } catch (final ScriptException exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:GuildBot    文件:EngineMap.java   
public EngineMap()
{
    this.map = Collections.synchronizedMap(new EnumMap<>(Engine.class));

    final ScriptEngine js = Engine.JAVASCRIPT.newScriptEngine();
    this.map.put(Engine.JAVASCRIPT, js);

    try
    {
        js.eval("engines = {}");
    }
    catch (final ScriptException e)
    {
        throw new RuntimeException(e); // should never happen
    }

    final Bindings engines = (Bindings) js.get("engines");
    engines.put("js", js);

    this.context = js.getContext();
    engines.put("context", this.context);

    for (final Engine engine : Engine.values())
        this.map.computeIfAbsent(engine, e ->
        {
            final ScriptEngine scriptEngine = e.newScriptEngine(this.context);
            ((Bindings) scriptEngine.get("engines")).put(e.getName(), scriptEngine);
            return scriptEngine;
        });
}
项目:openjdk-jdk10    文件:JavaAdapterTest.java   
@Test
public static void testConversions() throws ScriptException {
    final ScriptEngine e = createEngine();
    e.put("TestConversionsClass", TestConversions.class);
    final TestConversions tc = (TestConversions)e.eval(
            "function id(x) { return x };" +
            "new TestConversionsClass.static({" +
            "  getByte: id, getShort: id, getChar: id, getInt: id," +
            "  getFloat: id, getLong: id, getDouble: id });");

    Assert.assertEquals(Byte.MIN_VALUE, tc.getByte(Byte.MIN_VALUE));
    Assert.assertEquals(Byte.MAX_VALUE, tc.getByte(Byte.MAX_VALUE));

    Assert.assertEquals(Short.MIN_VALUE, tc.getShort(Short.MIN_VALUE));
    Assert.assertEquals(Short.MAX_VALUE, tc.getShort(Short.MAX_VALUE));

    Assert.assertEquals(Character.MIN_VALUE, tc.getChar(Character.MIN_VALUE));
    Assert.assertEquals(Character.MAX_VALUE, tc.getChar(Character.MAX_VALUE));

    Assert.assertEquals(Integer.MIN_VALUE, tc.getInt(Integer.MIN_VALUE));
    Assert.assertEquals(Integer.MAX_VALUE, tc.getInt(Integer.MAX_VALUE));

    Assert.assertEquals(Long.MIN_VALUE, tc.getLong(Long.MIN_VALUE));
    Assert.assertEquals(Long.MAX_VALUE, tc.getLong(Long.MAX_VALUE));

    Assert.assertEquals(Float.MIN_VALUE, tc.getFloat(Float.MIN_VALUE));
    Assert.assertEquals(Float.MAX_VALUE, tc.getFloat(Float.MAX_VALUE));
    Assert.assertEquals(Float.MIN_NORMAL, tc.getFloat(Float.MIN_NORMAL));
    Assert.assertEquals(Float.POSITIVE_INFINITY, tc.getFloat(Float.POSITIVE_INFINITY));
    Assert.assertEquals(Float.NEGATIVE_INFINITY, tc.getFloat(Float.NEGATIVE_INFINITY));
    Assert.assertTrue(Float.isNaN(tc.getFloat(Float.NaN)));

    Assert.assertEquals(Double.MIN_VALUE, tc.getDouble(Double.MIN_VALUE));
    Assert.assertEquals(Double.MAX_VALUE, tc.getDouble(Double.MAX_VALUE));
    Assert.assertEquals(Double.MIN_NORMAL, tc.getDouble(Double.MIN_NORMAL));
    Assert.assertEquals(Double.POSITIVE_INFINITY, tc.getDouble(Double.POSITIVE_INFINITY));
    Assert.assertEquals(Double.NEGATIVE_INFINITY, tc.getDouble(Double.NEGATIVE_INFINITY));
    Assert.assertTrue(Double.isNaN(tc.getDouble(Double.NaN)));
}
项目:RefDiff    文件:EsprimaParser.java   
public EsprimaParser() throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    engine.eval("load('classpath:esprima.js');");
    engine.eval("function parse(script) {return esprima.parseModule(script, {range: true});}");
    engine.eval("function tokenize(source) {return esprima.tokenize(source, {comment: true});}");
    engine.eval("function toJson(object) {return JSON.stringify(object);}");
    this.invocableScript = (Invocable) engine;
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public static void testMegamorphicGetInGlobal() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("nashorn");
    final String script = "foo";
    // "foo" is megamorphic because of different global scopes.
    // Make sure ScriptContext variable search works even after
    // it becomes megamorphic.
    for (int index = 0; index < 25; index++) {
        final Bindings bindings = new SimpleBindings();
        bindings.put("foo", index);
        final Number value = (Number)engine.eval(script, bindings);
        assertEquals(index, value.intValue());
    }
}
项目:Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming    文件:Processor.java   
private void execute(final String scriptFileName, final String engineName)
        throws ScriptException, FileNotFoundException {
    final ScriptEngineManager factory = new ScriptEngineManager();
    final ScriptEngine engine;
    if (engineName != null && engineName.length() > 0) {
        engine = factory.getEngineByName(engineName);
    } else {
        engine = factory
                .getEngineByExtension(getExtensionFrom(scriptFileName));
    }
    Reader scriptFileReade = new FileReader(new File(scriptFileName));
    engine.eval(scriptFileReade);
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public static void contextOverwriteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = new SimpleBindings();
    b.put("context", "hello");
    b.put("foo", 32);
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    e.setContext(newCtxt);
    assertEquals(e.eval("context"), "hello");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
项目:openjdk-jdk10    文件:JavaAdapterTest.java   
@Test
public static void testMaxLengthAdapter() throws ScriptException {
    final ScriptEngine e = createEngine();
    e.put("MaxParams", MaxParams.class);
    final MaxParams s = (MaxParams) e.eval("new MaxParams.static(function(){ return arguments })");
    final ScriptObjectMirror m = (ScriptObjectMirror)s.method(true, Byte.MIN_VALUE, Short.MIN_VALUE, 'a', Integer.MAX_VALUE, Float.MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE,
            "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",
            "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44",
            "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62",
            "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80",
            "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98",
            "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114",
            "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127", "128", "129", "130",
            "131", "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", "143", "144", "145", "146",
            "147", "148", "149", "150", "151", "152", "153", "154", "155", "156", "157", "158", "159", "160", "161", "162",
            "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", "176", "177", "178",
            "179", "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", "190", "191", "192", "193", "194",
            "195", "196", "197", "198", "199", "200", "201", "202", "203", "204", "205", "206", "207", "208", "209", "210",
            "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222", "223", "224", "225", "226",
            "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", "242",
            "243", "244", "245", "246", "247", "248", "249", "250", "251");
    Assert.assertEquals(true, m.getSlot(0));
    Assert.assertEquals(Integer.valueOf(Byte.MIN_VALUE), m.getSlot(1)); // Byte becomes Integer
    Assert.assertEquals(Integer.valueOf(Short.MIN_VALUE), m.getSlot(2)); // Short becomes Integer
    Assert.assertEquals(Character.valueOf('a'), m.getSlot(3));
    Assert.assertEquals(Integer.valueOf(Integer.MAX_VALUE), m.getSlot(4));
    Assert.assertEquals(Double.valueOf(Float.MAX_VALUE), m.getSlot(5)); // Float becomes Double
    Assert.assertEquals(Long.valueOf(Long.MAX_VALUE), m.getSlot(6)); // Long was untouched
    Assert.assertEquals(Double.valueOf(Double.MAX_VALUE), m.getSlot(7));
    for (int i = 8; i < 252; ++i) {
        Assert.assertEquals(String.valueOf(i), m.getSlot(i));
    }
}
项目:manifold    文件:JavascriptClass.java   
static SrcClass genClass(String fqn, ProgramNode programNode) {

        ClassNode classNode = programNode.getFirstChild(ClassNode.class);

        SrcClass clazz = new SrcClass(fqn, SrcClass.Kind.Class);
        clazz.addAnnotation(
          new SrcAnnotationExpression( SourcePosition.class )
            .addArgument( "url", String.class, programNode.getUrl().toString() )
            .addArgument( "feature", String.class, ManClassUtil.getShortClassName( fqn ) )
            .addArgument( "offset", int.class, classNode.getStart().getOffset() )
            .addArgument( "length", int.class, classNode.getEnd().getOffset() - classNode.getStart().getOffset() ) );

        String superClass = classNode.getSuperClass();
        if (superClass != null) {
            clazz.superClass(superClass);
        }
        clazz.imports(JavascriptClass.class)
          .imports( SourcePosition.class );

        clazz.addField(new SrcField("ENGINE", ScriptEngine.class)
                .modifiers(Modifier.PRIVATE | Modifier.STATIC | Modifier.VOLATILE)
                .initializer(new SrcRawExpression(("null"))));

        clazz.addField(new SrcField("TIMESTAMP", long.class)
                .modifiers(Modifier.PRIVATE | Modifier.STATIC | Modifier.VOLATILE)
                .initializer(new SrcRawExpression(("0"))));


        clazz.addField(new SrcField("_context", ScriptObjectMirror.class));

        addConstructor(clazz, classNode);
        addUtilityMethods( clazz, classNode, fqn );
        addMethods(fqn, clazz, classNode);
        addProperties(fqn, clazz, classNode);

        return clazz;
    }
项目:incubator-netbeans    文件:ScriptingCreateFromTemplateHandler.java   
private static ScriptEngine engine(FileObject fo) {
    Object obj = fo.getAttribute(SCRIPT_ENGINE_ATTR); // NOI18N
    if (obj instanceof ScriptEngine) {
        return (ScriptEngine)obj;
    }
    if (obj instanceof String) {
        return getEngine((String)obj);
    }
    return null;
}
项目:openjdk-jdk10    文件:JSONCompatibleTest.java   
/**
 * Wrap an embedded array as a list.
 */
@Test
public void testWrapObjectWithArray() throws ScriptException {
    final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine();
    final Object val = engine.eval("Java.asJSONCompatible({x: [1, 2, 3]})");
    assertEquals(asList(asMap(val).get("x")), Arrays.asList(1, 2, 3));
}
项目:openjdk-jdk10    文件:NashornScriptEngineFactory.java   
@Override
public ScriptEngine getScriptEngine() {
    try {
        return new NashornScriptEngine(this, DEFAULT_OPTIONS, getAppClassLoader(), null);
    } catch (final RuntimeException e) {
        if (Context.DEBUG) {
            e.printStackTrace();
        }
        throw e;
    }
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void testLengthOnArrayLikeObjects() throws Exception {
    final ScriptEngine e = new ScriptEngineManager().getEngineByName("nashorn");
    final Object val = e.eval("var arr = { length: 1, 0: 1}; arr.length");

    assertTrue(Number.class.isAssignableFrom(val.getClass()));
    assertTrue(((Number)val).intValue() == 1);
}