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 ognl.Ognl;
20: import ognl.OgnlContext;
21: import ognl.OgnlException;
22:
23: /**
24: * @author Sebastian Thomschke
25: *
26: */
27: public class ExpressionLanguageOGNLImpl implements ExpressionLanguage {
28: private final static Log LOG = Log
29: .getLog(ExpressionLanguageOGNLImpl.class);
30:
31: public Object evaluate(final String expression,
32: final Map<String, ?> values)
33: throws ExpressionEvaluationException {
34: try {
35: final OgnlContext ctx = (OgnlContext) Ognl
36: .createDefaultContext(null);
37:
38: for (final Entry<String, ?> entry : values.entrySet()) {
39: ctx.put(entry.getKey(), entry.getValue());
40: }
41:
42: LOG.debug("Evaluating OGNL expression: {}", expression);
43: return Ognl.getValue(expression, ctx);
44: } catch (final OgnlException ex) {
45: throw new ExpressionEvaluationException(
46: "Evaluating script with OGNL failed.", ex);
47: }
48: }
49:
50: public boolean evaluateAsBoolean(final String expression,
51: final Map<String, ?> values)
52: throws ExpressionEvaluationException {
53: final Object result = evaluate(expression, values);
54:
55: if (!(result instanceof Boolean))
56: throw new ExpressionEvaluationException(
57: "The script must return a boolean value.");
58: return (Boolean) result;
59: }
60: }
|