1 16 package org.apache.commons.jexl; 17 18 import java.io.StringReader ; 19 20 import org.apache.commons.jexl.parser.ASTExpressionExpression; 21 import org.apache.commons.jexl.parser.ASTForeachStatement; 22 import org.apache.commons.jexl.parser.ASTIfStatement; 23 import org.apache.commons.jexl.parser.ASTReferenceExpression; 24 import org.apache.commons.jexl.parser.ASTStatementExpression; 25 import org.apache.commons.jexl.parser.ASTWhileStatement; 26 import org.apache.commons.jexl.parser.Parser; 27 import org.apache.commons.jexl.parser.SimpleNode; 28 import org.apache.commons.jexl.parser.TokenMgrError; 29 import org.apache.commons.logging.Log; 30 import org.apache.commons.logging.LogFactory; 31 32 52 public class ExpressionFactory { 53 56 protected static Log log = 57 LogFactory.getLog("org.apache.commons.jexl.ExpressionFactory"); 58 59 64 protected static Parser parser = 65 new Parser(new StringReader (";")); 67 71 protected static ExpressionFactory ef = new ExpressionFactory(); 72 73 77 private ExpressionFactory() { 78 } 79 80 84 protected static ExpressionFactory getInstance() { 85 return ef; 86 } 87 88 98 public static Expression createExpression(String expression) 99 throws Exception { 100 return getInstance().createNewExpression(expression); 101 } 102 103 104 112 protected Expression createNewExpression(final String expression) 113 throws Exception { 114 115 String expr = cleanExpression(expression); 116 117 SimpleNode tree; 119 synchronized (parser) { 120 log.debug("Parsing expression: " + expr); 121 try { 122 tree = parser.parse(new StringReader (expr)); 123 } catch (TokenMgrError e) { 124 throw new JexlException("Failed to parse "+expr,e); 128 } 129 } 130 131 if (tree.jjtGetNumChildren() > 1 && log.isWarnEnabled()) { 132 log.warn("The JEXL Expression created will be a reference" 133 + " to the first expression from the supplied script: \"" 134 + expression + "\" "); 135 } 136 137 SimpleNode node = (SimpleNode) tree.jjtGetChild(0); 140 141 if (node instanceof ASTReferenceExpression 143 || node instanceof ASTExpressionExpression 144 || node instanceof ASTStatementExpression 145 || node instanceof ASTIfStatement 146 || node instanceof ASTWhileStatement 147 || node instanceof ASTForeachStatement 148 ) { 149 return new ExpressionImpl(expression, node); 150 } 151 log.error("Invalid Expression, node of type: " 152 + node.getClass().getName()); 153 throw new Exception ("Invalid Expression: not a Reference, Expression, " 154 + "Statement or If"); 155 } 156 157 162 private String cleanExpression(String expression) { 163 String expr = expression.trim(); 164 if (!expr.endsWith(";")) { 165 expr += ";"; 166 } 167 return expr; 168 } 169 } 170 | Popular Tags |