1 package org.testng.internal; 2 3 import bsh.EvalError; 4 import bsh.Interpreter; 5 6 import org.testng.ITestNGMethod; 7 import org.testng.TestNGException; 8 import org.testng.collections.Maps; 9 10 import java.lang.reflect.Method; 11 import java.util.Map; 12 13 public class Bsh implements IBsh { 14 private static Interpreter s_interpreter; 15 16 @Override includeMethodFromExpression(String expression, ITestNGMethod tm)17 public boolean includeMethodFromExpression(String expression, ITestNGMethod tm) { 18 boolean result = false; 19 20 Interpreter interpreter = getInterpreter(); 21 try { 22 Map<String, String> groups = Maps.newHashMap(); 23 for (String group : tm.getGroups()) { 24 groups.put(group, group); 25 } 26 setContext(interpreter, tm.getMethod(), groups, tm); 27 Object evalResult = interpreter.eval(expression); 28 result = (Boolean) evalResult; 29 } 30 catch (EvalError evalError) { 31 Utils.log("bsh.Interpreter", 2, "Cannot evaluate expression:" 32 + expression + ":" + evalError.getMessage()); 33 } 34 finally { 35 resetContext(interpreter); 36 } 37 38 return result; 39 40 } 41 getInterpreter()42 private static Interpreter getInterpreter() { 43 if(null == s_interpreter) { 44 s_interpreter= new Interpreter(); 45 } 46 47 return s_interpreter; 48 } 49 setContext(Interpreter interpreter, Method method, Map<String, String> groups, ITestNGMethod tm)50 private void setContext(Interpreter interpreter, Method method, Map<String, String> groups, ITestNGMethod tm) { 51 try { 52 interpreter.set("method", method); 53 interpreter.set("groups", groups); 54 interpreter.set("testngMethod", tm); 55 } 56 catch(EvalError evalError) { 57 throw new TestNGException("Cannot set BSH interpreter", evalError); 58 } 59 } 60 resetContext(Interpreter interpreter)61 private void resetContext(Interpreter interpreter) { 62 try { 63 interpreter.unset("method"); 64 interpreter.unset("groups"); 65 interpreter.unset("testngMethod"); 66 } 67 catch(EvalError evalError) { 68 Utils.log("bsh.Interpreter", 2, "Cannot reset interpreter:" + evalError.getMessage()); 69 } 70 } 71 72 } 73