Calling custom script function with ScriptEngine from Java

2.4k views Asked by At

I have same custom functions with the same names on different script files written in python, groovy and javascript. User can choose one of the scripts that want to use. I want to call functions from these scripts in generic way.

  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("python");
  Bindings bindings = engine.createBindings();

  engine.eval(new FileReader("C:/Users/Cgr/Desktop/CustomPython.py");
  Invocable inv = (Invocable) engine;

  System.out.println(inv.invokeFunction("customConcatFunc", "str1", "str2"));

With this way I can call my functions even change ScriptEngineManager parameter as "javascript" or "groovy" with changing reader files with "CustomJs.js" or "Customgroovy.groovy".

However, I wonder that is there a way to call functions without using invokeFunction like below:

First, evaluate script and put the result on binding then calling function on this object.

   bindings.put("x", "str1");
   bindings.put("y", "str2");
   bindings.put("script", engine.eval(new FileReader("C:/Users/Cgr/Desktop/CustomgrPython.py")));

   engine.eval("script.customConcatFunc(x,y)", bindings);

So, this is the most generic way for me if there is way like this or are there any other suggestions?

1

There are 1 answers

0
TCH On

The method below might be helpful avoiding call invokeFunction:

@Test
public void test60_ScriptEngineTest()
        throws URISyntaxException, ScriptException, NoSuchMethodException, FileNotFoundException {

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("groovy");
    Compilable compilable = (Compilable) engine;
    Bindings bindings = engine.createBindings();

    URL url=getClass().getResource("/data-encoder-dir/testFunc.groovy");
    File script =new File(url.toURI());
    Reader reader = new FileReader(script);
    CompiledScript compiledScript = compilable.compile(reader);

    bindings.put("x", 5011);
    String result = (String) compiledScript.eval(bindings);
    assertEquals(result, "5011");

}

a groovy file attached (in /data-encoder-dir/testFunc.groovy):

public String testFunc(Integer bd) {
    return bd.toString();
}

testFunc(x)

PS: I'm using groovy, the javascript scenario or other java script engine compatible would follow the same route.