Wednesday, September 07, 2011

Evaluating Javascript expressions in Java

As the java virtual machine comes up with Javascript runtime, we can directly evaluate JavaScript expressions in our Java Class. The approach could be helpful in conditions when we want certain kind of Javascript expressions to be evaluated in our Java class in server rather than the client side. JVM has the in built Script Engine called Mozilla Rhino. Rhino is an open-source implementation of JavaScript written in Java, which is used to run expressions given in Javascript from JVM.


Given is the ScriptingEngine info for Java virtual machine. This information can be obtained by running below method.

ScriptEngineManager mgr = new ScriptEngineManager();
List facts =
mgr.getEngineFactories();

System.out.println("engName :" + facts.getEngineName()
+ ":engVersion:" + facts.getEngineVersion()
+ ":langName :" + facts.getLanguageName()
+ ":langVersion :"+ factory.getLanguageVersion());


when the Engine Names is printed we can see the following results.

Script Engine: Mozilla Rhino (1.6 release 2)
Engine Alias: js
Engine Alias: rhino
Engine Alias: JavaScript
Engine Alias: javascript
Engine Alias: ECMAScript
Engine Alias: ecmascript
Language: ECMAScript (1.6)


Given below is the class which evaluates the JavaScript expression given to it. The evaluate method has to be given the expression to be evaluated, the setters names and the setterValueMap which contains the key,value pair of setterField and its corresponding value.

/**
*@author Bishal Acharya
*
*/
public class JavascriptEvaluator {
/**
*
* @param expression
* the expression to evaluate
* @param setters
* list of setters for the expression
* @param setterValueMap
* Map having setterKey and its value
* @return Object the evaluated expression
*/
public static Object evaluate(String expression, String setters,
Map<String, String> setterValueMap) {
String[] setterArray = setters.split(",");
List<String> setterList = new ArrayList<String>();

for (String val : setterArray) {
setterList.add(val.trim());
}

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
Object obj = null;
for (int i = 0; i < setterList.size(); i++) {
jsEngine.put(setterList.get(i),
setterValueMap.get(setterList.get(i)));
}
try {
obj = jsEngine
.eval("func1(); function func1(){" + expression + "}");
} catch (ScriptException e) {
e.printStackTrace();
}
return obj;
}

public static void main(String args[]) {
String expr = "return GROUP_NAME.substr(0,5).concat(' How are You');";
String setters = "GROUP_NAME";
Map<String, String> setterValueMap = new HashMap<String, String>();
setterValueMap.put("GROUP_NAME", "Hello World");
System.out.println(JavascriptEvaluator.evaluate(expr, setters,
setterValueMap));
}
}



Output of Running above class :

Hello How are You

No comments: