Wednesday 9 December 2015

Java - Call ruby script functions from java code

Sample Program:

Java Code: SampleJsTest .java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class SampleJsTest {

public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {

//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();

//create a RubyScript engine
ScriptEngine engine = manager.getEngineByName("ruby");

engine.eval(Files.newBufferedReader(Paths.get("C:\\eclipse\\RubyDemoProject\\Test.rb"), StandardCharsets.UTF_8));

Invocable inv = (Invocable)engine;
long a = (long) inv.invokeFunction("add", "3", "2");
System.out.println(">>>"+a);

}

}

Ruby script: Test.rb
def add (var1, var2)
   return var1.to_i + var2.to_i
end



Test.rb - ruby file.




Execute the java program.



Place jruby.jar in build path, to avoid the run time exception.

Download jruby.jar from http://jruby.org/download



Extract the downloaded zip file.

Now set the java build path for 'jruby.jar'.








Now execute the java program again, after setting the build path for 'jruby.jar'.



Note:
- For executing the ruby script function from java code using above procedure, doesn't require ruby software installed on your machine.
- Using above procedure java code passes two int values to the ruby script function, but result is returned as long value.

No comments:

Post a Comment