Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Comparison with Java ScriptFactory



The approach of the scriptHelper is different from the Java ScriptFactory because it sees the script as implementing a Java interface.

Comparison

Java ScriptFactory scriptHelper
Evaluates a script expression or method Evaluates an interface method
The exceptions encountered in the Script are not seen in the StackTrace, it is not possible to see the original exception in the Script The exceptions encountered in the Script are seen in the StackTrace
Exceptions during the execution are thrown Exceptions during the execution can be catched and managed by your code
Debugging a script in the context of a Java program is not supported The framework allows to debug a script in the context of a Java program

Example

Use case

Suppose that we want to execute a Groovy Script which will perform some code analog to this interface:
      public interface Script {
        public int execute(int value);
      }
The script will have the following content:
      public int execute(int value) {
        return 10 * value;
      }

The ScriptFactory approach

We have two ways of invoking the script:
  • By using a script function (which is not exactly what we want to do)
  • By using a script method (which is exactly what we want to do here)

Using a Groovy function

We will first need to get the Groovy script engine:
      GroovyScriptEngineFactory factory = new GroovyScriptEngineFactory();
      ScriptEngine engine = factory.getScriptEngine();
Then we can execute the script:
      Invocable invocableEngine = (Invocable) engine;
      Reader reader = new BufferedReader(new FileReader(<the Script file>);
      engine.eval(reader);
      Object result = invocableEngine.invokeFunction("execute", 10);
The script itself is:
      public int execute(int value) {
        return 10 * value;
      }

Using a Groovy method

We will first need to get the Groovy ClassLoader:
      GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
Then we need to get the groovy class and object associated with the script:
      Class<Script> clazz = groovyClassLoader.parseClass(new File(url.getFile()));
      Script script = clazz.newInstance();
Then we can execute the script:
      int result = script.execute(10);
The script itself is:
      import org.scripthelper.scriptfactory.samples.Script;

      class MyScript implements Script {
        public int execute(int value) {
          return 20 * value;
        }
      }

The scriptHelper approach

We have to do:
      ScriptWrapper<Script> wrapper = new GroovyScriptWrapper<Script>(){
      };
      Script script = wrapper.getScript();

      wrapper.installScript(<the Script file>);
      int value = script.execute(10);

Categories: general

Copyright 2019-2020 Herve Girod. All Rights Reserved. Documentation and source under the BSD licence