Automatic UML diagram generation for Maven projects

Jan 6, 2021 by Thibault Debatty | 1150 views

Java

https://cylab.be/blog/117/automatic-uml-diagram-generation-for-maven-projects

Documenting your project is an important part of good software development. Creating and maintaining UML diagrams is one of the things to do. Luckily, there is a maven plugin that does this automatically for you...

maven

To add the urm-maven-plugin to your maven project, add the following snippet to the <plugins> section of your pom.xml:

<plugin>
    <groupId>com.iluwatar.urm</groupId>
    <artifactId>urm-maven-plugin</artifactId>
    <version>1.4.8</version>
    <configuration>
        <outputDirectory>${project.basedir}/target</outputDirectory>
        <packages>
            <param>be.cylab.mark.server</param>
        </packages>
        <ignores>
        </ignores>
        <includeMainDirectory>true</includeMainDirectory>
        <includeTestDirectory>false</includeTestDirectory>
        <presenter>graphviz</presenter>
    </configuration>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>map</goal>
            </goals>
        </execution>
    </executions>
</plugin>

In this example:

  • We use version 1.4.8 of the plugin. At the time of writing, there is also a version 2.0.0 but that did not appear to work for our project.
  • You have to list the packages for which you want to create the diagram (be.cylab.mark.server in our example).
  • You can choose to ignore classes from the produced diagram.
  • The map goal of the plugin will be executed during the process-classes phase of the build process (right after the compile phase).

Now you can run the plugin using maven, for example:

mvn clean package

The UML graph will be saved in target/${project.name}.urm.dot

graphviz

urm-maven-plugin does not produce an image. It produces a graph description in one of three possible formats: graphviz (like in our example), plantuml or mermaid.

To create an image from this description, we need graphviz installed:

sudo apt install graphviz

clean

There is one caveat: urm-maven-plugin does not escape < and > characters, which will cause errors (Error: bad label format) when we try to convert to a png image.

So we first have to use sed to escape these characters:

sed -i 's/</\\</g' target/server.urm.dot
sed -i 's/>/\\>/g' target/server.urm.dot
sed -i 's/-\\>/->/g' target/server.urm.dot

convert

Now we can use the dot program (part of graphviz) to create a png image:

dot -Tpng target/server.urm.dot -o target/server.urm.png