Invoking a JS method using Rhino Script Engine
Hi All
We are trying to execute handlebar templates via a Script Engine Inside AEM. This Handlebar Execution needs to done using the Rhino Script Engine as we don't want to go to with Java based execution in order to be flexible in future to replace handlebars with any other client side templating language. I am able to load the Rhino script Engine successfully and also able to evaluate the handlebar.js file using the engine. However when I am trying to obtain a"javax.script.Invocable" object from "org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine" to call a JS method, I am getting below error.
Caused by: org.apache.sling.api.SlingException: Cannot get DefaultSlingScript: org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine cannot be cast to javax.script.Invocable
at org.apache.sling.scripting.core.impl.DefaultSlingScript.service(DefaultSlingScript.java:481)
at com.day.cq.wcm.tags.IncludeTag.includeScript(IncludeTag.java:167)
at com.day.cq.wcm.tags.IncludeTag.doEndTag(IncludeTag.java:87)
at org.apache.jsp.apps.saks.components.testing.testing_jsp._jspx_meth_cq_005finclude_005f0(testing_jsp.java:178)
at org.apache.jsp.apps.saks.components.testing.testing_jsp._jspService(testing_jsp.java:152)
at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:502)
It seems AEM has done the implementation of Rhino Engine in a different way as JDK because the same code runs fine as a Stand alone Java Program. Below is the code snippet being used to execute the handlebars as suggested on Java Scripting Programmer's Guide.
ScriptEngine engine = scriptEngineManager.getEngineByName("javascript");
URL fileURL = FrameworkUtil.getBundle(getClass()).getEntry("META-INF/js/handlebars.js");
try {
String jsSource = IOUtils.toString(fileURL.openStream());
engine.eval(jsSource);
} catch (IOException e) {
e.printStackTrace();
}
Object mustache = engine.eval("Handlebars");
Invocable invocable = (Invocable) engine;
String template = "Email addresses of {{contact.name}}:\n"
+ "{{#contact.emails}}\n" + "- {{.}}\n" + "{{/contact.emails}}";
Object compiledTemplate = invocable.invokeMethod(handlebar, "compile",template);
If anyone has done a similar thing using Rhino or any other JS Engine inside AEM, please help me identify the cause & solution to above problem.
Thanks
Nitin
