Data Binding objects from XML to Java code

Source: Internet
Author: User
Tags xslt

In the first part of this four-part series, we will find out what data binding is and what advantages it has compared to other methods for processing XML data in Java applications, and how to start using it. This section describes why data binding is used and how to create models for various constraints so that XML documents can be converted to Java objects. It also covers the input and output used to generate data binding classes.

Do you want to use XML in your Java application? Well, let's get on this ship with thousands of other people. After you have a deep understanding of XML, you may find that DOM and the sax api (see references) are just a publisher. You may think there is a simple way to get an XML document and access it through a Java application, right? Instead of calling back or using a complex tree structure, use methods like setOwner (Stringowner) and int getNumOrders (), right? If you have considered this problem, data binding is the solution you are looking.

 Analysis of various options

Today, XML and XML principles are flooding the tide (XSL, RDF, namespaces, RSS, XML Schema, XSLT ...), you may think that there are many ways to access XML data in Java applications. Surprisingly, there are only three methods to access XML data. That's right-there are only three methods, one of which is recently followed by a new Java API.

You should look at this problem as follows: a small selection range makes it easier for you to select the method that suits you.

Callback

Callback works as an event-driven model. When an XML document is analyzed, some events, such as the beginning of the document and the start of the character data in an element, will trigger the callback method. By using the data required for execution logic, you can implement the Java code of these events. It is not intuitive to understand this method. Developers usually spend some time understanding and understanding how to use the callback model. SAX, a simple API used for XML, is the de facto standard for using XML.

Tree

More common and popular is this API, which retrieves an XML document and then creates a tree structure of data. The XML document becomes the first tree and acts as a container. It has several sub-levels, such as the root element. The root element has its appended child level, and so on until (in a sense) a graph of XML data is obtained. Almost every college student must have processed the tree structure at a certain stage, so this can be used as a very intuitive way to represent XML data.

The most popular API used for the tree expression of XML documents is the W3C recommendation standard, that is, the Document Object Model (DOM ). An updated API, JDOM (which is not an acronym), has been widely used recently. (Although this solution was created by Jason Hunter, I have to tell the truth .) In addition, DOM and JDOM are both basic requirements for the design of the Spinnaker scheme. As a new XML analyzer, Spinnaker is under development as part of the Apache XML Scheme.

Although tree APIs seem easier to use than event-driven SAX, they are not always appropriate. Very large documents may require a large amount of memory (especially when using DOM); when performing a transformation (XSLT) to the tree structure, the system may stop running or even crash completely. Although updated APIs (such as JDOM) can handle these problems, they are still a problem if you have to process a large amount of data. In addition, sometimes developers prefer to model the data in the XML document as a simple Java object with a value-based read/write method, instead of working with a tree model. For example, developers would rather not access the child node named skuNumber and set the text value of the node, but only want to call setSkuNumber ("mySKU") and continue.


The latest methods for accessing XML data using Java code depend on a set of new Java methods and related APIs, which are still under development. Data Binding is a "Java specification requirement" (JSR-031, see references) built by Sun, designed to make it easier to bind Java objects to XML documents, in this way, one format can be easily converted to another format, and vice versa. Bind and reference a Java object with a read/write method. The read/write method affects the underlying XML document and is directly mapped to the element and feature names in the XML document. When you enter some details in the next part of this series of articles, this description will be more meaningful, but at present, just one point is enough: in this way, the feature name of the XML document can be changed by using a method called setName (), as I suggested above.

Data Binding

This access method is gaining popularity and is particularly useful when storing configuration information in XML documents. Many developers have found that it is very easy to directly access the required parameters without using a more complex tree structure. Although such access is of no use for document conversion or message transmission, it is extremely convenient for simple data processing. It is the third method to use XML in this article and this series of articles.

(Of course, any method will then introduce a series of new terms, so please refer to the glossary to learn about these new terms .)

Can any XML document be converted to a Java object? Or are there only some types of XML documents? Good question! You may only want to convert a document that meets a set of constraints to a Java object. This is similar to the method used to define a Java interface: Make sure that you only instantiate and use the objects that adapt to this interface, and allow assumptions on how to operate this object. Similarly, you can only convert XML objects that meet a set of constraints to Java objects. This allows you to use the created objects as expected.

 Constraint data

Before studying the code, you need to answer a few questions about how to represent XML data. This is one of the most challenging aspects of data binding. Create a new class for each document or an instance of an existing class? Which existing class do you want to use? And most importantly, is the document you are processing suitable for conversion to Java objects?

There are a lot of questions, but you will find all the answers here. Consider these problems as a series of decision points and a series of choices. First, you must determine whether you can create a Java object from the XML document (as discussed earlier ). If yes, you must decide whether the conversion should appear in the form of a new Java class or only in the form of an instance of the existing class. Finally, if you select an existing class, which class is used? The result is a variety of decision trees.

If we look at the example XML document shown in Listing 1 and try to solve these problems, the meaning of the decision tree will be clearer. This example indicates the configuration of a service (specifically a web Container) in the Enhydra Application Server.

Listing 1. an XML document used to configure the web Container in Enhydra <? Xml version = "1.0"?>


<WebServiceConfiguration version = "1.0" name = "My Web Container">
<Port number = "80" protocol = "http" protected = "false"/>
<Document root = "/usr/local/enhydra/html" index = "*. html, *. xml" error = "error.html"/>
</WebServiceConfiguration>


This configuration document contains information about the version and name of the service, as well as several nested projects. Each project represents additional information about the web Container service. It provides detailed information about ports (including port numbers, protocols, and security), and documentation service information (including document root, default extension used for index pages, and error pages ). All these together are all the information required to configure a new web Container service.

Remember this example, you can begin to answer all the questions in the data representation.

Is conversion appropriate?

Absolutely suitable! As long as you look at the XML document in Listing 1, you will find that it represents an object (the overall configuration object) with several features or variables. Some of these variables are other objects (ports and documents) that have their own characteristics. In fact, this is an excellent example of an XML document suitable for conversion to a Java object. To further ensure that this object is available, I will show you a way to constrain the data in the document later. However, let's continue following the decision tree.

Convert to class or instance?

After solving the suitability problem, we can now make a decision to convert every XML configuration document into a brand new Java class, or simply convert it into a new instance of an existing class. In other words, whether to generate new code or use existing code. In this way, this becomes a simple reusability problem. It is easier and more wise to generate new instances of existing classes for each XML document. If you have to try to create a new Java class from each document, the classes may not be compatible-that is, two identical documents may lead to two different Java classes!

Without this method that may cause confusion, you can use a set of XML constraints (represented by a DTD or XML scheme, which will be described below ), generate a Java class (or multiple classes, as needed) based on these constraints ). This generated class represents any XML document that meets these constraints; each of these XML documents will be decompressed to an instance of the generated class. In this case, you can define constraints for the document that represents the web service configuration. These constraints will be mapped into a Java class, which we will call WebServiceConfiguration. Then you can obtain any XML document that represents a specific web service configuration, and assume that this document complies with our constraints, by which you create an instance of the previously generated class. This allows applications to use different XML documents as objects of the same type, as long as the data in these documents is effective for the purpose of the Object design.

New Class or existing class?

Now you have the conditions to answer the next question: You want to create an instance of the existing class WebServiceConfiguration. All that remains to be clarified is how this class is pre-generated. So now, focus on the question: how to obtain a set of constraints, implement them using XML, and ensure that the documents comply with these constraints? Another question is, how do you generate a reusable Java class from these constraints?

Use document Constraints

Since you know that this document will be converted into a Java instance, this creates another problem: consider that you must ensure that this document can be correctly unwrapped into a selected Java class in some way. Missing variables or incorrect data types may cause errors during the unpacking process-or even running exceptions when the client accesses a container with incorrect configuration.

The best case is that before the actual unpacking process starts, the author of the document can ensure that the configuration document selects the class to indicate data as "legal ". XML people who have read this scheme may turn their eyes and say, "Well, of course you will use XML document constraints ." To confirm the validity of data for the selected class, you can reference the DTD (Document Type Definition) or XML Scheme.

By using a set of constraints represented by an external DTD or scheme file, the Document Author can test the configuration data on the "interface" of the data. In other words, you can create an application so that you can check the data contained in the XML instance document against the required data, the required data is specified in the external file of the document constraints. In this way, you can create an interface for data.

Making a decision between using the DTD scheme or using the XML Scheme is quite simple: because the Java language is highly typed, we hope to support typing in the XML document. For example, the data interface should be able to verify that the port number of the web container is provided with an integer rather than a string, which will cause an error when the service is started. DTD does not support type check. Therefore, we should select the XML Scheme. Although the XML Scheme is somewhat uncertain in the normative field, it has become stable to a large extent and is expected to be finalized within the year. We can write data constraints in an XML Scheme, and then use this scheme to verify possible instance documents to ensure that the unpacking can be performed on these instance documents. The following XML Scheme represents the data interface of our web Container service.

Listing 2. an XML Scheme indicating the data interface of a web container configuration document <? Xml version = "1.0"?>


<Schema targetNamespace = "http://www.enhydra.org" xmlns = "http://www.w3.org/1999/xmlSchema" xmlns: enhydra = "http://www.enhydra.org">

<ComplexType name = "ServiceConfiguration">
<Attribute name = "name" type = "string"/>
<Attribute name = "version" type = "float"/>
</ComplexType>


<Element name = "serviceConfiguration" type = "ServiceConfiguration"/>

<ComplexType name = "WebServiceConfiguration" baseType = "ServiceConfiguration" derivedBy = "extension">
<Element name = "port">
<ComplexType>
<Attribute name = "protocol" type = "string"/>
<Attribute name = "number" type = "integer"/>
<Attribute name = "protected" type = "string"/>
</ComplexType>
</Element>

<Element name = "document">
<ComplexType>
<Attribute name = "root" type = "string"/>
<Attribute name = "index" type = "string"/>
<Attribute name = "error" type = "string"/>
</ComplexType>
</Element>
</ComplexType>

<Element name = "webServiceConfiguration" type = "WebServiceConfiguration"/>

</Schema>


The XML Scheme in Listing 2 defines several different data objects, which together represent the configuration objects of a web service. First, a core service configuration (serviceConfiguration) is defined, which contains the version and name. This can be used as a basic object for all services (such as server Load balancer, EJB containers, and of course our web services. Then, as an extension of this basic service, the web service configuration is defined ). Note that after Java is built, the solution has already created a model for the data interface. We add the additional web service attributes port and document to the basic attributes of version and name. These attributes are all objects and have their own attributes (protocol, root, error, etc ).

In the definition method of this scheme, features represent a simple Java type, usually the primitive type. In this way, name and version are the original Java types of String and float respectively. Elements such as port and document become Java objects. They can have their own attributes or be represented by features. In this way, recursion occurs: the element becomes a new object, and each attribute of the element is checked. If an attribute is a feature, a simple original Java member variable is created for this object. If the attribute is an element, a new object is created and added as a member variable, then, the same process is started on the new object until all classes have been created.
Obtain Java from radish... mm... XML

Once an XML Scheme is created, you need to extract the required information from the scheme to determine which Java classes should be created. The first step in this process is to view the XML Scheme and strictly determine what the output should be. For simple serviceConfiguration objects, two original Java attributes are defined: name and version. For such a simple object, it is not difficult to determine the required interface. You only need to uppercase the first letter of the name of the defined type and add these Java attributes to the interface, as shown in listing 3.

Listing 3. Java code public interface generated from XML Scheme for ServiceConfiguration interface

ServiceConfiguration {
Public void setVersion (float version );
Public float getVersion ();
Public void setName (String name );
Public String getName ();
}

This is quite understandable; the interfaces in listing 3 provide read and write methods for the attributes defined in the XML Scheme. In addition, you will need to generate an implementation class to define each member variable of this interface and implement each method in this interface. This method of separating interfaces from implementations enables us to provide multiple implementations for specific needs. For example, a specific service may need to perform computation instead of simply accepting the value received from the write method. It is still too early to consider more complex situations, but I will repeat it in subsequent articles. However, in general, you can determine what the implementation class should look like, as shown in Listing 4.

Listing 4. Java code public class generated from the XML Scheme for ServiceConfiguration implementation

ServiceConfigurationImpl implements ServiceConfiguration {
Private String name;
Private float version;

Public void setVersion (float version ){
This. version = version;
}

Public float getVersion (){
Return version;
}

Public void setName (String name ){
This. name = name;
}

Public String getName (){
Return name;
}
}

The same principle applies to other objects defined in the XML Scheme. You can see other Java classes below (because they should all be generated ):

PortType. java
PortTypeImpl. java
DocumentType. java
DocumentTypeImpl. java
WebServiceConfiguration. java
WebServiceConfigurationImpl. java

Summary

So far, you should be familiar with all aspects of data binding. I have introduced the reasons for using data binding, especially in the scope of configuration information, and outlined some basic concepts you need to understand to implement this method.

Related Article

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.