View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2015 Sebastian
3    * Thomschke.
4    *
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    *
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.expression;
14  
15  import java.util.ArrayList;
16  import java.util.Map;
17  import java.util.Map.Entry;
18  
19  import net.sf.oval.exception.ExpressionEvaluationException;
20  import net.sf.oval.internal.Log;
21  
22  import org.jruby.CompatVersion;
23  import org.jruby.Ruby;
24  import org.jruby.RubyInstanceConfig;
25  import org.jruby.javasupport.JavaEmbedUtils;
26  import org.jruby.runtime.builtin.IRubyObject;
27  
28  /**
29   * @author Sebastian Thomschke
30   *
31   */
32  public class ExpressionLanguageJRubyImpl extends AbstractExpressionLanguage
33  {
34  	private static final Log LOG = Log.getLog(ExpressionLanguageJRubyImpl.class);
35  
36  	public Object evaluate(final String expression, final Map<String, ? > values) throws ExpressionEvaluationException
37  	{
38  		LOG.debug("Evaluating JRuby expression: {1}", expression);
39  		try
40  		{
41  			final RubyInstanceConfig config = new RubyInstanceConfig();
42  			config.setCompatVersion(CompatVersion.RUBY1_9);
43  			final Ruby runtime = JavaEmbedUtils.initialize(new ArrayList<String>(), config);
44  
45  			final StringBuilder localVars = new StringBuilder();
46  			for (final Entry<String, ? > entry : values.entrySet())
47  			{
48  				runtime.getGlobalVariables().set("$" + entry.getKey(), JavaEmbedUtils.javaToRuby(runtime, entry.getValue()));
49  				localVars.append(entry.getKey()) //
50  						.append("=$") //
51  						.append(entry.getKey()) //
52  						.append("\n");
53  			}
54  			final IRubyObject result = runtime.evalScriptlet(localVars + expression);
55  			return JavaEmbedUtils.rubyToJava(runtime, result, Object.class);
56  		}
57  		catch (final RuntimeException ex)
58  		{
59  			throw new ExpressionEvaluationException("Evaluating JRuby expression failed: " + expression, ex);
60  		}
61  	}
62  }