Reduce code expansion with xdoclet [Pick]

xiaoxiao2021-03-06  13

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 = " form"

* /

Public class form extends actionform {

Private

Public () {

Return

}

Public void ( value) {

= value;

}

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"%>

>>

TAGNAME = "dw.genstruts" paramname = "formlabel" />

Size = "

"/>

Submit

RESET

Note that the code value specified in the XDoclet tag in the original addressBean.java code is obtained in the code in . When you perform the GenStruts Ant target, the GenFormJsp.xDT template displayed by Listing 5 is also handled. You can find the generated addressBeanForm.jsp file in the generated subdirectory, check the contents of the file, you can see the replacement of the template.

Example, but first ... To test the template code generation in this example, you need to install and test the ANT and XDoclets. The code in this article is all based on ANT 1.5.4 and XDoclet 1.2.1. To generate all artifacts, and test the generated web application, you also need to install Hibernate, Struts, and Application Server, and you need to access the relational database. Example is based on Hibernate 2.1.4, Struts 1.1, and Servlet 2.3. See Resources for more information on these technologies. Be sure to read the ReadMe file I provide with the source code. Generate other workpieces You can generate any text-based output with an xdoclet. I use the XDoclet to generate Java code, JSP page, XML file, configuration file, and other more outputs using the XDoclet. It creates a complete data portal web application from a simple Java source file that tagged with xdoclet. To do this, it performs the XDoclet's built-in template (located in the JAR file, called module), generates: Struts configuration and support files. Hibernate configuration and support files. The deployment descriptor (Web.xml) of the web application. Table 1 shows all files generated for the sample application (typically referred to as artifact): Table 1. Workpool generated by xdoclets for addressBean.java

The generated workpiece description position addressBeanForm.javajava source file, contains a form bean class, using the generated directory AddressBeanForm.jspjSP form in Struts, with the Struts tag library Accept user address Enter the JSP directory AddressBeanAction.javastruts action class, accept the input value, Save the value to the relational database generated directory addressBean.hbm.xmlhibernate mapping file, mapping Web / Classes directory DWSCHEMA.SQLRDBMS table architecture in the AddressBean Java object and database, used to use the architecture of the AddressBean object Examples Permanent SQL Directory Hibernate.cfg.xmlhibernate runtime Profile Web / Classes Directory Web Application Descriptor Web Directory Struts-Config.xmlstruts Frame The configuration file Web directory in this article You know more about the generation of the first workpiece in the two artifacts listed in Table 1, and understand the templates that generate them in deep understanding. Workpiece AddDressBeanAction.java uses a similar method to generate templates called GenAction.xdt. XDoclets have built-in templates and label processors that can generate other workpieces in Table 1. Table 2 lists the ANT targets and ANT tasks corresponding to each generated workpiece. You can perform each Ant target in the table to generate a corresponding workpiece. All of these generated workpieces plus the original and addressBean.java, together forms an example web application. You will also find the default Ant target called ALL, which will do anything, including establish WAR to the application (web archive that can be deployed). Before working, you must read the Readme.txt file in the code release package.

The merge points in the XDoclet are in the xdoclet documentation, you will see the merge point (Merge file) very frequently. The merge file is a text file, you can merge it into the specified location of the xdoclet generating code - "consolidated points" (specified by the template). You can use a merged file to include static text (eg, code snippet and XML pieces), which may be difficult or unable to generate with xDoclet. For example, in the Merge / Web Directory of the sample code, you will find the struts-action.xml file. During the code generation, you can use this file to merge into the Struts action map, which constitutes a part of the generated struts-config.xml file. Ant and Ant task Ant target directory Ant task generated corresponding to the work table 2. The workpiece genstrutsxdoclet.DocletTaskAddressBeanForm.javagenstrutsxdoclet.DocletTaskAddressBeanForm.jspgenstrutsxdoclet.DocletTaskAddressBeanAction.javagenerateHIBxdoclet.modules.hibernate.HibernateDocletTaskAddressBean.hbm.xmlgenerateHIBxdoclet.modules.hibernate.HibernateDocletTaskhibernate.cfg. xmlcreateDDLxdoclet.modules.hibernate.HibernateDocletTaskdwschema.sqlgenerateDDxdoclet.modules.web.WebDocletTaskweb.xmlgenerateDDxdoclet.modules.web.WebDocletTaskstruts-config.xml Conclusion XDoclet is a useful, intelligent code generator, you can perform many everyday Java automatically use it Develop tasks. Don't be scared by the complex surface of it. With the gradual proficient in xDoclet (and related APACHE ANT), you will save your precious time and get several times rewards in future development work. Reference

You can see this article in our website on our world. Click the Code icon at the top or bottom of this article (or see the Download Site), download the Java code, xdoclet template, and Ant script used in this example. On the official open source site, learn more about xDoclet, which provides the latest source code, download, document, FAQ, and mailing list. Download the latest version of Apache Ant generation management and automation. Access the official Hibernate site to get the latest version of Hibernate persistence, documentation, mailing list, and community news. See the latest version of the Struts MVC framework. "Writing your own Secret Santa Web application, Part 1: Bean" (DevelOperWorks, December 2003) shows how XDoclet can accelerate the development and deployment of J2EE applications. The tutorial "USE XDoclet to Generate Web Service Support Files" (June 2003) shows the J2EE developers how to use XDoclet to write their own custom templates and subtutaneous tasks. The tutorial "Enhance J2EE Component Reuse with XDoclet" (May 2003) shows the J2EE developers how to use XDoclet to increase development speed. To use an open source application service for the examples of this article, you can try Tomcat 5 servers. Explore another easy-to-use template language, please refer to Sing Li's article "Using Velocity to implement Client and Server Templates" (DeveloperWorks, February 2004). The author of XDoclet In Action (Independent Pub Group; 2003) is Walls and Richards, which is a complete resource generated by XDoclet code. To learn from the new metadata function in Java 5, see "Note in Tiger, Part 1: Adding metadata to Java code" and "Note in Tiger, Part 2: Custom Note" (DeveloperWorks, 2004 9 month). In the developerWorks Java technology area, hundreds of Java technology resources can be found. Please visit developer bookstore to get a complete list of technical books, including hundreds of Java-related topics books. Download Name

Size

Download Method

J-Doclet-code.zip

FTP

About the author Sing Li is the author of many other books published by ProFessional Apache Tomcat 5, Pro JSP, Third Edition, Early Adopter Jxta, Professional JINI, and Wrox Press. He is a regular contributor to the technical magazine, or the enthusiastic communication of P2P development. Sing is a consultant and senior author, you can contact him through his email westmakaha@yahoo.com.

转载请注明原文地址:https://www.9cbs.com/read-67630.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.041, SQL: 9