JAXB-based Ant custom task

Source: Internet
Author: User


Official Manual Link: http://ant.apache.org/manual/index.html


The basic concepts of Ant, XSD, JAXB, and XML are not introduced here, there is a lot of random search on the Internet, this article mainly explains the use of XSD generation JAXB class to customize Ant Task, automatically complete the parsing work of XML, improve the development efficiency.


Development tools take eclipse.


The first step is to create a Java project in Eclipse, named Writinganttaskdemo.


The second step is to create the XSD file, where I created the file named Mytaskconfig.xsd under the Jet.demo.xsd package in the project.

The following is the source configuration information for this XSD (the graphical interface in design, which is not here):

<?xml version= "1.0" encoding= "UTF-8"? ><schema xmlns= "Http://www.w3.org/2001/XMLSchema" targetnamespace= " Http://www.example.org/patternConfig "<span style=" White-space:pre "></span>xmlns:tns="/HTTP/ Www.example.org/patternConfig "elementformdefault=" qualified ">    <complextype name=" Mytaskconfig " >    <span style= "White-space:pre" ></span><sequence>    <span style= " White-space:pre "></span><element name=" message "type=" Tns:message "maxoccurs=" unbounded "    <span style= "White-space:pre" ></span>minoccurs= "0" >    <span style= "White-space:pre" ></span></element>    <span style= "White-space:pre" ></span><element name= " Description "type=" tns:description "    <span style=" White-space:pre "></span>maxoccurs=" 1 " minoccurs= "0" >    <span style= "White-space:pre" ></span></element>  &nbsp <span style= "White-space:pre" ></span></sequence>    <span style= "White-space:pre" ></span><attribute name= "id" type= "string" ></attribute>    </complexType>     <element name= "Mytaskconfig" type= "Tns:mytaskconfig" ></element>    < ComplexType name= "Message" >    <span style= "White-space:pre" ></span><attribute name= "id "Type=" string "></attribute>    <span style=" White-space:pre "></span><attribute Name= "Content" type= "string" ></attribute>    </complexType>        <complextype name= "Description" >    <span style= "White-space:pre" ></span>< Attribute name= "id" type= "string" ></attribute>    <span style= "White-space:pre" ></span ><attribute name= "Content" type= "string" ></attribute>    &LT;/COMPLEXTYPE&GT;</schema> 

The root element is an id attribute in Mytaskconfig,mytaskconfig, with a number of message child elements, with two attributes in the message child element, namely ID and content. The Mytaskconfig also has 0 or 1 description elements, which have the same attributes as a message.


third , using XSD to generate the Jaxb class, first create a package named Jet.demo.model in the project, which will be used to store the generated JAXB class. Right click on the mytaskconfig.xsd file, select Generate->jaxb Classes ....

Select the Writinganttaskdemo project, select the Jet.demo.model pack in the package, then keep next, and finally finish on the line, this time pop up a warning box, such as:


This is to remind us that the generated class file will overwrite the existing file and ask us if we are sure to do so, here we choose Yes, otherwise it cannot be generated. Or just put the box again on the Tick, solve everything, but I don't recommend it, because sometimes it's bad to do it by mistake.

Next, all class files configured in the XSD are generated in the Jet.demo.model package, and the following is the output information for the console console:

Parsing a schema ...
Compiling a schema ...
Jet\demo\model\description.java
Jet\demo\model\message.java
Jet\demo\model\mytaskconfig.java
Jet\demo\model\objectfactory.java
Jet\demo\model\package-info.java

Messge.java is the message child element in the preceding XSD, and Mytaskconfig is the mytaskconfig root element in the preceding XSD. Here Objectfactory.java and Package-info.java We do not need, here too much introduction, want to know the netizen himself to watch.

Message.java

This file is generated by the JAVATM Architecture for XML Binding (JAXB) Reference Implementation, V2.2.4-2//See &L T;a href= "HTTP://JAVA.SUN.COM/XML/JAXB" >http://java.sun.com/xml/jaxb</a>//any modifications to the this file Would be lost upon recompilation of the source schema. Generated on:2016.04.12 at 10:14:00 AM CST//package jet.demo.model;import javax.xml.bind.annotation.XmlAccessType; Import Javax.xml.bind.annotation.xmlaccessortype;import Javax.xml.bind.annotation.xmlattribute;import javax.xml.bind.annotation.xmltype;/** * <p>java class for Message complex type. * * <p>the following schema fragment specifies the expected content contained within this class. * * <pre> * <complextype name= "Message" > * <complexContent> * <restriction base= "{HTTP://WWW.W       3.org/2001/xmlschema}anytype "> * <attribute name=" id "type=" {http://www.w3.org/2001/xmlschema}string "/> * <attribute name= "Content" Type= "{http://www.W3.org/2001/xmlschema}string "/> * </restriction> * </complexContent> * </complexType> * </p  re> * * */@XmlAccessorType (Xmlaccesstype.field) @XmlType (name = "message") public class Message {@XmlAttribute (name    = "id") protected String ID;    @XmlAttribute (name = "Content") protected String content;     /** * Gets The value of the ID property.        * * @return * Possible object is * {@link string} * */public String getId () {    return ID;     }/** * Sets the value of the ID property. * * @param value * Allowed object is * {@link string} * */public void SetId (string    Value) {this.id = value;     }/** * Gets The value of the content property.        * * @return * Possible object is * {@link string} * */public String getcontent () {    return content; }/** * Sets the value of the content PropeRty. * * @param value * Allowed object is * {@link String} * */public void setcontent (St    Ring value) {this.content = value; }}

In Ant Manual, the writing tasks in the Developing with Apache ant section have an introduction to attributes:

It is very easy-for each attribute provide a public void set <attributename> ( <type> newvalue) method and Ant would do the res T via reflection.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

This means that each property should provide a set method.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

There are only two attributes in the message child element, and the set and get methods have been automatically generated in the Jaxb class, so we don't need any modification.

Description is the same as the message, it is not copied here.

Writing tasks has an introduction to child elements (http://ant.apache.org/manual/develop.html#nested-elements):

Now there's a class NestedElement that's supposed to being used for your nested <inner> elements and you have three options:

    1. public NestedElement createInner()
    2. public void addInner(NestedElement anInner)
    3. public void addConfiguredInner(NestedElement anInner)

What's the difference?

Option 1 makes the task create NestedElement the instance of, there is no restrictions on the type. For the options 2 and 3, Ant have to create a instance of NestedInner before it can pass it to the task, this means, NestedInner must There is a public No-arg constructor or a public One-arg constructor taking a Project class as a parameter. The only difference between options 1 and 2.

The difference between 2 and 3 are what Ant have done to the object before it passes it to the method. Would addInner receive an object directly after the constructor have been called, while addConfiguredInner gets the object after th e attributes and nested children for this new object has been handled.

What happens if do I more than one of the options? Only one of the methods would be called, but we don't know which, this depends on the implementation of your Java virtual m Achine.


--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

The approximate meaning is that for embedded elements, there are three options, create method, add method, Addconfigured method.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

Three methods are not in the JAXB class, so we need to add, here I choose the Add method, this method is the simplest .... As follows:

Added by hand, for the purpose of ant script running.public void addmessage (Message message) {list<message> Messa Gelist = GetMessage (); messagelist.add (message);} public void Adddescription (Description Description) {this.description = Description;} End of adding.

For a single child element, you can assign a value directly. For the child elements of the list type, the method to add is used.

Modified Mytaskconfig.java

This file is generated by the JAVATM Architecture for XML Binding (JAXB) Reference Implementation, V2.2.4-2//See &L T;a href= "HTTP://JAVA.SUN.COM/XML/JAXB" >http://java.sun.com/xml/jaxb</a>//any modifications to the this file Would be lost upon recompilation of the source schema. Generated on:2016.04.12 at 10:37:45 AM CST//package jet.demo.model;import java.util.arraylist;import java.util.List; Import Javax.xml.bind.annotation.xmlaccesstype;import Javax.xml.bind.annotation.xmlaccessortype;import Javax.xml.bind.annotation.xmlattribute;import Javax.xml.bind.annotation.xmlelement;import javax.xml.bind.annotation.xmltype;/** * <p>java class for mytaskconfig complex type. * * <p>the following schema fragment specifies the expected content contained within this class. * * <pre> * <complextype name= "Mytaskconfig" > * <complexContent> * <restriction base= "{/HTTP/ Www.w3.org/2001/xmlschema}anytype "> * <sequence> * &ltElement name= "message" type= "{http://www.example.org/patternconfig}message" maxoccurs= "unbounded" minoccurs= "0"/ > * <element name= "description" type= "{http://www.example.org/patternconfig}description"/> * </s equence> * <attribute name= "id" type= "{http://www.w3.org/2001/xmlschema}string"/> * &LT;/RESTRICTION&G T * </complexContent> * </complexType> * </pre> * * * * @XmlAccessorType (Xmlaccesstype.field) @XmlType (NA me = "Mytaskconfig", Proporder = {"Message", "description"}) public class Mytaskconfig {protected List<messag    E> message;    @XmlElement (required = true) protected Description Description;    @XmlAttribute (name = "id") protected String ID; Added by hand, for the purpose of ant script running.public void addmessage (Message message) {list<message> Messa Gelist = GetMessage (); messagelist.add (message);} public void Adddescription (Description Description) {this.description = Description;}//End of adding.     /** * Gets The value of the message property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot.     Therefore any modification the * returned list would be is present inside the JAXB object.     * This is why there are not a <CODE>set</CODE> method for the message property. * * <p> * For example, to add a new item, do as follows: * <pre> * GetMessage (). Add (Newite     m); * </pre> * * * <p> * Objects of the following type (s) is allowed in the list * {@link M essage} * * * * public list<message> getMessage () {if (Message = = null) {MESSAG        E = new arraylist<message> ();    } return this.message;     }/** * Gets The value of the Description property. * * @return * Possible object is * {@link Description} * */PubliC Description getdescription () {return Description;     }/** * Sets the value of the Description property. * * @param value * Allowed object is * {@link Description} * */public void SETDESCR    Iption (Description value) {this.description = value;     }/** * Gets The value of the ID property.        * * @return * Possible object is * {@link string} * */public String getId () {    return ID;     }/** * Sets the value of the ID property. * * @param value * Allowed object is * {@link string} * */public void SetId (string    Value) {this.id = value; }}

Fourth Step, write your own task.

First import the Ant's Jar package in the project: Ant.jar and Ant-launcher.jar. Then create a new MyTask class under the Jet.demo.task package, inheriting the ant's Torg.apache.tools.ant.Task class.

Mytask.java

Package Jet.demo.task;import Java.util.list;import Jet.demo.model.description;import jet.demo.model.message;import Jet.demo.model.mytaskconfig;import Org.apache.tools.ant.buildexception;import Org.apache.tools.ant.Task;public Class MyTask extends Task {private mytaskconfig mytaskconfig;public void Addmytaskconfig (Mytaskconfig mytaskconfig) {thi S.mytaskconfig = Mytaskconfig;} @Overridepublic void Execute () throws Buildexception {//show Message listlist<message> messagelist = mytaskconfig. GetMessage (); if (messagelist! = null) {for (message message:messagelist) {Show ("message", Message.getid (), message.getc Ontent ());}} Show Descriptiondescription description = Mytaskconfig.getdescription (); if (description! = null) {Show ("description" , Description.getid (), description.getcontent ());}}  Show information of Elementprivate void Show (string type, string ID, string content) {System.out.println ("type=" + type + ", id=" + ID + ", content=" + content);}}

Where mytaskconfig is our root element, we also need to add the addition method, execute is the method that ant's task executes, we can overload this method, realize our function. This is just to print all the message and description information.


Fifth Step , write the ant script. Create an ant script under the Jet.demo.script package named Mytask.xml.

<?xml version= "1.0" encoding= "UTF-8"? ><project name= "Writinganttaskdemo" default= "Thetarget" >< Target Name= "thetarget" ><echo message= "Begin to run the target ..."/><taskdef name= "MyTask" Classname= " Jet.demo.task.MyTask "></taskdef><mytask><mytaskconfig><message id=" MESG1 "content=" this Is message one. "/><message id=" MESG2 "content=" the "is Message", "/><message id=" MESG3 "content=" This is M Essage thress. "/><description id=" Descone "content=" This is my description. "/></mytaskconfig></ Mytask></target></project>

Here project is named "Writinganttaskdemo", and the default execution target is "thetarget". A target named "Thetarget" has been created in project as the default execution target for project.


In target, first use echo to output a word, indicating that targe started execution.


Then it is configuring our own defined task, using the taskdef tag, name named Mytask,classname, which represents the class name of our custom task, here is jet.demo.task.MyTask.


This is the definition of our parameter information, "MyTask" is corresponding to the name in the Taskdef. Inside there is a mytaskconfig,mytaskconfig with three message and one description.


OK, so the next step is to execute the ant script.


Sixth step , execute the ant script.

In the Eclipse menu bar, choose Run--> Run configurations--> to create a Java Applicatio.

The name here is Mytask,project select Writinganttaskdeml,main class is set to Org.apache.tools.ant.Main.

Arguments is set to-F "E:\workplace_smart_luna\WritingAntTaskDemo\src\jet\demo\script\MyTask.xml", and F is the path of the ant script we wrote earlier , this one needs to be modified by itself.



Select Apply, and then run. This time you can control the output of the console:

Buildfile:e:\workplace_smart_luna\writinganttaskdemo\src\jet\demo\script\mytask.xmlthetarget:     [echo] Begin To run the target ...   [MyTask] type=message,id=mesg1,content=this is message one.   [MyTask] type=message,id=mesg2,content=this is message.   [MyTask] type=message,id=mesg3,content=this is message thress.   [MyTask] Type=description,id=descone,content=this is my description. BUILD successfultotal time:0 seconds

Done.


Summarize

This article explains how to use the JAXB class to read a custom ant task in a way that reads the XML format from the definition to directly generate the Property object.

The advantage of creating an XSD first as an XML schema is that it is easy to modify later and looks intuitive.

The Jaxb class is then generated via XSD, and the properties for ant are modified slightly to the JAXB class, adding the Add method.

Then you write your own task class, and you need to inherit the ant's Org.apache.tools.ant.Task class to implement your own Execute method.

Then write the ant build script to configure the XML information.

The last is to run the ant script.


Source:

Https://github.com/siyueshiqi/JetDemos



JAXB-based Ant custom task

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.