View Javadoc

1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2012 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 bsh.EvalError;
21  import bsh.Interpreter;
22  
23  /**
24   * @author Sebastian Thomschke
25   */
26  public class ExpressionLanguageBeanShellImpl implements ExpressionLanguage
27  {
28  	private static final Log LOG = Log.getLog(ExpressionLanguageBeanShellImpl.class);
29  
30  	/**
31  	 * {@inheritDoc}
32  	 */
33  	public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
34  	{
35  		LOG.debug("Evaluating BeanShell expression: {1}", expression);
36  		try
37  		{
38  			final Interpreter interpreter = new Interpreter();
39  			interpreter.eval("setAccessibility(true)"); // turn off access restrictions
40  			for (final Entry<String, ? > entry : values.entrySet())
41  				interpreter.set(entry.getKey(), entry.getValue());
42  			return interpreter.eval(expression);
43  		}
44  		catch (final EvalError ex)
45  		{
46  			throw new ExpressionEvaluationException("Evaluating BeanShell expression failed: " + expression, ex);
47  		}
48  	}
49  
50  	/**
51  	 * {@inheritDoc}
52  	 */
53  	public boolean evaluateAsBoolean(final String expression, final Map<String, ? > values)
54  			throws ExpressionEvaluationException
55  	{
56  		final Object result = evaluate(expression, values);
57  		if (!(result instanceof Boolean))
58  			throw new ExpressionEvaluationException("The script must return a boolean value.");
59  		return (Boolean) result;
60  	}
61  }