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.ArrayList;
15: import java.util.Map;
16: import java.util.Map.Entry;
17:
18: import net.sf.oval.exception.ExpressionEvaluationException;
19: import net.sf.oval.internal.Log;
20:
21: import org.jruby.Ruby;
22: import org.jruby.javasupport.JavaEmbedUtils;
23: import org.jruby.runtime.builtin.IRubyObject;
24:
25: /**
26: * @author Sebastian Thomschke
27: *
28: */
29: public class ExpressionLanguageJRubyImpl implements ExpressionLanguage {
30: private final static Log LOG = Log
31: .getLog(ExpressionLanguageJRubyImpl.class);
32:
33: public Object evaluate(final String expression,
34: final Map<String, ?> values)
35: throws ExpressionEvaluationException {
36: try {
37: final Ruby runtime = JavaEmbedUtils
38: .initialize(new ArrayList<String>());
39:
40: final StringBuilder localVars = new StringBuilder();
41: for (final Entry<String, ?> entry : values.entrySet()) {
42: runtime.getGlobalVariables().set(
43: "$" + entry.getKey(),
44: JavaEmbedUtils.javaToRuby(runtime, entry
45: .getValue()));
46: localVars.append(entry.getKey());
47: localVars.append("=$");
48: localVars.append(entry.getKey());
49: localVars.append("\n");
50:
51: }
52: LOG.debug("Evaluating Ruby expression: {}", expression);
53: final IRubyObject result = runtime.evalScript(localVars
54: + expression);
55: return JavaEmbedUtils.rubyToJava(runtime, result,
56: Object.class);
57: } catch (final RuntimeException ex) {
58: ex.printStackTrace(System.out);
59: throw new ExpressionEvaluationException(
60: "Evaluating script with JRuby failed.", ex);
61: }
62: }
63:
64: public boolean evaluateAsBoolean(final String expression,
65: final Map<String, ?> values)
66: throws ExpressionEvaluationException {
67: final Object result = evaluate(expression, values);
68:
69: if (!(result instanceof Boolean))
70: throw new ExpressionEvaluationException(
71: "The script must return a boolean value.");
72: return (Boolean) result;
73: }
74: }
|