In previous steps, we created an MDWorkbench project and inspected the structure of model information we need to handle. Now we are ready to create a generation program using a text template.
A text template specifies the information to generate in a given file as well as the name of the file.
To create a text template:
A file JavaSource.tgt is created in the folder com.sodius.mdw.samples.tutorial/src/tutorial/java and is opened in an editor.
[#package tutorial.java] [#template public JavaSource()] [#file]file.txt[/#file] generated text [/#template]
The text template JavaSource is defined in the package tutorial.java and generates the static text generated text in the file file.txt.
We want to generate a Java source file based on a UML input Class. So we need to add a UML Class parameter to the text template:
[#package tutorial.java] [#template public JavaSource(class : uml21.Class)] [#file]file.txt[/#file] generated text [/#template]
Add the code "class : uml21.Class
"
and click File > Save.
uml21 is the metamodel identifier of the UML 2.1 metamodel, Class is the name of a metatype defined in this metamodel, and class is the name of the parameter.
The generated file name and contents must depend on the UML Class name.
So we need to change the contents of the template and file directives
to reflect the name of the class parameter, using dynamic text.
Dynamic text is a section delimited by ${
and }
replaced with a calculated value in the output.
Change the text template contents to:
[#package tutorial.java] [#template public JavaSource(class : uml21.Class)] [#file]generated/${class.name}.java[/#file] public class ${class.name} { } [/#template]
Now the generated contents will be the static text "public class "
,
followed by the name of the class parameter and by brackets.
This generated contents will be written out in a file whose name is the name of the class parameter,
extension is ".java"
,
in a "generated"
folder.
TGL (Template Generation Language)
package directive
file directive