Agile Zone is brought to you in partnership with:

Meera has posted 70 posts at DZone. You can read more from them at their website. View Full User Profile

Reverse-engineer Source Code into UML Diagrams

08.22.2008
| 171680 views |
  • submit to reddit

I have been on several teams where we studiously designed UML diagrams at the beginning of the project. As the project progressed, and deadlines approached, the UML diagrams were left somewhere behind, not to be updated in months. When a new developer joined the team, we showcased the old UML diagrams, and kept telling "Oh, we never had time to update them, please see the source code to get an idea. And, don't hesitate to ask if you have any doubt's". I am sure, you all have gone through the same scenario.

However, we don't have to keep making up stories anymore, since this article shows how easy and simple it is to include UML diagrams within your Javadoc and also keep them updated with every change in the source code repository. We can do these in less than a few minutes, and in a few simple steps.

Getting started with UmlGraph takes five steps:

  1. Download the source code for UMlGraph.
  2. Download and install Graphviz.
  3. Make changes to your Ant build file.
  4. Run the Ant target.
  5. Add this target to your CI job.

Step 1: Download the source code for UMLGraph from here. Unzip the contents. To compile the Java doclet from the source code run ant on the build.xml file. Copy the UmlGraph.jar file to your projects library. If there is a version mismatch between the different versions of JDK you are using you get an exception like this:

java.lang.UnsupportedClassVersionError: Bad version number in .class file

Make sure you recompile the UMLGraph source code, and copy the library to your project.

Step2 : Download and install Graphviz from here. The dot file needs to be post-processed with Graphviz to produce the actual UML diagram. Running the UmlGraph doclet will generate a Graphviz diagram specification that can be automatically processed to create png drawings. You can also generate other formats using Graphviz as well. If Graphviz isn’t installed you will get an exception as shown below:

BUILD FAILED
/Users/meerasubbarao/Development/webservices-samples/build.xml:107:
Execute failed: java.io.IOException: dot: not found
Total time: 269 milliseconds


Step 3. Changes to your build.xml file.
Assuming you already have a working project, with Ant build file. Add the following target to your build.xml file as shown below:

<target name="javadocs" depends="build" description="generates javadoc and also UML Diagram">
<mkdir dir="${reports.dir}/javadoc"/>
<javadoc sourcepath="${src.dir}" packagenames="com.stelligent.*" destdir="${reports.dir}/javadoc"
classpathref="java.classpath" private="true">
<doclet name="org.umlgraph.doclet.UmlGraphDoc"
path="lib/UMLGraph.jar">
<param name="-attributes" />
<param name="-operations" />
<param name="-qualify" />
<param name="-types" />
<param name="-visibility" />
</doclet>
</javadoc>
<apply executable="dot" dest="${reports.dir}" parallel="false">
<arg value="-Tpng"/>
<arg value="-o"/>
<targetfile/>
<srcfile/>
<fileset dir="${reports.dir}" includes="*.dot"/>
<mapper type="glob" from="*.dot" to="*.png"/>
</apply>
</target>

 

A number of options contol the operation of UMLGraph class diagram generator. These can be specified as parameters within your build file as shown above.

Details about a few options are:

-output
Specify the output file (default graph.dot).
-d
Specify the output directory (defaults to the current directory).
-qualify
Produce fully-qualified class names.
-horizontal
Layout the graph in the horizontal direction.
-attributes
Show class attributes (Java fields)
-operations
Show class operations (Java methods)
-constructors
Show a class's constructors
-visibility
Adorn class elements according to their visibility (private, public, protected, package)
-types
Add type information to attributes and operations
-enumerations
Show enumarations as separate stereotyped primitive types.
-enumconstants
When showing enumerations, also show the values they can take.
-all
Same as -attributes -operations -visibility -types -enumerations -enumconstants

Take a look here for more options.

Step 4. Run the ant target:
Open a command window and run the ant target: ant javadocs and you should see output as such in your console window:

meera-subbaraos-macbook-9:webservices-samples meerasubbarao$ ant javadocs
Buildfile: build.xml

init:

cleanGenerated:

build:
[javac] Compiling 22 source files to /Users/meerasubbarao/Development/ci-jobs/jobs/PetStore_Nightly/workspace/webservices-samples/classes
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.

javadocs:
[javadoc] Generating Javadoc
[javadoc] Javadoc execution
[javadoc] Loading source files for package com.stelligent.biz.ws...
[javadoc] Loading source files for package com.stelligent.ent.jpa...
[javadoc] Constructing Javadoc information...
[javadoc] UmlGraphDoc version 5.0, running the standard doclet
[javadoc] Standard Doclet version 1.5.0_13
[javadoc] Building tree for all the packages and classes...
[javadoc] Building index for all the packages and classes...
[javadoc] Building index for all classes...
[javadoc] Generating /Users/meerasubbarao/Development/ci-jobs/jobs/PetStore_Nightly/workspace/webservices-samples/reports/javadoc/stylesheet.css...
[javadoc] UmlGraphDoc version 5.0, altering javadocs
[javadoc] Building Package view for package com.stelligent.biz.ws
[javadoc] Building Package view for package com.stelligent.ent.jpa
[javadoc] Building Context view for class com.stelligent.biz.ws.SupplierManagerBean
[javadoc] Building Context view for class com.stelligent.biz.ws.SupplierManager
[javadoc] Building Context view for class com.stelligent.biz.ws.SignonManagerBean
[javadoc] Building Context view for class com.stelligent.biz.ws.SignonManager
.....

BUILD SUCCESSFUL
Total time: 8 seconds
meera-subbaraos-macbook-9:webservices-samples meerasubbarao$

 

The javadoc generated is pretty neat with UML diagrams on the top:

Step 5: Add this target to your CI Job.
If you already have a CI server like Hudson up and running, which runs commit builds and nightly builds, adding this new target is a one step process. In my case, I already have a nightly job running, I added this ant target to my default target as shown below:

<target name="all" depends="cleanAndDeployForCoverage, javadocs" />

Next, force a build on the Hudson job, publish the javadocs, and you can see the results on the hudson dashboard.

The Javadoc embedded with UML diagrams displayed from within the Hudson dashboard:

Now that we have UML diagram integrated within our build file, and also our CI job, we can ensure that our code base and the UML diagrams are always in sync. We saw how to include these ant targets in our commit builds or nightly builds of our CI jobs, and also published these artifacts as part of our post build process.

 

Resources:

Published at DZone with permission of its author, Meera Subbarao.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Eric Asberry replied on Fri, 2008/08/22 - 10:36am

Thanks for the article!  I've been looking for something like this as I'm trying to learn a pretty complex system at a new job.

Meera Subbarao replied on Fri, 2008/08/22 - 10:59am in response to: Eric Asberry

Yes, indeed. As I mentioned in my article, you can do it in less than few minutes.

Eric Asberry replied on Fri, 2008/08/22 - 12:40pm

Yes, I was able set this up very quickly with your detailed instructions.

One thing I quickly learned is that its not feasible for me to include this on every integration build.  For my very large project it made the javadoc generation time go from 4 minutes to around 30+, so I've set up a separate job for this task to just run nightly.  But I'm very glad to have this!

Meera Subbarao replied on Fri, 2008/08/22 - 2:06pm

Great. Yes, I agree. That's the reason I mentioned about nightly jobs in my article.

Michael Weber replied on Sun, 2008/08/24 - 3:37pm

Martin Keschenau's class2uml does something similar: besides class diagrams, class2uml also generates UML elements for generalizations, dependencies and associations.

Meera Subbarao replied on Sun, 2008/08/24 - 4:54pm

You can do that using UMLGraph as well using some of the following parameters:

1. aggregation relationships (specified using the javadoc @has tag)
2. composition relationships (specified using the javadoc @composed tag)
3. dependency relationships (specified using the javadoc @depend tag)

James Selvakumar replied on Sun, 2008/08/24 - 8:41pm

Hi Meera,

Excellent article. The scenario you explained is absolutely true and I feel every organization must use this. I'll surely try this out.

Meera Subbarao replied on Mon, 2008/08/25 - 7:11am

Hi James,

Give it a try, you will be surprised how easy and above all useful this will be for your project. 

Antti Kekki replied on Mon, 2008/08/25 - 7:39am

Great article! Finally easy and working (and also free) solution to reverse engineer java-code to UML class diagrams in Eclipse. Ant and Eclipse appears to be very versatile tools: Build, deployment and javadoc generation with UML class diagrams with one click. Not bad!

Pether Sorling replied on Mon, 2008/08/25 - 11:36am

How to use it in maven

---

            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
                    <docletArtifact>
                        <groupId>gr.spinellis</groupId>
                        <artifactId>UmlGraph</artifactId>
                        <version>5.0</version>
                    </docletArtifact>
                    <additionalparam>
                        -inferrel -inferdep -quiet -hide java.* -collpackages java.util.* -qualify -postfixpackage -nodefontsize 9
                        -nodefontpackagesize 7
                    </additionalparam>
                </configuration>
            </plugin>

---
 

Also a tool to consider that creates nicer diagrams but cost money is yDoc

Meera Subbarao replied on Mon, 2008/08/25 - 4:46pm

Hi Pether,

Thanks for posting the maven task.  

Diomidis Spinellis replied on Tue, 2008/08/26 - 12:51am

Meera,

 This is an excellent article!  I will link it on UMLGraph's documentation.  To make the javadoc documentation easier to navigate, the upcoming version of UMLGraph will contain Javascript to show/hide the generated UML diagrams.  Stay tuned!

 Diomidis

Michael Weber replied on Tue, 2008/08/26 - 4:34am in response to: Meera Subbarao

Ah, interesting.  class2uml analyzes bytecode to find this information, which is nice if the original source code did not have any annotations.  Since the tool is also intended for reverse-engineering resp. a starting point for refactoring, it goes to some lengths to ensure for example that the analyzed cardinalities are not mind-boggling.

Meera Subbarao replied on Tue, 2008/08/26 - 7:08am

Neal Ford, in his latest book "The Productive Programmer", which I received just yesterday, says as follows in page 92 of Chapter 5: Canonicality:

Some IDEs (such as Visual Studio) will offer to generate diagrams for you, but they are sometimes hard to automate. Ideally, you should generate diagrams at the same time you compile your code(using something like a continuous integration server). That way, you never have to think, "Are my diagrams up-to-date?" because they always live in an up-to-date state.

I am glad this article shows you how to do the excat same thing.

Nitin Aggarwal replied on Tue, 2008/08/26 - 9:42am in response to: Pether Sorling

Hi ,

 I have tried to add this to my POM.

 

 <reporting>
       <plugins>
               <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <reportSets>
               <reportSet>
                  <id>uml</id>
                  <configuration>
                     <doclet>gr.spinellis.umlgraph.doclet.UmlGraph</doclet>

                     <!--docletPath>/path/to/UmlGraph.jar</docletPath-->
                     <docletArtifact>
                        <groupId>gr.spinellis</groupId>
                        <artifactId>UmlGraph</artifactId>
                        <version>5.0</version>
                     </docletArtifact>

                     <additionalparam>-views</additionalparam>
                     <destDir>target/uml</destDir>
                     <show>private</show>
                  </configuration>
                  <reports>
                     <report>javadoc</report>
                  </reports>
               </reportSet>
               <reportSet>
                  <id>html</id>
                  <configuration>
                     <show>private</show>
                  </configuration>
                  <reports>
                     <report>javadoc</report>
                  </reports>
               </reportSet>
            </reportSets>
         </plugin>

        </plugins>
    </reporting>
 

 

But i am still not able to get it working.

Do we need to add some goals for this ?

I installed the umlgraph jar using $ mvn install:install-file  -Dpackaging=jar -DartifactId=UmlGraph -Dversion=5.0 -Dfile=path to/UmlGraph.jar -DgroupId=gr.spinellis -DgeneratePom=true

Does running simple mvn install work ??? or a specific call is needed?

 

Diomidis Spinellis replied on Tue, 2008/08/26 - 9:51am in response to: Nitin Aggarwal

Under UMLGraph version 5.0 and later, all code lives under org.umlgraph, not gr.spinellis.  Try changing the corresponding references.

Meera Subbarao replied on Tue, 2008/08/26 - 10:00am in response to: Diomidis Spinellis

[quote=dspin]

Meera,

This is an excellent article! I will link it on UMLGraph's documentation. To make the javadoc documentation easier to navigate, the upcoming version of UMLGraph will contain Javascript to show/hide the generated UML diagrams. Stay tuned!

Diomidis

[/quote]

 Hi Diomidis,

Do update us here on this thread when the new version comes out.  

Meera Subbarao

Pether Sorling replied on Tue, 2008/08/26 - 11:46am in response to: Diomidis Spinellis

Really like umlgraph, but missing the package dependency diagram.  example from ydoc any feature you are planning ?

Diomidis Spinellis replied on Tue, 2008/08/26 - 1:07pm in response to: Pether Sorling

The link you posted looks to me like a class diagram inside a package container, rather than a package dependency diagram.  Is that what you want?

Pether Sorling replied on Tue, 2008/08/26 - 1:16pm in response to: Diomidis Spinellis

Sorry I meant this one ! But always like more diagrams :)

Nitin Aggarwal replied on Wed, 2008/08/27 - 4:20am in response to: Diomidis Spinellis

thanks Diomidis,

I have managed to generate the .Dot files but i am unable to understand how can i  use graphviz in maven2.

as per my understanding i have graphviz installed on my machine. and its and exe how can i have that talk to maven. in order to generate the final uml diagrams ??

One alternative i thought about is to use antrun plugin of maven in order to execute it as a ant task.

If there any other approach?

 

 

 

Diomidis Spinellis replied on Wed, 2008/08/27 - 4:26am in response to: Pether Sorling

I looked into the proposal some more.  It would involve adding a single diagram to the JavaDoc HTML file overview-summary.html.  I've already contributed to GraphViz a change that allows it to draw UML package-style boxes, and UMLGraph supports them via the "shape package" option, so drawing the packages is easy.  I think the relevant code should be placed in UmlGraphDoc.generatePackageDiagrams.  Contributions welcomed!

Diomidis Spinellis replied on Wed, 2008/08/27 - 4:34am in response to: Nitin Aggarwal

Sorry, I'm not a Maven expert.  However, keep in mind that UmlGraphDoc (the subject of this article) will autoamtically run dot internally to generate the UML diagrams.   Justensure that dot appears in your path.

Meera Subbarao replied on Wed, 2008/08/27 - 6:26am

I am glad it worked for Maven users as well. Thanks for sharing your efforts.

Meera Subbarao replied on Wed, 2008/08/27 - 7:15am

For those of you who are interested in generating UML Diagrams from NetBeans IDE,  Geertjan Wielenga has written an article at the NetBeans Zone.

Sakthivel Palan... replied on Wed, 2008/08/27 - 8:07am

I installed UML graph in my maven project. But I do not know how to generate diagrams? I run mvn install, it is not generating graphs.

 if any one through lights on this will be appriciated.

Meera Subbarao replied on Wed, 2008/08/27 - 8:21am in response to: Sakthivel Palaniappan

[quote=sakthivel.sp@gmail.com]

I installed UML graph in my maven project. But I do not know how to generate diagrams? I run mvn install, it is not generating graphs.

if any one through lights on this will be appriciated.

[/quote]

Take a look at one of the comments above, I think you should run the mvn javadoc:javadoc plugin. I am not a Maven expert. Hope to become one soon..

Meera Subbarao

Pether Sorling replied on Wed, 2008/08/27 - 11:30am in response to: Diomidis Spinellis

Thanks for the feedback, had quick look at the code but will have to investigate further once I have more time.

Diomidis Spinellis replied on Wed, 2008/08/27 - 12:42pm

A few minutes ago I releazed UMLGraph 5.1.  This version has active classes appearing with a double vertical border as required by UML2, two new class diagram options, which control the node and rank separation of the nodes in generated diagram layout, support for showing a class's title as a tooltip in image files, and an option for generating Javascript-collapsible UML diagrams in javadoc files. I also reorganized the documentation of class diagram options and gave the project's web page a small face lift.

Meera Subbarao replied on Wed, 2008/08/27 - 2:01pm

That was really quick, Diomidis. Thanks for the update. I sure will give it a try.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.