script工具类 @author SeanDragon
| 18 | * @author SeanDragon |
| 19 | */ |
| 20 | public final class ToolScript { |
| 21 | |
| 22 | private ToolScript() { |
| 23 | throw new UnsupportedOperationException("我是工具类,别初始化我。。。"); |
| 24 | } |
| 25 | |
| 26 | |
| 27 | private static final Logger log = LoggerFactory.getLogger(ToolScript.class); |
| 28 | |
| 29 | /** |
| 30 | * 渲染模板 |
| 31 | * |
| 32 | * @param templateContent |
| 33 | * @param paramMap |
| 34 | * |
| 35 | * @return |
| 36 | */ |
| 37 | public static String render(String templateContent, Map<String, Object> paramMap) throws ScriptException { |
| 38 | ScriptEngineManager manager = new ScriptEngineManager(); |
| 39 | // 建立javascript脚本引擎 |
| 40 | ScriptEngine engine = manager.getEngineByName("javascript"); |
| 41 | // 将变量和变量值传给javascript脚本 |
| 42 | for (String key : paramMap.keySet()) { |
| 43 | engine.put(key, paramMap.get(key)); |
| 44 | } |
| 45 | |
| 46 | // 开始执行脚本 |
| 47 | engine.eval(templateContent); |
| 48 | |
| 49 | // 编译执行,执行单个函数 |
| 50 | // if (engine instanceof Compilable){ |
| 51 | // Compilable compEngine = (Compilable)engine; |
| 52 | // compEngine.compile(templateContent); |
| 53 | // } |
| 54 | |
| 55 | // 执行多个函数 |
| 56 | // if (engine instanceof Invocable){ |
| 57 | // engine.eval(templateContent); |
| 58 | // Invocable invokeEngine = (Invocable)engine; |
| 59 | // Object o = invokeEngine.invokeFunction("funcName", "funcParam1", "funcParam2"); |
| 60 | // } |
| 61 | |
| 62 | // 异步调用 |
| 63 | // Invocable invokeEngine = (Invocable)engine; |
| 64 | // Runnable runner = invokeEngine.getInterface(Runnable.class); |
| 65 | // Thread t = new Thread(runner); |
| 66 | // t.start(); |
| 67 | // t.join(); |
| 68 | |
| 69 | // } catch (NoSuchMethodException e) { |
| 70 | // log.error("执行脚本异常"); |
| 71 | // } |
| 72 | |
| 73 | // 取js变量值 |
| 74 | return (String) engine.get("output"); |
| 75 | } |
| 76 | |
| 77 | /** |
nothing calls this directly
no outgoing calls
no test coverage detected