Given is the ScriptingEngine info for Java virtual machine. This information can be obtained by running below method.
ScriptEngineManager mgr = new ScriptEngineManager();
List
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:
Post a Comment