Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Introducing XDoclet

XDoclet is an open source product that makes the power of attribute-oriented programming available to Java developers. As XDoclet precedes J2SE 5.0 annotations, it does so by enabling custom attributes to be specified within Java code as innocuous, compiler-friendly, Javadoc tags.

XDoclet began life as EJBDoclet and was the brainchild of leading open source contributor Rickard Öberg. The original EJBDoclet was built as a Javadoc plug-in that used the Doclet API to create custom Javadoc tags. With this ingenious approach, Öberg used his newly defined tags to generate Java files rather than the HTML pages commonly associated with Javadoc output.

As the name implies, EJBDoclet was primarily concerned with code generation for EJB support. However, since its inception, EJBDoclet has extended its portfolio to include software components other than enterprise beans. In line with this wider scope, the product name was changed to XDoclet, and it was launched as an active open source project. For the purposes of this discussion, we focus on the enterprise-bean-generation capabilities of XDoclet.

The custom Javadoc tags of XDoclet make it possible to generate much of the boilerplate code necessary for enterprise bean development.

The best way to appreciate the time XDoclet can save on a project is to look at an example. The next sections do just this, putting XDoclet through its paces by seeing just how much boilerplate code can be generated from the skeleton of a simple session bean.

The first step is to install the XDoclet software.

Installing XDoclet

XDoclet is maintained as a Source Forge project and can be downloaded from http://xdoclet.sourceforge.net. Full installation and setup instructions, along with information on the open source license, are provided as part of the download.

XDoclet is run using the Jakarta Ant build utility from Apache. Ant has proven extremely popular among the Java community and has overtaken build tools such as make as the de facto standard for building Java applications. A copy of Ant can be freely downloaded from the Apache site, see http://ant.apache.org.

If you are unfamiliar with Ant, you may wish to read the documentation that comes with the installation before continuing with this chapter. However, the Ant syntax is relatively straightforward, and the examples covered are explained in detail. We start by covering the Ant build file necessary to run XDoclet over our source files.

Setting Up the Ant Build File

The XDoclet installation comes with a number of Ant tasks that are used for invoking the doclet engine from Ant build files. The two main Ant tasks XDoclet provides are <ejbdoclet> for EJB support and <webdoclet> for Web applications. Since we are generating the code for an enterprise bean, the example covers the use of the <ejbdoclet> Ant task.

Listing 6-4 shows the relevant extracts from the Ant build file.

Example 6-4. Ant Build File


   <!-- Setup xdoclet classpath -->
<path id="project.class.path">
    <fileset dir="${libs.dir}/xdoclet-1.2">
        <include name="*.jar"/>
    </fileset>
    <pathelement location="${j2ee.lib}"/>
</path>

<!-- Define the ejbdoclet task -->
<taskdef name="ejbdoclet"
            classname="xdoclet.modules.ejb.EjbDocletTask">
    <classpath refid="project.class.path"/>
</taskdef>

<!-- Invoke xdoclet compilation -->
<target name="generate">
    <ejbdoclet destdir="gen-src"
               ejbspec="2.0">

        <!-- Source files to be processed by xdoclet -->
        <fileset dir="src">
            <include name="**/*Bean.java"/>
        </fileset>

        <!-- Code generation options -->
        <remoteinterface pattern="{0}Remote"/>
        <homeinterface/>
        <localinterface/>
        <localhomeinterface/>
        <utilobject cacheHomes="true"
                    includeGUID="true"
                    kind="physical"/>

        <!-- Generated deployment descriptors location -->
        <deploymentdescriptor destdir="${ejb.dd.dir}"/>

        <!-- Container specific -->
        <weblogic destdir="${ejb.dd.dir}"
                    xmlencoding="UTF-8"
                    validatexml="true"/>
    </ejbdoclet>
</target>

The comments in the build file highlight the various steps necessary for setting up and running the doclet engine. Next, we go over each step in more detail.

Setup the XDoclet Classpath

As with any Java program, the classpath must be configured to point to all the libraries the running application requires. The <path> tag builds up a classpath that includes all of the XDoclet libraries and the EJB library:

<path id="project.class.path">
    <fileset dir="${libs.dir}/xdoclet-1.2">
        <include name="*.jar"/>
    </fileset>
    <pathelement location="${j2ee.lib}"/>
</path>

The <fileset> tag provides a convenient shorthand for adding all of the libraries in the XDoclet directory to the classpath without having to specify each individual library. The locations of the various libraries are defined with Ant properties, which are set up elsewhere in the build file. The use of properties is considered good practice for Ant build files because it allows the build file to be tailored for different environments.

Define the XDoclet EJB Task

Ant needs to know what to do when it encounters the <ejbdoclet> tag. The <taskdef> task tells Ant where it can locate the class that will handle the <ejbdoclet> tag on behalf of Ant:

<taskdef name="ejbdoclet"
            classname="xdoclet.modules.ejb.EjbDocletTask">
    <classpath refid="project.class.path"/>
</taskdef>

Attributes for the task specify the name of the new tag and the implementing XDoclet class. The classpath established earlier gives directions to the libraries required by the <ejbdoclet> task.

Invoke XDoclet from Ant

The <ejbdoclet> task initiates XDoclet, providing all the configuration details the doclet engine requires in order to generate code from the Java source files.

We use this task to tell XDoclet the location of the destination directory for all generated code and the EJB version to be supported. Taken from the example, we have the following:

<ejbdoclet destdir="gen-src"
           ejbspec="2.0">

The destdir attribute specifies the location for all source generated by XDoclet, while the EJB version is specified with the ejbspec attribute.

The next step is to supply XDoclet with the location of all source code to be parsed. This is achieved with the <fileset> task, as shown below:

<fileset dir="src">
    <include name="**/*Bean.java"/>
</fileset>

The <fileset> task submits a list of all files for processing to XDoclet. For the example, all source resides in the src directory, and we've further informed XDoclet we are only interested in files with a filename that matches the *Bean.java pattern.

The ability to specify different directories for source and generated output is critical to good housekeeping, as it keeps the source that is produced by XDoclet distinct from code managed by hand. This separation lessens the likelihood of a developer inadvertently changing generated code, which would result in any changes being lost once the build process was rerun. Moreover, the separation of the two code types also enables clean operations to be implemented more easily, as all code under the gen-src directory can safely be deleted.

The next elements determine just what the <ejbdoclet> task is to generate from the source it parses. In this case, we produce remote, home, and local interfaces as well as a deployment descriptor and helper class for the enterprise bean. This is achieved with elements nested inside the <ejbdoclet> task as follows:

<remoteinterface pattern="{0}Remote"/>
<homeinterface/>
<localinterface/>
<localhomeinterface/>
<utilobject cacheHomes="true"
            includeGUID="true"
            kind="physical"/>
<deploymentdescriptor destdir="${ejb.dd.dir}"/>

Additional instructions can be passed to the doclet engine by specifying attributes for the nested elements. For example, with the <remoteinterface> tag, we specify that the word Remote be appended to the end of the remote interface name.

For the deployment descriptor, we request that it be generated to a different directory than that of the other generated code. Typically, deployment descriptors are generated directly into the target build directory to simplify the packaging of the enterprise bean later in the build process.

The final element in the example is vendor-specific and generates a deployment descriptor proprietary to BEA WebLogic Server:

<weblogic destdir="${ejb.dd.dir}"
          xmlencoding="UTF-8"
          validatexml="true"/>

XDoclet is not shackled to a single J2EE vendor and provides support for generating deployment descriptors for many of the different application servers currently available. The use of these elements makes it easy to target multiple vendor application servers by including elements for each server within the <ejbdoclet> task. Refer to the XDoclet documentation for a complete list of all the application servers supported.

With the build file created, we are nearly all set to start generating code for our session bean. All that is needed is a Java file complete with attributes.

Creating a Session Bean

To begin building our enterprise bean, we must first write the implementation for the session bean and add the various XDoclet attributes as Javadoc tags. Listing 6-5 shows the source for a basic Customer session bean, complete with XDoclet attributes.

Example 6-5. Session Bean with XDoclet Attributes

// CustomerServiceBean.java

package customer;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

/**
 * @ejb.bean
 *  name="CustomerService"
 *  jndi-name="CustomerServiceBean"
 *  type="Stateless"
 *
 * @ejb.resource-ref
 *  res-ref-name="jdbc/CustomerDataSource"
 *  res-type="javax.sql.Datasource"
 *  res-auth="Container"
 *
 * @weblogic.resource-description
 *  res-ref-name="jdbc/CustomerDataSource"
 *  jndi-name="CustomerDS"
 *
**/
public abstract class CustomerServiceBean
  implements SessionBean {

  /**
   * @ejb.interface-method tview-type="both"
   */
  public void createCustomer(CustomerVO customer) {
  }

  /**
   * @ejb.interface-method tview-type="both"
   */
  public void updateCustomer(CustomerVO customer) {
  }

  /**
   * @ejb.interface-method tview-type="both"
   */
  public CustomerVO getCustomer(int customerID) {
    return new CustomerVO();
  }

} // CustomerServiceBean

The code in Listing 6-5 is a very minimal implementation of a session bean. However, from this one source file, all the code necessary to assemble a complete enterprise bean can be generated. From this example, the following file types are produced:

  • ejb-jar.xml deployment descriptor
  • weblogic-ejb-jar.xml proprietary deployment descriptor
  • Home, remote, and local interfaces for the enterprise bean
  • Helper class for accessing the enterprise bean

Producing all of these files by hand is a slow, tedious, and error-prone process. XDoclet does all of the grunt work for us with the help of a few carefully placed attributes in the bean class.

Declaring XDoclet Attributes

The XDoclet attributes masquerade as Javadoc tags. They take the form of a namespace followed by a tag name located within the namespace scope. Properties of the tag are passed in as named arguments. Here is the format of an XDoclet tag:

@namespace.tag name="value" name2="value"

Within the code of the bean, XDoclet tags are embedded at the class and method levels. Each tag augments the information already defined in the Java. The doclet engine does not simply parse the file, looking for tags and ignoring the code. Instead, where XDoclet encounters a tag, it uses the Java Doclet API to retrieve information on the code annotated by the tag. All of this information, both tag and source, is used in the code generation process.

Class-Level Tags

The class-level @ejb.bean tag gives the bean a name, the JNDI lookup name, an optional display name, and a type. For the example, a type of stateless has been defined for a stateless session bean. Here is how this information is expressed with XDoclet tags:

@ejb.bean name="CustomerService"
  jndi-name="CustomerServiceBean"
  type="Stateless"

The example also has two further tags at the class level: @ejb.resource-ref and @weblogic.resource-description. Each of these tags defines a resource; in the example, a data source has been defined. The output from each tag is output directly to the deployment descriptors. The tag with the namespace @weblogic is a proprietary tag and results in the details of the data source being written to the weblogic-ejb.xml deployment descriptor. Equally, other proprietary tags can be used here to support alternative J2EE vendors.

XDoclet supports a comprehensive range of tags and allows a complete deployment descriptor to be specified entirely within the code as attributes. For the full list of tags, refer to the XDoclet documentation.

Method-Level Tags

Method-level tags give fine-grained control for each method. The example illustrates the use of the @ejb.interface-method to tell the doclet engine whether the method is to be part of the bean's remote or local interface. The options available are remote, local, or both. Wanting to generate as much code as possible from the example, I have specified both, which as the name implies sees the method added to each interface type.

With the build file created and source file suitably adorned with attributes, all that remains is to execute the build file and examine the output.

Inspecting the Output

Issuing ant generate from the command line unleashes XDoclet upon the source, and the result is all the files necessary to assemble a complete session bean. Table 6-2 lists the files created by XDoclet.

Table 6-2. XDoclet Generated Files for the CustomerService Session Bean

Name

Description

ejb-jar.xml

EJB deployment descriptor

weblogic-ejb-jar.xml

Deployment descriptor for BEA WebLogic Server

CustomerServiceHome.java

Home interface

CustomerServiceLocal.java

Local interface

CustomerServiceLocalHome.java

Home for local interface

CustomerServiceRemote.java

Remote interface

CustomerServiceUtil.java

Helper class for accessing the session bean

The list in Table 6-2 illustrates the amount of baggage associated with a single enterprise bean. Each file is related to and must be kept in sync with the originating bean class. A change in the bean class must be reflected across all of the different interfaces and deployment descriptors. Performing this task manually is monotonous, time consuming, and subject to error.

The tag-like attributes of the XDoclet engine enable all of these files to be generated from a single source. A change to the bean class can be replicated out to all files associated with the enterprise bean by running the XDoclet engine.

XDoclet is an active code generator, and consequently, the output of the doclet engine can be considered disposable. The generation of all source files by XDoclet should be made part of the build process. In this way, the bean class, deployment descriptors, and EJB interfaces are kept in sync.

Discrepancies in these files can often be hard to detect. The relationship between a remote interface and the implementing bean class is not enforced by the compiler. This relationship is defined by configuration parameters in the enterprise bean's deployment descriptor. Errors in configuration-based relationships are difficult to detect, as they require runtime tests to determine any fault. The use of a code generator in this instance removes the possibility of such time-consuming errors occurring.

Let's examine what has been generated from our solitary bean class. Listing 6-6 shows an extract from the ejb-jar.xml for the session bean. As can be seen, all the pertinent information from the bean class has been extracted by the doclet engine and defined in the EJB deployment descriptor.

Example 6-6. Generated ejb-jar.xml

<!-- Session Beans -->
<session >
  <description><![CDATA[]]></description>

  <ejb-name>CustomerService</ejb-name>

  <home>customer.CustomerServiceHome</home>
  <remote>customer.CustomerServiceRemote</remote>
  <local-home>customer.CustomerServiceLocalHome</local-home>
  <local>customer.CustomerServiceLocal</local>
  <ejb-class>customer.CustomerServiceBean</ejb-class>
  <session-type>Stateless</session-type>
  <transaction-type>Container</transaction-type>

  <resource-ref >
    <res-ref-name>jdbc/CustomerDataSource</res-ref-name>
    <res-type>javax.sql.Datasource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

</session>

The bean class defines the vendor-specific tag, @weblogic.resource-description at the class level. Output from this tag is proprietary to WebLogic Server and is written to the WebLogic deployment descriptor, weblogic-ejb-jar.xml. Listing 6-7 contains an extract from the deployment descriptor. The information generated by the @weblogic.resource-description tag is represented in the deployment descriptor by the element <resource-description/>.

Example 6-7. Generated weblogic-ejb-jar.xml

<weblogic-enterprise-bean>
  <ejb-name>CustomerService</ejb-name>
  <stateless-session-descriptor>
  </stateless-session-descriptor>
  <reference-descriptor>
    <resource-description>
      <res-ref-name>jdbc/CustomerDataSource</res-ref-name>
      <jndi-name>CustomerDS</jndi-name>
    </resource-description>
  </reference-descriptor>
  <jndi-name>CustomerServiceBean</jndi-name>
  <local-jndi-name>CustomerServiceLocal</local-jndi-name>
</weblogic-enterprise-bean>

A useful tool for viewing the different Java classes and interfaces generated by XDoclet, and indeed any code generator, is a modeling tool with reverse-engineering capabilities.

Figure 6-2 illustrates a class diagram produced using Borland's Together ControlCenter and displays all the classes generated for the enterprise bean that are contained by the customer package. The diagram emphasizes the absence of any relationships between the originating bean class and the generated classes. These relationships are defined within the EJB deployment descriptors and so are not covered by the UML notation.

06fig02.gif

Figure 6-2 Class diagram for the CustomerServiceBean-generated class.

You may find reverse engineering very helpful when working with generated code. After running the code generator, the modeling tool can display what new classes have been injected into the model by the generator and how they impact the existing design model.

Our example has reached the point where it can be compiled and packaged as an enterprise bean. In getting to this point, a sizeable amount of code was generated for what is a very simple session bean with a minimum set of XDoclet tags. Now that we know how to generate the code, the next question is how we manage the code generated.

  • + Share This
  • 🔖 Save To Your Account