wrp.jdk.nashorn.api.scripting.NashornScriptEngineUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of doip-audit-tool Show documentation
Show all versions of doip-audit-tool Show documentation
doip audit tool developed by bdware
package wrp.jdk.nashorn.api.scripting;
import com.google.gson.JsonElement;
import org.bdware.doip.cluster.util.DOAClientUtil;
import org.bdware.doip.cluster.util.DoipClusterUtil;
import org.bdware.doip.cluster.util.JSONTool;
import org.bdware.sc.util.JsonUtil;
import wrp.jdk.nashorn.internal.runtime.Context;
import javax.script.Bindings;
import javax.script.ScriptException;
import java.net.URL;
import java.net.URLClassLoader;
public class NashornScriptEngineUtil {
public NashornScriptEngine engine;
public Bindings functionBindings;
public DoipClusterUtil doipClusterUtil;
public NashornScriptEngineUtil() {
String[] args = new String[]{"--loader-per-compile=false", "-strict=false"};
ClassLoader cl = new URLClassLoader(new URL[]{}, NashornScriptEngineFactory.class.getClassLoader());
engine = (NashornScriptEngine)
new NashornScriptEngineFactory()
.getScriptEngine(
args, // "--print-ast",
// "true",
// "-d=/Users/huaqiancai/Downloads/dumpedClz",
// "--trace-callsites=enterexit"
// "--log=methodhandles:all",
// fields:all,
// "--print-parse", "true" "--print-code",
// fields:finest
cl);
functionBindings = engine.createBindings();
doipClusterUtil = new DoipClusterUtil();
functionBindings.put("ClusterUtil", doipClusterUtil);
// functionBindings.put("DOAClient", DOAClientUtil.getInstance());
// engine.eval("function autoWrap(functionName,funcArgs){\n" +
// " var convertedArg = xx.xxx.xxJSONTool.convertJsonToMirror(funcArgs);\n" +
// " var result = functionName(convertedArg);\n" +
// " return XX.xx.JSONTool.convertMirrorToJson(result);\n" +
// " }", functionBindings);
}
public void evalFunction(String funcScript) throws ScriptException {
engine.eval(funcScript, functionBindings);
}
public T invokeFunction(String funcName, Class t, JsonElement... args) throws ScriptException, NoSuchMethodException {
;
assert args != null;
int length = args.length;
Object[] funcArgs = new Object[length];
Object scriptRes = null;
// synchronize(全局只有一个线程能走完54~60) -> 两个线程同时执行到Global的时候,前一个会被后面的替换掉,导致出现问题
synchronized (NashornScriptEngineUtil.class) {
Context.setGlobal(((ScriptObjectMirror) functionBindings).getHomeGlobal());
for (int i = 0; i < length; i++) {
funcArgs[i] = JSONTool.convertJsonElementToMirror(args[i]);
}
scriptRes = engine.invokeMethod(functionBindings, funcName, funcArgs);
scriptRes = JSONTool.convertMirrorToJson(scriptRes);
}
String engineRes = JsonUtil.toJson(scriptRes);
return JsonUtil.fromJson(engineRes, t);
}
}