Add a script to handle the type

We now want to insert the type of each attribute in the second column. The type name should reflect the multiplicity of the attribute, for example to print "Collection" when the multiplicity if 0..*. We could add an if tag directly in the second column, but this would add complexity to the template. So we will simplify the template using a script. A script is a method dynamically added to a metatype.

The type Property inherits from the type MultiplicityElement. The Java class com.sodius.mdw.metamodel.uml21.MultiplicityElement defines a method isMultivalued(), which determines if the upper bound is higher than 1.

To add a script:

  1. Click File > New > Script.
  2. Type com.sodius.mdw.samples.tutorial/src in the Source folder field.
  3. Type tutorial.doc in the Package field.
  4. Type uml21.Property in the Type field.
  5. Type typeName in the Name field.
  6. Click MQL in the Language group.

  7. Click Finish.

A file uml21_Property.mqs is created: it allows us to define MQL scripts on the metatype UML Property. Change its contents to:

package tutorial.doc;

metatype uml21.Property;

public script typeName() : String {
    var name : String = self.type.name;
    if (self.isMultivalued()) {
        return "Collection of " + name;
    }
    else {
        return name;
    }
}

The self variable is available in the script contents. This variable is the instance the script is evaluated on (instance of the script's metatype).

Now the script typeName can be used in a doc template, as you do with any predefined feature of the type Property (e.g. ${myProperty.typeName}).

Related reference
method call