I'm trying to run the JS function in Java code and the JS function is not executing since it had some third party library that needs to be load.
JsFunction.js
load('crypto-js-3.1.9/crypto-js.js');
var encrypterId = function(name) {
var context_data = {"referralId": name};
var secret = CryptoJS.enc.Utf8.parse(JSON.stringify(context_data))
var encoded_referral_id = CryptoJS.enc.Base64.stringify(secret);
return encoded_referral_id;
}
JavaCode:
public static void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("./resources/JsFunction.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("encrypterId", "827AE1001sdsj213jasu721kkao@1sa");
System.out.println(result);
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
Exception:
javax.script.ScriptException: TypeError: Cannot load script from crypto-js-3.1.9/crypto-js.js in <eval> at line number 1
at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:469)
at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:453)
at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:405)
at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:401)
at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:149)
Can someone help me to run this JS and return the value ? else is it possible to write the equivalent code in Java?
I think you can do it this way:
Remove the 'load' line from JsFunction.js
In your JavaCode, in the line immediately before engine.eval(new FileReader("./resources/JsFunction.js"));
just insert a line engine.eval(new FileReader("./resources/crypto-js-3.1.9/crypto-js.js"));
I believe that puts the contents of the crypto-js.js file into scope in the ScriptEngine, and the subsequent JsFunction.js call should work.
I did something similar with much simpler JS files as a test case.