Article Source:
Http://www-900.ibm.com/developerWorks/cn/java/J-DOCLET/index.shtml
Reduce code expansion with xDoclet
content:
Smart Code Builder In-depth XDoclet Use XDoclet Conclusion Reference Download About Authors' Evaluation
related information:
Write your own Secret Santa Web Apps, Part 1: Bean Use XDoclet to Generate Web Service Support Filesenhance J2EE Component Reuse with xdocletibm Developer Kits for the Java Platform (Downloads)
subscription:
DeveloperWorks News DeveloperWorks Subscribe (Subscribe CD and Download)
Discover multi-function template-driven code generator
Level: primary
Sing Li
(Westmakaha@yahoo.com) Author, Wrox Press 2004 November
The XDoclet code generation engine for open source code is an indispensable component of many leading Java frameworks, often used as an attribute-oriented programming and continuously integrated engines. But XDoclets have some things that are not very eye-catching: It is too difficult to master for primary developers. In this article, popular authors Sing Li take XDoclet as objects, revealing its internal simple but elegant design, so that you can understand this technology and apply it in practice.
XDoclets can easily become a more universal cross-technical code generation tool in your Java programming toolbox. Unfortunately, developers often ignore the general purpose of xDoclets, only use it in a large development framework or IDE, it is used as one of the hidden elements. It is often considered that it is difficult to apply XDoclet to custom solutions. The purpose of this article is to eliminate this confusion, free XDoclet from a common complex trap, and show you how to use this code generation engine. I will use an actual example to demonstrate the use of xdoclets, which will receive a Pojo (Plain Old Java Object) and generate full files for complete web applications with XDoclets, which are required to input the data input relationship database. This example uses XDoclet's custom template code generation features, as well as internal support for Hibernate object relationship mapping tools, Struct web application frameworks, and application servers. (See Referring). The core function of the smart code generator xDoclet is based on the following combination (or generate other configuration / data files):
Java source files for special tags. A predefined template. The xdoclet has the following unique advantages compared to other template-based code generation techniques (such as Velocity; see Resources).
XDoclets are closely integrated with Apache Ant (see Resources) to provide highly automated operations. The xdoclet tag processing of the control code generation and template is embedded in the Java source code file as an inline comment. This eliminates the need for multiple related files and control files. XDoclet's built-in Java parser uses its in-depth understanding of the Java code structure, establishes internal structural models for the input Java code. This structural model is often called metadata because it contains data related to the associated code. The xdoclet template generated logic has full access to the internal structure model of the input Java code. Next, I will further study how XDoclet works to help you understand these features. XDoclet operation Figure 1 shows the input and generated output of the xDoclet. Figure 1. XDoclet black box You can see that the Java source code containing the embedded xdoclet tag is the system's input. Under the drive of Apache Ant, the XDoclet handles the input code, the generated output text file can be a Java source code, HTML page, XML file, etc. To handle input, xDoclets need to use templates (saved in .xdt files) and label processors (encoded with Java). XDoclet packs templates and tag processors into "modules", different "modules" processing different problem domains. The XDoclet generated structural model XDoclet parsed the input Java source code containing the embedded xdoclet tag, and establishes a very detailed structure model for the code. Each element in the structural model represents a Java structure in the source code. The structural model shown in Figure 2 reveals the XDoclet tracked code constructors and relationships. Figure 2. The internal structure model of the XDoclets of the Java source code is a code constructor such as the structural model trace class, an interface, method in FIG. 2. The model also tracks the relationship between elements, such as inheritance and interface implementation. Embedding the xdoclet tag in the source code in the form of the inline note is parsed to the properties of the model element and is tracked.
The general Javadoc engine understands the smart code generating engine of the Java code structure model is not a new concept. In fact, it is a way of operation of Javadoc tools comes with JDK. By resolving Java source files with special Javadoc tags, the JavadoC tool can generate an HTML document for all Java programs (including classes, interfaces, fields, and methods) for all Java programs. Javadoc also has knowledge of special Java language concepts, such as inheritance, abstract classes, storage classes, and modifiers. The birth of XDoclets comes from such an observation: a universal version of Javadoc generated by any code, which will be extremely useful under many programming situations. However, the actual Javadoc source code is not designed for universal code, but just to generate an HTML document. The XDoclet development team will rewrite the engine from the header and significantly optimize its performance. In-depth XDoclet FIG. 3 shows the internal structure of the XDoclet reveals the function block that operates. Figure 3. The function block inside the xdoclet As shown in Figure 3, the Apache Ant controls the configuration and operation of the XDoclet when running. XDoclet parses the input Java source code and generates a structural model in memory. The template engine generates an output file by processing a set of templates and label processors. The template and label processor can be built-in or custom. During the code generation, the template and label processor has full access to the structural model. XDoclet fake complexity XDoclet is essentially a universal Javadoc engine (see the sidebar, the General Javadoc Engine). So, what makes it look so complicated? The answer is that xDoclets have never been discussed separately, but always hidden in many other complex technologies. Figure 4 shows the complex fog surrounding XDoclet (see why xDoclets look much more complicated than actual). Why xDoclet looks more than the actual multi-apache Ant automatically performs Java software generation process. Building management processes are usually part of more complex process in production projects. The terminology and concept of building management are integrated into the APCHE ANT and is a prerequisite for understanding its operation. Mature Ant scripts may be very complicated. Every new version of Ant will introduce some new features, which further adds complexity. This forms the complexity of the XDoclet surface because the xdoclet needs ANT to execute. The problem of xDoclet processing is another source of complexity. When publishing XDoclets, XDoclets have been integrated with EJB components, J2EE Web container integration, Hibernate persistence, Struts framework, Java management extension (JMX), etc. generate code. Each area in these issues has a large set of deli and concepts in this field. From these complex problems, there is often a discussion of xdoclets, which also increases the complexity of the XDoclet surface. It may be "I only see the forest, don't see the trees". Figure 4. Complex coupled coupling of XDoclets In Figure 4, you can see that XDoclet is closely related to the following:
Apache Ant, which controls the operation of xDoclets. XDoclet is existing as a set of Ant tasks, and no ANT is not executed. Some details of specific problems associated with generating files. The xdoclet itself is amazing and simple, as shown in the working code in the example below. Using XDoclet now, you can observe the actual work of xDoclet by studying the data entry application examples I provide to you. (To download the Java code used in this example, the xdoclet template, and Ant script, click the Code icon at the top or bottom of this article, or see the Download section.) We will start from the Java code shown in Checklist 1, this part The code represents the address of a customer. This address is encoded as a JavaBean component, where the xdoclet tag is displayed in black body: List 1. AddressBean.java source file for marked with xdoclet tag package com.ibm.dw.beans;
Import java.io.serializable;
/ **
* @ dw.genstrutsaction action = "/ addressdress.do"
* @ hibernate.class table = "address"
* /
Public class addressBean imports serializable {
Private string streetnumber = "";
Private string street = "";
Private string city = ""
Private String Country = "";
Private string postalcode = ""
Private long id = 0;
Public addressBean () {
}
/ **
* @ dw.genstruts forml = "street number"
* @ hibernate.property Length = "10"
* /
Public string getStreetNumber () {
Return streetnumber;
}
Public void setstreetNumber (String INPSTREETNUMBER) {
Streetnumber = INPSTREETNUMBER;
}
/ **
* @ dw.genstruts forml = "street"
* @ hibernate.property length = "40"
* /
Public string getStreet () {
Return street;
}
Public void setstreet (String INPSTREET) {
street = INPSTREET;
}
... more address bean printerties ......
/ **
* @ hibernate.id generator-class = "native"
* /
Public long getId ()
{
Return ID;
}
Public void setid (long inID) {
ID = InID;
}
}
In Listing 1, it is important to note that the XDoclet tag is to be embedded in the comment, tight in front of the related code element (such as a field, method, interface, or class). When parsing the source code, the xdoclet creates an attribute for each tag and attached the property to the code element of the structural model. Now, please pay attention to the @ dw.genstruts label because this is the first template that will be used in this example. Generate another Java class For this example, you need to generate a new Java class code - a Struts form bean. Struts will save and transfer user input with this bean. Bean must contain all data fields in the form of a bean property, and it must be subclasses of org.apache.struts.Action.ActionForm. In order to generate a form bean code, you will generate an xdoclet template according to the pseudo code shown in Listing 2. The black body in parentheses represents the text of the control flow logic and you want to replace. Note how the template extracts information from the structural model of the parsed Java source code file: Listing 2. Establish the pseudocode template for addressBeanform.java Struts form bean code package {package name of source class};
Import javax.servlet.http.httpservletRequest;
Import javax.servlet.http.httpservletResponse;
Import org.apache.struts.Action.actionform;
Import org.apache.struts.action.actionmapping;
Import org.apache.struts.upload.formfile;
/ **
* Form bean class for {name of source class} ;.
*
* @ Struts.form name = "{name of source class} form"
* /
Public class {name of source class} form extends actionform {
{loop through all the methods in the source class}
{if the method is a javabean "getter" method}
{if The method Has been marked with the @ dw.genstruts tag}
Private {return type of method} {name of the javabean property};
Public {return type of method} {name of the getter method for this property} () {
Return {Name of JavaBean property};
}
Public void {name of the setter method for this property}
{Return Type of Method} value) {
{Name of the javabean proteness} = value;
}
{end of @ dw.genstruts}
{end of if javabean getter}
{end of loop}
Establish an XDoclet tab with XDoclet Please note that the xdoclet @ struts.form label generated in the template of Listing 2. You can use XDoclet to generate an XDoclet tag in the Java source code, and the xdoclet will process these tags again in later operations. When Structs-config.xml is established later, XDoclet uses the @ Struts.Form tab. The code in the loop in Listing 2 generates a field declaration and an accessor method, and generates a setter method for each accessor method of each @ dw.genstruts tag in the input source code. Listing 2 uses an easy-to-understand pseudo code to represent template replacement tags. The actual XDoclet template tag is quite cumbersome. Listing 3 shows the GenFormBean.xdt template (all xdoclet templates are saved in the .xdt file). I have used the black body to emphasize the XDoclet template tag to facilitate the reference in pseudo code. Listing 3. Establishing a Structs Form Bean Java code Package
Import javax.servlet.http.httpservletRequest;
Import javax.servlet.http.httpservletResponse;
Import org.apache.struts.Action.actionform;
Import org.apache.struts.action.actionmapping;
Import org.apache.struts.upload.formfile;
/ **
* Form bean class for
*
* @ Struts.form name = "
* /
Public class
Private
Public
Return
}
Public void
}
Xdtmethod: ifhaasmethodtag>
Xdtmethod: ifisgetter>
Xdtmethod: forllmethods>
Familiar with the ANT script to write ANT scripts build.xml (I have provided this file as the sample code this article, see the link to find the code) Define all the necessary ANT targets used by the sample application. If you want to modify the script, you need to be familiar with Ant. See the reference information to learn more about Ant. You can refer to the XDoclet's "Template Language" document, find a list of all available tags available (see Resources). To run templates for the AddressBean.java source file, use the following ANT command line: Ant -dbase.class.java = address genstruts This command can perform custom Ant targets (see the sidebar familiar with ANT scripts) to process GenbeanForm. XDT template. The XDoclet provided by the ANT task called XDoclet.Doclettask, which is used to run the template file. If you are interested in the details of Ant, see the build.xml file in the sample code for more information. When the XDoclet handles the template, it generates an AddressBeanForm.java file under the subdites called Generated. Listing 4 shows the file, which contains all the texts replaced during template processing: Listing 4. XDoclet generated Java source code containing struts form bean
Package com.ibm.dw.beans;
Import javax.servlet.http.httpservletRequest;
Import javax.servlet.http.httpservletResponse;
Import org.apache.struts.Action.actionform;
Import org.apache.struts.action.actionmapping;
Import org.apache.struts.upload.formfile;
/ **
* Form bean class for addressbean.
*
* @ Struts.form name = "addressBeanForm"
* /
Public class addressBeanform Extends actionform {
Private java.lang.string streetnumber;
Public Java.lang.String getStreetNumber () {
Return streetnumber;
}
Public void setstreetNumber (java.lang.string value) {
streetnumber = value;
}
Private java.lang.stringstreet;
Public Java.lang.String getStreet () {
Return street;
}
Public void setStreet (java.lang.string value) {
street = value;
}
...... More bean property .....
}
Generating a JSP page for a data sheet You can use the same addressBean.java source file, but use the GenFormJsp.xdt template to generate a data entry form JSP page. Listing 5 shows GenFormJsp.xdt: Listing 5. Generate a JSP page using the Struts tag library to display the XDoclet template for HTML form
<% @ page language = "java"%>
<% @ Taglib Uri = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>
hEAD>