001    /*******************************************************************************
002     * Portions created by Sebastian Thomschke are copyright (c) 2005-2012 Sebastian
003     * Thomschke.
004     * 
005     * All Rights Reserved. This program and the accompanying materials
006     * are made available under the terms of the Eclipse Public License v1.0
007     * which accompanies this distribution, and is available at
008     * http://www.eclipse.org/legal/epl-v10.html
009     * 
010     * Contributors:
011     *     Sebastian Thomschke - initial implementation.
012     *******************************************************************************/
013    package net.sf.oval.expression;
014    
015    import java.util.Map;
016    import java.util.Map.Entry;
017    
018    import net.sf.oval.exception.ExpressionEvaluationException;
019    import net.sf.oval.internal.Log;
020    import bsh.EvalError;
021    import bsh.Interpreter;
022    
023    /**
024     * @author Sebastian Thomschke
025     */
026    public class ExpressionLanguageBeanShellImpl implements ExpressionLanguage
027    {
028            private static final Log LOG = Log.getLog(ExpressionLanguageBeanShellImpl.class);
029    
030            /**
031             * {@inheritDoc}
032             */
033            public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
034            {
035                    LOG.debug("Evaluating BeanShell expression: {1}", expression);
036                    try
037                    {
038                            final Interpreter interpreter = new Interpreter();
039                            interpreter.eval("setAccessibility(true)"); // turn off access restrictions
040                            for (final Entry<String, ? > entry : values.entrySet())
041                                    interpreter.set(entry.getKey(), entry.getValue());
042                            return interpreter.eval(expression);
043                    }
044                    catch (final EvalError ex)
045                    {
046                            throw new ExpressionEvaluationException("Evaluating BeanShell expression failed: " + expression, ex);
047                    }
048            }
049    
050            /**
051             * {@inheritDoc}
052             */
053            public boolean evaluateAsBoolean(final String expression, final Map<String, ? > values)
054                            throws ExpressionEvaluationException
055            {
056                    final Object result = evaluate(expression, values);
057                    if (!(result instanceof Boolean))
058                            throw new ExpressionEvaluationException("The script must return a boolean value.");
059                    return (Boolean) result;
060            }
061    }