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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020