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 java.util.Map;
15: import java.util.Map.Entry;
16:
17: import net.sf.oval.exception.ExpressionEvaluationException;
18: import net.sf.oval.internal.Log;
19: import bsh.EvalError;
20: import bsh.Interpreter;
21:
22: /**
23: * @author Sebastian Thomschke
24: */
25: public class ExpressionLanguageBeanShellImpl implements
26: ExpressionLanguage {
27: private final static Log LOG = Log
28: .getLog(ExpressionLanguageBeanShellImpl.class);
29:
30: public Object evaluate(final String expression,
31: final Map<String, ?> values)
32: throws ExpressionEvaluationException {
33: try {
34: final Interpreter interpreter = new Interpreter();
35: interpreter.eval("setAccessibility(true)"); // turn off access restrictions
36: for (final Entry<String, ?> entry : values.entrySet()) {
37: interpreter.set(entry.getKey(), entry.getValue());
38: }
39: LOG
40: .debug("Evaluating BeanShell expression: {}",
41: expression);
42: return interpreter.eval(expression);
43: } catch (final EvalError ex) {
44: throw new ExpressionEvaluationException(
45: "Evaluating script with BeanShell 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: }
|