View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2015 Sebastian
3    * Thomschke.
4    *
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    *
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.expression;
14  
15  import java.util.Map;
16  import java.util.Map.Entry;
17  
18  import net.sf.oval.exception.ExpressionEvaluationException;
19  import net.sf.oval.internal.Log;
20  import net.sf.oval.internal.util.ObjectCache;
21  import ognl.Ognl;
22  import ognl.OgnlContext;
23  import ognl.OgnlException;
24  
25  /**
26   * @author Sebastian Thomschke
27   *
28   */
29  public class ExpressionLanguageOGNLImpl extends AbstractExpressionLanguage
30  {
31  	private static final Log LOG = Log.getLog(ExpressionLanguageOGNLImpl.class);
32  
33  	private final ObjectCache<String, Object> expressionCache = new ObjectCache<String, Object>();
34  
35  	public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
36  	{
37  		LOG.debug("Evaluating OGNL expression: {1}", expression);
38  		try
39  		{
40  			final OgnlContext ctx = (OgnlContext) Ognl.createDefaultContext(null);
41  
42  			for (final Entry<String, ? > entry : values.entrySet())
43  			{
44  				ctx.put(entry.getKey(), entry.getValue());
45  			}
46  
47  			Object expr = expressionCache.get(expression);
48  			if (expr == null)
49  			{
50  				expr = Ognl.parseExpression(expression);
51  				expressionCache.put(expression, expr);
52  			}
53  			return Ognl.getValue(expr, ctx);
54  		}
55  		catch (final OgnlException ex)
56  		{
57  			throw new ExpressionEvaluationException("Evaluating MVEL expression failed: " + expression, ex);
58  		}
59  	}
60  }