You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Modelio embeds a Jython script engine that can execute Jython code. Jython scripts can access the Modelio Java API exactly as modules can.
Jython is an interpreted langage, therefore Jython scripts can be use to develop ‘quick and dirty’ experimental or temporary pieces of code often called macros. Jython is accessible as a Modelio view in which Jython code fragments can directly be entered and evaluated.
The Modelio script service provides the same capability of evaluating Jython code at the API level. The API is able to provide a Jython script engine:
Specific to the caller module (ie Jython engine is not shared between modules)
Configured to have access to the full Modelio API
Class loader configuration
Modelio API packages pre-import
The returned Jython engine can then run any Jython code fragment as needed.
The Jython engine is available at the module level, ie you need to ask your own module instance for a Jython engine instance using the `getJythonEngine() method of `IModuleContext. Note that successive calls to `getJythonEngine()` will return the same Jython engine instance for a given module.
Modelio script service provides a Jython engine which is a javax.script.ScriptEngine instance:
specific to your module. Note that successive calls to the service will return the same instance for a given module.
several Jython variables are pre-defined and initialized
SESSION: the modeling session
MODULE: the module which the script engine is attached to
CLASSLOADER: the module class loader
Modelio API packages are pre-imported in the engine to make the API available
Example
In the following example, we implement a module command using Jython.
1import java.util.List;
2
3import javax.script.ScriptEngine;
4import javax.script.ScriptException;
5
6import org.modelio.api.module.IModule;
7import org.modelio.api.module.commands.DefaultModuleContextualCommand;
8import org.modelio.vcore.smkernel.mapi.MObject;
9
10public class HelloWorldInJython extends DefaultModuleContextualCommand {
11 ...
12 public void actionPerformed(List<MObject> selectedElements, IModule module) {
13 // get the Jython engine
14 ScriptEngine jythonEngine = module.getModuleContext().getJythonEngine();
15
16 // use the Jython engine to evaluate some Jython code
17 try {
18 jythonEngine.eval("print 'Hello, world!'");
19 } catch (ScriptException ex) {
20 module.getModuleContext().getLogService().error(ex);
21 }
22 }
23 ...
24 }
line 18: the script expression is evaluated by this call to the eval() method. line 20: if an error occurs while evaluating the Jython code a ScriptException is thrown. See how the log service error method can directly log an exception.