类javax.script.Compilable源码实例Demo

下面列出了怎么用javax.script.Compilable的API类实例代码及写法,或者点击链接到github查看源代码。

@Before
public void setup() {
  ScriptEngineManager scriptEngineManager = spy(new ScriptEngineManager());
  when(scriptEngineManager.getEngineByName(anyString())).then(new Answer<ScriptEngine>() {
    public ScriptEngine answer(InvocationOnMock invocation) throws Throwable {
      scriptEngineSpy = spy((ScriptEngine) invocation.callRealMethod());
      compilableSpy = (Compilable) scriptEngineSpy;
      return scriptEngineSpy;
    }
  });

  DefaultDmnEngineConfiguration configuration = new DefaultDmnEngineConfiguration();

  configuration.setScriptEngineResolver(new DefaultScriptEngineResolver(scriptEngineManager));
  configuration.init();


  elProviderSpy = spy(configuration.getElProvider());
  configuration.setElProvider(elProviderSpy);

  expressionEvaluationHandler = new ExpressionEvaluationHandler(configuration);
}
 
源代码2 项目: TencentKona-8   文件: 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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
源代码3 项目: openjdk-jdk8u   文件: 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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
源代码4 项目: tinkerpop   文件: ScriptRecordReader.java
@Override
public void initialize(final InputSplit genericSplit, final TaskAttemptContext context) throws IOException {
    this.lineRecordReader.initialize(genericSplit, context);
    final Configuration configuration = context.getConfiguration();
    if (configuration.get(Constants.GREMLIN_HADOOP_GRAPH_FILTER, null) != null)
        this.graphFilter = VertexProgramHelper.deserialize(ConfUtil.makeApacheConfiguration(configuration), Constants.GREMLIN_HADOOP_GRAPH_FILTER);
    this.engine = manager.getEngineByName(configuration.get(SCRIPT_ENGINE, "gremlin-groovy"));
    final FileSystem fs = FileSystem.get(configuration);
    try (final InputStream stream = fs.open(new Path(configuration.get(SCRIPT_FILE)));
         final InputStreamReader reader = new InputStreamReader(stream)) {
        final String parse = String.join("\n", IOUtils.toString(reader), READ_CALL);
        script = ((Compilable) engine).compile(parse);
    } catch (ScriptException e) {
        throw new IOException(e.getMessage());
    }
}
 
源代码5 项目: dynkt   文件: KotlinScriptEngineTest.java
@Test
public void testCompileFromFile2() throws FileNotFoundException, ScriptException {
	InputStreamReader code = getStream("nameread.kt");
	CompiledScript result = ((Compilable) engine).compile(code);
	assertNotNull(result);
	// First time
	Bindings bnd1 = engine.createBindings();
	StringWriter ret1;
	bnd1.put("out", new PrintWriter(ret1 = new StringWriter()));
	assertNotNull(result.eval(bnd1));
	assertEquals("Provide a name", ret1.toString().trim());
	// Second time
	Bindings bnd2 = engine.createBindings();
	bnd2.put(ScriptEngine.ARGV, new String[] { "Amadeus" });
	StringWriter ret2;
	bnd2.put("out", new PrintWriter(ret2 = new StringWriter()));
	assertNotNull(result.eval(bnd2));
	assertEquals("Hello, Amadeus!", ret2.toString().trim());
}
 
源代码6 项目: netbeans   文件: OQLEngineImpl.java
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = Scripting.newBuilder().allowAllAccess(true).build();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.INFO, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
 
源代码7 项目: neoscada   文件: ScriptExecutor.java
/**
 * Construct a new script executors
 *
 * @param engine
 *            the script engine to use, must not be <code>null</code>
 * @param command
 *            the command to execute, may be <code>null</code>
 * @param classLoader
 *            the class loader to use when executing, may be
 *            <code>null</code>
 * @throws ScriptException
 */
public ScriptExecutor ( final ScriptEngine engine, final String command, final ClassLoader classLoader, final String sourceName ) throws Exception
{
    this.engine = engine;
    this.command = command;
    this.commandUrl = null;
    this.classLoader = classLoader;
    this.sourceName = sourceName;

    if ( command != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
    {
        if ( sourceName != null )
        {
            engine.put ( ScriptEngine.FILENAME, sourceName );
        }

        Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {
            @Override
            public Void call () throws Exception
            {
                ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( command );
                return null;
            }
        } );
    }
}
 
源代码8 项目: neoscada   文件: ScriptExecutor.java
public ScriptExecutor ( final ScriptEngine engine, final URL commandUrl, final ClassLoader classLoader ) throws Exception
{
    this.engine = engine;
    this.command = null;
    this.commandUrl = commandUrl;
    this.classLoader = classLoader;
    this.sourceName = commandUrl.toString ();

    if ( commandUrl != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
    {
        Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {

            @Override
            public Void call () throws Exception
            {
                ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( new InputStreamReader ( commandUrl.openStream () ) );
                return null;
            }
        } );
    }
}
 
源代码9 项目: openjdk-jdk8u-backup   文件: 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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
源代码10 项目: openjdk-jdk9   文件: 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);
}
 
源代码11 项目: visualvm   文件: OQLEngineImpl.java
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.INFO, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
 
源代码12 项目: jdk8u_nashorn   文件: 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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
源代码13 项目: beanshell   文件: TestBshScriptEngine.java
@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));
}
 
源代码14 项目: AutoLoadCache   文件: JavaScriptParser.java
@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);
    }
}
 
源代码15 项目: oval   文件: ExpressionLanguageScriptEngineImpl.java
protected ExpressionLanguageScriptEngineImpl(final ScriptEngine engine) {
   this.engine = engine;
   if (engine instanceof Compilable) {
      compilable = (Compilable) engine;
      compiledCache = new ObjectCache<String, CompiledScript>() {
         @Override
         protected CompiledScript load(final String expression) {
            try {
               return compilable.compile(expression);
            } catch (final ScriptException ex) {
               throw new ExpressionEvaluationException("Parsing " + engine.get(ScriptEngine.NAME) + " expression failed: " + expression, ex);
            }
         }
      };
   } else {
      compilable = null;
      compiledCache = null;
   }
}
 
源代码16 项目: constellation   文件: RowFilter.java
/**
 * The script that this filter implements.
 *
 * @param script the script that will be applied to each row to test if it
 * should be included in the import.
 *
 * @return true if the script was successfully compiled.
 */
public boolean setScript(final String script) {
    try {
        this.script = encodeScript(script);
        compiledScript = ((Compilable) engine).compile(this.script);

        LOGGER.log(Level.INFO, "SCRIPT = {0}", this.script);
        return true;

    } catch (ScriptException ex) {
        this.script = null;
        return false;
    }
}
 
源代码17 项目: SubTitleSearcher   文件: Test2.java
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();
	}
}
 
源代码18 项目: SubTitleSearcher   文件: ExeJsUtil.java
/**
 * 执行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;
}
 
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);
    }
}
 
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);
    }
}
 
源代码21 项目: TencentKona-8   文件: ScriptEngineTest.java
@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");
}
 
@Override
public Object compile(String expression, Map<String, Object> parameters) {
	if (scriptEngine instanceof Compilable) {
		logger.debug("Compiling expression {} with engine {}", expression, scriptEngine);
		try {
			return ((Compilable) scriptEngine).compile(expression);
		} catch (ScriptException e) {
			throw new RuntimeException("Error when compiling script", e);
		}
	}
	logger.debug("Compilation not supported on engine {}", scriptEngine);
	return expression;
}
 
源代码23 项目: jdk8u60   文件: ScriptEngineTest.java
@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");
}
 
源代码24 项目: SubTitleSearcher   文件: Test2.java
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();
	}
}
 
源代码25 项目: SubTitleSearcher   文件: ExeJsUtil.java
/**
 * 执行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;
}
 
源代码26 项目: TabooLib   文件: Scripts.java
public static CompiledScript compile(String script) {
    try {
        return ((Compilable) scriptEngine).compile(script);
    } catch (Exception e) {
        TLogger.getGlobalLogger().info("§4JavaScript §c" + script + "§4 Compile Failed: §c" + e.toString());
        return null;
    }
}
 
源代码27 项目: jstarcraft-core   文件: JsExpression.java
private JsHolder(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);
    }
}
 
源代码28 项目: jstarcraft-core   文件: LuaFunction.java
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);
    }
}
 
源代码29 项目: jstarcraft-core   文件: PythonExpression.java
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);
    }
}
 
源代码30 项目: jstarcraft-core   文件: LuaExpression.java
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);
    }
}