下面列出了javax.script.ScriptEngineManager#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testScopes() throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
Assert.assertNotNull("Manager should not be null", manager);
ScriptEngine engine = manager.getEngineByName("JEXL");
Assert.assertNotNull("Engine should not be null (JEXL)", engine);
manager.put("global", 1);
engine.put("local", 10);
manager.put("both", 7);
engine.put("both", 7);
engine.eval("local=local+1");
engine.eval("global=global+1");
engine.eval("both=both+1"); // should update engine value only
engine.eval("newvar=42;");
Assert.assertEquals(2,manager.get("global"));
Assert.assertEquals(11,engine.get("local"));
Assert.assertEquals(7,manager.get("both"));
Assert.assertEquals(8,engine.get("both"));
Assert.assertEquals(42,engine.get("newvar"));
Assert.assertNull(manager.get("newvar"));
}
public static Object executeScript(String resourcePath, Map<String, Object> params,
List<String> attributesToRemove) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("ruby");
InputStream resource = GrokIngestMapper.class.getClassLoader().getResourceAsStream(resourcePath);
for (String toRemove : attributesToRemove) {
engine.getContext().setAttribute(toRemove, params.get(toRemove),
ScriptContext.ENGINE_SCOPE);// necessary limit the scope to just engine
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
manager.put(entry.getKey(), entry.getValue());
}
if (resource == null) {
throw new RuntimeException("Resource not found " + resourcePath);
}
if (engine == null) {
throw new RuntimeException("Script engine can not be created");
}
InputStreamReader is = new InputStreamReader(resource);
try {
Object response = engine.eval(is);
return response;
} catch (Exception e) {
log.error("Error executing script: " + e.getMessage(), e);
throw new RuntimeException("Error executing ruby script", e);
}
}