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  
17  import net.sf.oval.exception.ExpressionEvaluationException;
18  import net.sf.oval.internal.Log;
19  import net.sf.oval.internal.util.ObjectCache;
20  
21  import org.apache.commons.jexl2.Expression;
22  import org.apache.commons.jexl2.JexlEngine;
23  import org.apache.commons.jexl2.MapContext;
24  
25  /**
26   * @author Sebastian Thomschke
27   */
28  public class ExpressionLanguageJEXLImpl extends AbstractExpressionLanguage
29  {
30  	private static final Log LOG = Log.getLog(ExpressionLanguageJEXLImpl.class);
31  
32  	private static final JexlEngine jexl = new JexlEngine();
33  
34  	private final ObjectCache<String, Expression> expressionCache = new ObjectCache<String, Expression>();
35  
36  	@SuppressWarnings("unchecked")
37  	public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
38  	{
39  		LOG.debug("Evaluating JEXL expression: {1}", expression);
40  		try
41  		{
42  			Expression expr = expressionCache.get(expression);
43  			if (expr == null)
44  			{
45  				expr = jexl.createExpression(expression);
46  				expressionCache.put(expression, expr);
47  			}
48  			return expr.evaluate(new MapContext((Map<String, Object>) values));
49  		}
50  		catch (final Exception ex)
51  		{
52  			throw new ExpressionEvaluationException("Evaluating JEXL expression failed: " + expression, ex);
53  		}
54  	}
55  }