下面列出了怎么用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);
}
@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);
}
@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);
}
@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());
}
}
@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());
}
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);
}
}
/**
* 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;
}
} );
}
}
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;
}
} );
}
}
@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);
}
@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);
}
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);
}
}
@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);
}
@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));
}
@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);
}
}
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;
}
}
/**
* 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;
}
}
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();
}
}
/**
* 执行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);
}
}
@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;
}
@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");
}
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();
}
}
/**
* 执行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 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;
}
}
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);
}
}
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);
}
}
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);
}
}
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);
}
}