code-generationvelocitytelosys

Is it possible in a Telosys template to call a function created specifically?


I use Telosys (https://www.telosys.org) to generate Python source code and it works fine. But I have a specific need that could be solved by calling a specific conversion function.

Is it possible to create a specific function and to call it inside a Telosys template?

For example: myFunction(“abc”) or $something.myFunction(“abc”) or anything else

If necessary it's possible for me to create this function in different languages ​​like Java, Python or JavaScript.


Solution

  • Telosys is designed to be extensible, so yes you can create your own functions and call them in your templates. As Telosys is written in Java you will have to create these functions in Java, then use the "loader" object in the ".vm" file to load your class and call the methods defined in this class.

    Here's how to do that step by step:

    1. Use your preferred IDE to create a Java class defining your specific method(s). This class can be in any package (including the "default / unnamed package"), the method(s) can be "static" if you don't need an instance of the class.

    2. Compile this class (the goal is to produce a simple ".class" file or a ".jar" file if you prefer)

    3. Put the class (or the jar) in the templates bundle folder :

    Examples :

    TelosysTools/templates/my-bundle/classes/MyClass.class
    TelosysTools/templates/my-bundle/lib/my-lib.jar
    
    1. In the template file (".vm") use the "$loader" object to load your Java class and call any of its methods See "$loader" reference here : http://www.telosys.org/templates-doc/objects/loader.html

    If all your methods are “static” you don’t need an instance so just use “$loader.loadClass()”. Example :

    ## load the class and keep it in a new “$Math” object (no instance created)
    #set( $Math = $loader.loadClass("java.lang.Math")
    ## use the static methods of this class
    $Math.random()
    

    If your methods are not “static” so you need an instance, then use “$loader.newInstance()”. Examples :

    ## create an instance of StringBuilder and put it in the context with #set
    #set( $strBuilder = $loader.newInstance('java.lang.StringBuilder') )
    ## use the instance to call a method
    $strBuilder.append('aa')
           
    ## create new instance of a specific class : MyTool.class
    #set( $tool = $loader.newInstance('MyTool') )
    ## use the instance to call a method
    $tool.myFunction()
    

    So to sum up, you can use any class provided by Java-JRE (eg "Math", “StringBuilder”), you can reuse existing libraries by adding a “.jar” file (don't forget to add dependencies required if the jar file is not stand-alone) or just add a single “.class” file.