1 17 package org.apache.geronimo.system.configuration.condition; 18 19 import org.apache.commons.logging.Log; 20 import org.apache.commons.logging.LogFactory; 21 import org.apache.commons.jexl.Expression; 22 import org.apache.commons.jexl.ExpressionFactory; 23 import org.apache.commons.jexl.JexlContext; 24 import org.apache.commons.jexl.JexlHelper; 25 26 import java.util.Map ; 27 import java.util.HashMap ; 28 import java.util.Collections ; 29 30 40 public class JexlConditionParser 41 implements ConditionParser 42 { 43 private static final Log log = LogFactory.getLog(JexlConditionParser.class); 44 45 private final Map vars; 46 47 public JexlConditionParser() { 48 vars = new HashMap (); 50 51 vars.put("props", Collections.unmodifiableMap(System.getProperties())); 52 vars.put("java", new JavaVariable()); 53 vars.put("os", new OsVariable()); 54 } 55 56 64 public boolean evaluate(final String expression) throws ConditionParserException { 65 if (expression == null) { 66 throw new IllegalArgumentException ("Expression must not be null"); 67 } 68 69 if (expression.trim().length() == 0) { 71 log.debug("Expression is empty; skipping evaluation"); 72 73 return true; 74 } 75 76 Object result; 77 try { 78 result = doEvaluate(expression); 79 } 80 catch (Exception e) { 81 throw new ConditionParserException("Failed to evaluate expression: " + expression, e); 82 } 83 84 if (result instanceof Boolean ) { 85 return ((Boolean )result).booleanValue(); 86 } 87 else { 88 throw new ConditionParserException("Expression '" + expression + "' did not evaluate to a boolean value; found: " + result); 89 } 90 } 91 92 private Object doEvaluate(final String expression) throws Exception { 93 assert expression != null; 94 95 boolean debug = log.isDebugEnabled(); 96 97 if (debug) { 98 log.debug("Evaluating expression: " + expression); 99 } 100 101 Expression expr = ExpressionFactory.createExpression(expression); 102 103 JexlContext ctx = JexlHelper.createContext(); 104 ctx.setVars(vars); 105 106 Object result = expr.evaluate(ctx); 107 if (debug) { 108 log.debug("Result: " + result); 109 } 110 111 return result; 112 } 113 } 114 | Popular Tags |