9.9 Extending XDoclet to Generate Custom Files

9.9.1 Problem

You would like to extend XDoclet to generate custom files.

9.9.2 Solution

There are five main steps needed to create a custom XDoclet extension. XDoclet refers to custom extensions as modules. A module is a JAR file with a specific naming convention and structure. See Recipe 9.14 for more information on modules. Here are the steps:

  1. Create an Ant task and subtask to invoke your XDoclet code generator from an Ant buildfile.

  2. Create an XDoclet tag handler class to perform logic and generate snippets of code.

  3. Create an XDoclet template file (.xdt) for mixing snippets of Java code with XDoclet tag handlers to generate a complete file.

  4. Create an xdoclet.xml file that defines the relationships of tasks and subtasks, as well as specifying a tag handlers namespace.

  5. Package the new XDoclet code generator into a new JAR file, known as a module.

9.9.3 Discussion

Creating a custom code generator is not as dire as you may think. The key is to take each step one at a time and build the code generator in small chunks. There are five main steps needed to complete an entire custom code generator, and each of these steps is broken into its own recipe.

The following recipes build a code generator for creating JUnitPerf test classes based on custom XDoclet @ tags. The new @ tags are used to mark up existing JUnit tests to control the type of JUnitPerf test to create. This example is realistic because JUnitPerf tests build upon existing JUnit tests. By simply marking up a JUnit test with specific @ tags, a JUnitPerf test can be generated and executed through Ant. The code generator is aptly named JUnitPerfDoclet.[6]

[6] At the time of this writing, a tool to generate JUnitPerf tests did not exist.

9.9.4 See Also

Recipe 9.10 shows how to create a custom Ant Doclet subtask to generate JUnitPerf tests. Recipe 9.11 shows how to create the JUnitPerfDoclet tag handler class to perform simple logic and generate snippets of code. Recipe 9.12 shows how to create a custom template file that uses the JUnitPerfDoclet tag handler. Recipe 9.13 shows how to create an XDoclet xdoclet.xml file used to define information about your code generator. Recipe 9.14 shows how to package JUnitPerfDoclet into a JAR module. Chapter 8 provides information on the JUnitPerf tool and how to update your Ant buildfile to invoke JUnitPerfDoclet.