Java Code Examples for javax.script.Compilable#compile()

The following examples show how to use javax.script.Compilable#compile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 6 votes vote down vote up
@Test
public void test_bsh_script_engine_compile_return_this() throws Throwable {
    class CompiledMethod {
        Object bshThis;
        Method invokeMethod;
        CompiledMethod() throws Throwable {
            Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
            assertNotNull( engine );
            CompiledScript script = engine.compile("square(x) { return x*x; } return this;");
            bshThis = script.eval();
            invokeMethod = bshThis.getClass().getMethod("invokeMethod", new Class[] {String.class, Object[].class});
        }
        int square(int x) throws Throwable {
            return (int) invokeMethod.invoke(bshThis, new Object[] {"square", new Object[] {x}});
        }
    }
    CompiledMethod cm = new CompiledMethod();
    assertEquals(16, cm.square(4));
    assertEquals(25, cm.square(5));
}
 
Example 2
Source File: JavaScriptParser.java    From AutoLoadCache with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
                        Class<T> valueType) throws Exception {
    Bindings bindings = new SimpleBindings();
    bindings.put(TARGET, target);
    bindings.put(ARGS, arguments);
    if (hasRetVal) {
        bindings.put(RET_VAL, retVal);
    }
    CompiledScript script = expCache.get(exp);
    if (null != script) {
        return (T) script.eval(bindings);
    }
    if (engine instanceof Compilable) {
        Compilable compEngine = (Compilable) engine;
        script = compEngine.compile(funcs + exp);
        expCache.put(exp, script);
        return (T) script.eval(bindings);
    } else {
        return (T) engine.eval(funcs + exp, bindings);
    }
}
 
Example 3
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 5 votes vote down vote up
@Test
public void test_bsh_script_engine_compile() throws Throwable {
    Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
    assertNotNull( engine );
    CompiledScript script = engine.compile(new StringReader("return 42;"));
    assertEquals(42, script.eval());
}
 
Example 4
Source File: NashornJsEvaluator.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private static CompiledScript compileScript(String script) {
  ScriptEngine engine = factory.getScriptEngine(new String[] { "--no-java" });
  Compilable compEngine = (Compilable) engine;
  try {
    return compEngine.compile(script);
  } catch (ScriptException e) {
    log.warn("Failed to compile filter script: {}", e.getMessage(), e);
    throw new IllegalArgumentException("Can't compile script: " + e.getMessage());
  }
}
 
Example 5
Source File: ScriptEngineTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 6
Source File: ScriptEngineTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 7
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 8
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 9
Source File: L2ScriptEngineManager.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
{
	if (engine instanceof Compilable && ATTEMPT_COMPILATION)
	{
		Compilable eng = (Compilable) engine;
		CompiledScript cs = eng.compile(script);
		return context != null ? cs.eval(context) : cs.eval();
	} else
		return context != null ? engine.eval(script, context) : engine.eval(script);
}
 
Example 10
Source File: ScriptEngineTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 11
Source File: LuaExpression.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private LuaHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 12
Source File: PythonExpression.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private PythonHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 13
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 5 votes vote down vote up
@Test
public void test_bsh_script_engine_compile_no_line_terminator() throws Throwable {
    Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
    assertNotNull( engine );
    CompiledScript script = engine.compile("37+5");
    assertEquals(42, script.eval());
}
 
Example 14
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a compiled script.
 *
 * @param language
 * @param script
 * @return The compiled script, or <code>null</code> if the script engine does not support compilation.
 * @throws IllegalArgumentException
 * @throws ScriptException
 */
public static CompiledScript compileScriptString(String language, String script) throws ScriptException {
    if ("bsh".equals(language)) { // SCIPIO: 2018-09-19: Beanshell backward-compatibility mode
        // FIXME?: currently unable to use a custom GroovyClassLoader in configureScriptEngineForInvoke so
        // we cannot fully honor GroovyLangVariant(.BSH) config yet; thankfully right now it only needs a custom Binding...
        language = "groovy";
    }
    Assert.notNull("language", language, "script", script);
    String cacheKey = language.concat("://").concat(script);
    CompiledScript compiledScript = parsedScripts.get(cacheKey);
    if (compiledScript == null) {
        ScriptEngineManager manager = getScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(language);
        if (engine == null) {
            throw new IllegalArgumentException("The script type is not supported for language: " + language);
        }
        engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
        try {
            Compilable compilableEngine = (Compilable) engine;
            compiledScript = compilableEngine.compile(script);
            if (Debug.verboseOn()) {
                Debug.logVerbose("Compiled script [" + script + "] using engine " + engine.getClass().getName(), module);
            }
        } catch (ClassCastException e) {
            if (Debug.verboseOn()) {
                Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
            }
        }
        if (compiledScript != null) {
            parsedScripts.putIfAbsent(cacheKey, compiledScript);
        }
    }
    return compiledScript;
}
 
Example 15
Source File: Test2.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByName("JavaScript");
	try {
		String script = "function getUrl(){var url='adsf';return url;} getUrl()";
		Compilable compilable = (Compilable) engine;
		CompiledScript JSFunction = compilable.compile(script);
		Object result = JSFunction.eval();
		System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: ScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 17
Source File: JavascriptRequestResponseFilter.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
public void setResponseFilterScript(String script) {
    Compilable compilable = (Compilable) JAVASCRIPT_ENGINE;
    try {
        compiledResponseFilterScript = compilable.compile(script);
    } catch (ScriptException e) {
        throw new JavascriptCompilationException("Unable to compile javascript. Script in error:\n" + script, e);
    }
}
 
Example 18
Source File: JavascriptRequestResponseFilter.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
public void setRequestFilterScript(String script) {
    Compilable compilable = (Compilable) JAVASCRIPT_ENGINE;
    try {
        compiledRequestFilterScript = compilable.compile(script);
    } catch (ScriptException e) {
        throw new JavascriptCompilationException("Unable to compile javascript. Script in error:\n" + script, e);
    }
}
 
Example 19
Source File: ExeJsUtil.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 执行js并返回结果
 * @param jsStr
 * @return
 */
public static String getJsVal(String jsStr) {
	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByName("JavaScript");
	try {
		Compilable compilable = (Compilable) engine;
		CompiledScript JSFunction = compilable.compile(jsStr);
		Object result = JSFunction.eval();
		return result != null ? result.toString() : null;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 20
Source File: EJSParser.java    From jeddict with Apache License 2.0 4 votes vote down vote up
private ScriptEngine createEngine() {
        // Hack until NETBEANS-2705 fixed
        System.getProperties().setProperty("polyglot.js.nashorn-compat", "true");
        System.getProperties().setProperty("js.global-arguments", "true");
        CompiledScript compiledScript;
        Bindings bindings;
        GraalJSEngineFactory graalJSEngineFactory = new GraalJSEngineFactory();
        ScriptEngine scriptEngine = graalJSEngineFactory.getScriptEngine();
//      org.netbeans.api.scripting.Scripting.createManager().getEngineByName("Graal.js");

        try {
            if (base == null) {
                base = readString(loadResource(TEMPLATES + "base.js"));
            }
            if (ejs == null) {
                ejs = readString(loadResource(TEMPLATES + "ejs.js"));
            }

            scriptEngine.eval(base);
            Compilable compilingEngine = (Compilable) scriptEngine;
            compiledScript = compilingEngine.compile(ejs);
            bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            compiledScript.eval(bindings);
            scriptEngine.eval(scripts.toString());

            for (Map<String, Object> context : contexts) {
                context.entrySet()
                        .forEach(entry -> {
                                Object value = entry.getValue();
                                if (value instanceof Collection || value instanceof Map) {
                                        value = toJson(scriptEngine, value);
                                }
                                bindings.put(entry.getKey(), value);
                        });
            }
        } catch (ScriptException ex) {
            Exceptions.printStackTrace(ex);
        }
        // Hack until NETBEANS-2705 fixed
        System.getProperties().remove("polyglot.js.nashorn-compat");
        return scriptEngine;
    }