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:
20: import org.mozilla.javascript.Context;
21: import org.mozilla.javascript.EvaluatorException;
22: import org.mozilla.javascript.Scriptable;
23:
24: /**
25: * @author Sebastian Thomschke
26: *
27: */
28: public class ExpressionLanguageJavaScriptImpl implements
29: ExpressionLanguage {
30: private final static Log LOG = Log
31: .getLog(ExpressionLanguageJavaScriptImpl.class);
32:
33: private final Scriptable parentScope;
34:
35: public ExpressionLanguageJavaScriptImpl() {
36: final Context ctx = Context.enter();
37: try {
38: parentScope = ctx.initStandardObjects();
39: } finally {
40: Context.exit();
41: }
42: }
43:
44: public Object evaluate(final String expression,
45: final Map<String, ?> values)
46: throws ExpressionEvaluationException {
47: final Context ctx = Context.enter();
48: try {
49: final Scriptable scope = ctx.newObject(parentScope);
50: scope.setPrototype(parentScope);
51: scope.setParentScope(null);
52:
53: for (final Entry<String, ?> entry : values.entrySet()) {
54: scope.put(entry.getKey(), scope, Context.javaToJS(entry
55: .getValue(), scope));
56: }
57: LOG.debug("Evaluating JavaScript expression: {}",
58: expression);
59: return ctx.evaluateString(scope, expression, "<cmd>", 1,
60: null);
61: } catch (final EvaluatorException ex) {
62: throw new ExpressionEvaluationException(
63: "Evaluating script with Rhino failed.", ex);
64: } finally {
65: Context.exit();
66: }
67: }
68:
69: public boolean evaluateAsBoolean(final String expression,
70: final Map<String, ?> values)
71: throws ExpressionEvaluationException {
72: final Object result = evaluate(expression, values);
73: if (!(result instanceof Boolean))
74: throw new ExpressionEvaluationException(
75: "The script must return a boolean value.");
76: return (Boolean) result;
77: }
78: }
|