01: /*******************************************************************************
02: * Portions created by Sebastian Thomschke are copyright (c) 2005-2007 Sebastian
03: * Thomschke.
04: *
05: * All Rights Reserved. This program and the accompanying materials
06: * are made available under the terms of the Eclipse Public License v1.0
07: * which accompanies this distribution, and is available at
08: * http://www.eclipse.org/legal/epl-v10.html
09: *
10: * Contributors:
11: * Sebastian Thomschke - initial implementation.
12: *******************************************************************************/package net.sf.oval.expression;
13:
14: import groovy.lang.Binding;
15: import groovy.lang.GroovyRuntimeException;
16: import groovy.lang.GroovyShell;
17:
18: import java.util.Map;
19: import java.util.Map.Entry;
20:
21: import net.sf.oval.exception.ExpressionEvaluationException;
22: import net.sf.oval.internal.Log;
23:
24: /**
25: * @author Sebastian Thomschke
26: *
27: */
28: public class ExpressionLanguageGroovyImpl implements ExpressionLanguage {
29: private final static Log LOG = Log
30: .getLog(ExpressionLanguageGroovyImpl.class);
31:
32: public Object evaluate(final String expression,
33: final Map<String, ?> values)
34: throws ExpressionEvaluationException {
35: try {
36: final Binding binding = new Binding();
37: for (final Entry<String, ?> entry : values.entrySet()) {
38: binding.setVariable(entry.getKey(), entry.getValue());
39: }
40: final GroovyShell shell = new GroovyShell(binding);
41: LOG.debug("Evaluating Groovy expression: {}", expression);
42: return shell.evaluate(expression);
43: } catch (final GroovyRuntimeException ex) {
44: throw new ExpressionEvaluationException(
45: "Evaluating script with Groovy failed.", ex);
46: }
47: }
48:
49: public boolean evaluateAsBoolean(final String expression,
50: final Map<String, ?> values)
51: throws ExpressionEvaluationException {
52: final Object result = evaluate(expression, values);
53:
54: if (!(result instanceof Boolean))
55: throw new ExpressionEvaluationException(
56: "The script must return a boolean value.");
57: return (Boolean) result;
58: }
59: }
|