Using UML2 with Groovy
November 29, 2007
The UML2 project provides an EMF based implementation of the UML 2.x metamodel in Java. The fact that the underlying technology is the Eclipse Modeling Framework (EMF) makes it possible to use the EMFBuilder with the UML2 metamodel.
Getting Started with UML2
The article Getting Started with UML2 by Kenn Hussey explains how to create UML2 models with the Eclipse editor and how to create them programmatically with Java code.
The data model is shown in the following diagram.
In the following it is shown how to create (parts of) this model with the EMFBuilder. Compare the code below to the original code in the article!
We use the
UMLFactory for the
We create a
Model as the root node and then we create four primitive types and store
them in Groovy variables because we have to reference them later on.
We define an enumeration
OrderStatus with three literals.
The following code snippet shows the definition of the class
All the attributes are defined as a
Here the primitive type
stringPrimitiveType defined above is used.
In UML2 there is the concept of "generalization" to model inheritance relationships. The class
USAddress is a subclass of
Address. This is expressed by using
An association is a relationship between two types. For each end of an association the type, the navigability, the aggregation, the name and the lower and upper bound have to be specified. The UML2 API method Type.createAssociation(). can be used to create an association and to connect the ends to the respective types.
The following code snippet creates the composite association between
PurchaseOrder (see the edge with the black diamond from from
PurchaseOrder) with the name
The one to many association between
PurchaseOrder is created
with the following code snippet.
Finally the model is saved into a file.
There are the following things to point out.
- The code is very concise and is a direct representation of the UML2 diagram.
- The auxiliary methods defined in the article are not needed.
- Beauty through brevity: shorter, less verbose, more expressive !
The source code is available with the EMFBuilder distribution.
Thanks to László Sütő for contributing a patch.
Remark: This post was adapted to the new blog format in November 2016.