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    
017    import net.sf.oval.exception.ExpressionEvaluationException;
018    import net.sf.oval.internal.Log;
019    import net.sf.oval.internal.util.ObjectCache;
020    
021    import org.mvel2.MVEL;
022    
023    /**
024     * @author Sebastian Thomschke
025     */
026    public class ExpressionLanguageMVELImpl implements ExpressionLanguage
027    {
028            private static final Log LOG = Log.getLog(ExpressionLanguageMVELImpl.class);
029    
030            private final ObjectCache<String, Object> expressionCache = new ObjectCache<String, Object>();
031    
032            /**
033             * {@inheritDoc}
034             */
035            public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
036            {
037                    LOG.debug("Evaluating MVEL expression: {1}", expression);
038                    try
039                    {
040                            Object expr = expressionCache.get(expression);
041                            if (expr == null)
042                            {
043                                    expr = MVEL.compileExpression(expression);
044                                    expressionCache.put(expression, expr);
045                            }
046                            return MVEL.executeExpression(expr, values);
047                    }
048                    catch (final Exception ex)
049                    {
050                            throw new ExpressionEvaluationException("Evaluating MVEL expression failed: " + expression, ex);
051                    }
052            }
053    
054            /**
055             * {@inheritDoc}
056             */
057            public boolean evaluateAsBoolean(final String expression, final Map<String, ? > values)
058                            throws ExpressionEvaluationException
059            {
060                    final Object result = evaluate(expression, values);
061                    if (!(result instanceof Boolean))
062                            throw new ExpressionEvaluationException("The script must return a boolean value.");
063                    return (Boolean) result;
064            }
065    }