View Javadoc

1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2013 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 implements ExpressionLanguage
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  	/**
37  	 * {@inheritDoc}
38  	 */
39  	@SuppressWarnings("unchecked")
40  	public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
41  	{
42  		LOG.debug("Evaluating JEXL expression: {1}", expression);
43  		try
44  		{
45  			Expression expr = expressionCache.get(expression);
46  			if (expr == null)
47  			{
48  				expr = jexl.createExpression(expression);
49  				expressionCache.put(expression, expr);
50  			}
51  			return expr.evaluate(new MapContext((Map<String, Object>) values));
52  		}
53  		catch (final Exception ex)
54  		{
55  			throw new ExpressionEvaluationException("Evaluating JEXL expression failed: " + expression, ex);
56  		}
57  	}
58  
59  	/**
60  	 * {@inheritDoc}
61  	 */
62  	public boolean evaluateAsBoolean(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
63  	{
64  		final Object result = evaluate(expression, values);
65  		if (!(result instanceof Boolean)) throw new ExpressionEvaluationException("The script must return a boolean value.");
66  		return (Boolean) result;
67  	}
68  }