bea.com | products | dev2dev | support | askBEA

Download Docs | Site Map | Glossary
Search

Developing Adapters

XML Toolkit

The XML Toolkit provided with BEA WebLogic Integration's Adapter Development Kit (ADK) helps you develop valid XML documents to transmit information from an EIS to the application on the other side of the adapter. It consolidates, in a single location, many of the operations required for XML manipulation, relieving you of the need to perform these often tedious chores separately.

This section contains information about the following subjects:

- Toolkit Packages

- IDocument

- Schema Object Model (SOM)

Toolkit Packages

The XML Toolkit is composed primarily of two Java packages:

- com.bea.document

- com.bea.schema

These packages are available in the xmltoolkit.jar file, which is installed with the ADK when you install WebLogic Integration. They include complete Javadoc for each class, interface, and method. To see the Javadoc, go to the following URL:

>     http://edocs.bea.com/wli/docs70/classdocs/index.html

In this URL WLI_HOME is the folder in which WebLogic Integration is installed.

IDocument

com.bea.document.IDocument

An IDocument is a container that combines the W3C Document Object Model (DOM) with an XPath interface to elements in an XML document. This combination makes it possible to query and update IDocument objects simply by using XPath strings. These strings eliminate the need to parse an entire XML document to find specific information by allowing you to specify only those elements you want to query, and returning responses to those queries.

For example, the XML document shown in Listing B-1 describes a person named Bob.

Listing B-1 XML Example

>     <Person name="Bob">
>         <Home squareFeet="2000"/>
>         <Family>
>             <Child name="Jimmy">
>                 <Stats sex="male" hair="brown" eyes="blue"/>
>             </Child>
>             <Child name="Susie">
>                 <Stats sex="female" hair="blonde" eyes="brown"/>
>             </Child>
>         </Family>
>     </Person>

Suppose you want to retrieve Jimmy's hair color from the <child> element. If you use DOM, you must use the code shown in Listing B-2.

Listing B-2 Sample Retrieval of DOM Data

>     String strJimmysHairColor = null;
>     org.w3c.dom.Element root = doc.getDocumentElement();
>     if (root.getTagName().equals("Person") && root.getAttribute("name").
>        equals("Bob") {
>         org.w3c.dom.NodeList list = root.getElementsByTagName("Family"); if
>                 (list.getLength() > 0) {
>              org.w3c.dom.Element family = (org.w3c.dom.Element)list.item(0);
>               org.w3c.dom.NodeList childList = family.getElementsByTagName ("Child");
>              for (int i=0; i < childList.getLength(); i++) {
>                   org.w3c.dom.Element child = childList.item(i);
>                   if (child.getAttribute("name").equals("Jimmy")) {
>                        org.w3c.dom.NodeList statsList = child.
>                           getElementsByTagName("Stats");
>                        if (statsList.getLength() > 0) {
>                             org.w3c.dom.Element stats = statsList.item(0);
>                             strJimmysHairColor = stats.getAttribute("hair");
>                        }
>                   }
>              }
>          }
>     }

By using IDocument, however, you can retrieve Jimmy's hair color by creating the XPath string that seeks exactly that information, as shown in Listing B-3.

Listing B-3 Sample Retrieval of IDocument Data

>     System.out.println("Jimmy's hair color: " + person.getStringFrom
>        ("//Person[@name=\"Bob\"] /Family/Child[@name=\"Jimmy\"]/Stats/@hair");

As you can see, by using IDocument you can simplify the code necessary to query and find information in a document.

Schema Object Model (SOM)

SOM is an interface for programmatically building XML schemas. An adapter calls an EIS for specific request and response metadata, which then must be programatically transformed into an XML schema. SOM is a set of tools that extracts and validates many of the common details XML schemas—such as syntactical complexities of schemas—so that you can focus on the more fundamental aspects of the XML document.

How SOM Works

An XML schema is similar to a contract between an EIS and an application on the other side of the adapter. This contract specifies how data coming from the EIS must be displayed in order to be manipulated by the application. A document (that is, an XML-rendered collection of metadata from the EIS) is considered valid if it meets the rules specified in the schema, regardless of whether or not the XML code in the document is correct. For example, if a schema requires a name to be shown in a <name> element and that element requires two child elements, <firstname> and <lastname>, then, in order to be valid, the document from the EIS must be written in the form shown in Listing B-4 and the schema must be written as shown in Listing B-5.

Listing B-4 Document Example

>     <name>
>          <firstname>Joe</firstname>
>          <lastname>Smith</lastname>
>     </name>

Listing B-5 Schema Example

>     <schema>
>         <element name="name">
>             <complexType>
>                 <sequence>
>                     <element name="firstname" />
>                     <element name="lastname" />
>                 </sequence>
>             </complexType>
>         </element>
>     </schema>

No other form of <name></name> is valid, even if it is written as correct XML code. The following XML, for example, is not valid:

<name>Joe Smith</name>

Creating the Schema

You can create an XML schema programatically by using the classes and methods provided with SOM. The benefit of using this tool is that it allows you to tailor a schema for your needs simply by populating the variables in the program components. For instance, the following code examples create a schema that validates a purchase order document. Listing B-6 sets up the schema and adds the necessary elements.

Listing B-6 Purchase Order Schema

>     import com.bea.schema.*;
>     import com.bea.schema.type.SOMType;

>     public class PurchaseOrder
>     {
>         public static void main(String[] args)
>         {
>             System.out.println(getSchema().toString());
>         }

>         public static SOMSchema getSchema()
>         {
>             SOMSchema po_schema = new SOMSchema();

>         po_schema.addDocumentation("Purchase order schema for
>           Example.com.\nCopyright 2000 Example.com.\nAll rights
>           reserved.");

>             SOMElement purchaseOrder =
>                po_schema.addElement("purchaseOrder");

>             SOMElement comment = po_schema.addElement("comment");

>             SOMComplexType usAddress =
>                po_schema.addComplexType("USAddress");

>             SOMSequence seq2 = usAddress.addSequence();

>         // adding an  object to a SOMSchema defaults to type="string"
>         seq2.addElement("name");
>         seq2.addElement("street");
>         seq2.addElement("city");
>         seq2.addElement("state");
>         seq2.addElement("zip", SOMType.DECIMAL);

Attributes can be set in the same way that elements are created, as shown in Listing B-7. To set these attributes correctly, you must maintain their addressability.

Listing B-7 Setting Parent Attributes

>     SOMAttribute country_attr = usAddress.addAttribute("country",
>        SOMType.NMTOKEN);
>         country_attr.setUse("fixed");
>         country_attr.setValue("US");

Like complexTypes, simpleTypes can be added to the root of the schema, as shown in Listing B-8.

Listing B-8 Adding SimpleTypes to the Schema Root

>     SOMSimpleType skuType = po_schema.addSimpleType("SKU");
>     SOMRestriction skuRestrict = skuType.addRestriction
>        (SOMType.STRING);
>     skuRestrict.setPattern("\\d{3}-[A-Z]{2}");

>     SOMComplexType poType =
>        po_schema.addComplexType("PurchaseOrderType");

>     purchaseOrder.setType(poType);
>     poType.addAttribute("orderDate", SOMType.DATE);

The addSequence() method of a SOMComplexType object returns a SOMSequence reference, allowing you to modify the element that was added to the schema. As shown in Listing B-9, objects are added to the schema in this way.

Listing B-9 Implementing addSequence() to Modify an Element

>     SOMSequence poType_seq = poType.addSequence();
>         poType_seq.addElement("shipTo", usAddress);
>         poType_seq.addElement("billTo", usAddress);

The attributes of an element within a schema can be set by calling the setter methods of the SOMElement object. For example, Listing B-10 shows the implementation of setMinOccurs() and setMaxOccurs().

Listing B-10 Implementing setMinOccurs() and setMaxOccurs()

>     SOMElement commentRef = new SOMElement(comment);
>         commentRef.setMinOccurs(0);
>         poType_seq.add(commentRef);
>     SOMElement poType_items = poType_seq.addElement("items");

>     SOMComplexType itemType = po_schema.addComplexType("Items");
>     SOMSequence seq3 = itemType.addSequence();
>     SOMElement item = new SOMElement("item");
>         item.setMinOccurs(0);
>         item.setMaxOccurs(-1);
>         seq3.add(item);
>     SOMComplexType t = new SOMComplexType();
>         item.setType(t);
>     SOMSequence seq4 = t.addSequence();
>         seq4.addElement("productName");
>     SOMElement quantity = seq4.addElement("quantity");
>     SOMSimpleType st = new SOMSimpleType();
>         quantity.setType(st);
>     SOMRestriction restrict =
>        st.addRestriction(SOMType.POSITIVEINTEGER);
>        restrict.setMaxExclusive("100");

In this example, the items element for PurchaseOrderType was created before the Items type. Therefore when the Items type object becomes available, you must create the reference and set the type by using the code shown in Listing B-11.

Listing B-11 Setting the Type When the Items Type Object Is Available

>     poType_items.setType(itemType);

Finally, you need to add an element to the schema. You can do so by implementing either the addElement() method of SOMSequence or the add() method from a previously created SOMElement. Listing B-12 shows both methods.

Listing B-12 Adding an Element to the Schema

>     seq4.addElement("USPrice", SOMType.DECIMAL);

>         SOMElement commentRef2 = new SOMElement(comment);
>            commentRef2.setMinOccurs(0);
>            seq4.add(commentRef2);

>         SOMElement shipDate = new SOMElement("shipDate", SOMType.DATE);
>            shipDate.setMinOccurs(0);
>            seq4.add(shipDate);
>         t.addAttribute("partNum", skuType);

>         return po_schema;
>       }
>     }

Resulting Schema

When you run the code shown in the previous seven listings (Listing B-6 through Listing B-12), the schema shown in Listing B-13 is created.

Listing B-13 XML Schema Definition Document

>     <?xml version="1.0" ?>
>     <!DOCTYPE schema (View Source for full doctype...)>
>     <xsd:schema xmlns:xsd="http://www.w3.org/2000/XMLSchema">
>         <xsd:annotation>

>             <xsd:documentation>Purchase order schema for Example.com.
>                Copyright 2000 Example.com. All rights
>                reserved.</xsd:documentation>

>         </xsd:annotation>

>         <xsd:simpleType name="SKU">
>             <xsd:annotation>
>             </xsd:annotation>
>             <xsd:restriction base="xsd:string">
>                 <xsd:pattern value="\d{3}-[A-Z]{2}" />
>             </xsd:restriction>
>         </xsd:simpleType>

>         <xsd:complexType name="PurchaseOrderType">
>             <xsd:sequence>
>                 <xsd:element type="USAddress" name="shipTo" />
>                 <xsd:element type="USAddress" name="billTo" />
>                 <xsd:element ref="comment" minOccurs="0" />
>                 <xsd:element type="Items" name="items" />
>             </xsd:sequence>

>             <xsd:attribute name="orderDate" type="xsd:date" />
>         </xsd:complexType>

>         <xsd:complexType name="Items">
>             <xsd:sequence>
>                 <xsd:element maxOccurs="unbounded" name="item"
>                    minOccurs="0">
>                     <xsd:complexType>
>                         <xsd:sequence>
>                             <xsd:element type="xsd:string"
>                                name="productName"/>
>                             <xsd:element name="quantity">
>                                <xsd:simpleType>
>                                    <xsd:restriction base=
>                                       "xsd:positiveInteger">
>                                        <xsd:maxExclusive value="100"/>
>                                    </xsd:restriction>
>                                </xsd:simpleType>
>                             </xsd:element>
>                             <xsd:element type="xsd:decimal" name=
>                                "USPrice" />
>                             <xsd:element ref="comment"
>                                minOccurs="0" />
>                             <xsd:element type="xsd:date"
>                                name="shipDate" minOccurs="0" />
>                         </xsd:sequence>
>                         <xsd:attribute name="partNum" type="SKU" />
>                     </xsd:complexType>
>               </xsd:element>
>           </xsd:sequence>
>       </xsd:complexType>

>       <xsd:complexType name="USAddress">
>         <xsd:sequence>
>             <xsd:element type="xsd:string" name="name" />
>             <xsd:element type="xsd:string" name="street" />
>             <xsd:element type="xsd:string" name="city" />
>             <xsd:element type="xsd:string" name="state" />
>             <xsd:element type="xsd:number" name="zip" />
>         </xsd:sequence>

>         <xsd:attribute name="country" use="fixed" value="US"
>            type="xsd:NMTOKEN" />
>     </xsd:complexType>
>     <xsd:element type="PurchaseOrderType" name="purchaseOrder" />
>     <xsd:element type="xsd:string" name="comment" />
>     </xsd:schema>

Validating an XML Document

The schema shown in Listing B-13 is then used to validate a document sent from the EIS. For example, the document described in Listing B-14 passes schema validation based on the schema we just created.

Listing B-14 Validated XML Document

>     <?xml version="1.0" ?>
>     <!DOCTYPE PurchaseOrder (View Source for full doctype...)>

>     <purchaseOrder orderDate="1/14/00">
>     <shipTo Country="US">
>         <name>Bob Jones</name>
>         <street>1000 S. 1st Street</street>
>         <city>Denver</city>
>         <state>CO</state>
>         <zip>80111</zip>
>     </shipTo>

>     <billTo Country="US">
>         <name>Bob Jones</name>
>         <street>1000 S. 1st Street</street>
>         <city>Denver</city>
>         <state>CO</state>
>         <zip>80111</zip>
>     </billTo>

>     <comment>None</comment>

>     <items>
>         <item partNum="123-AA">
>             <productName>Washer</productName>
>             <quantity>20</quantity>
>             <USPrice>0.22</USPrice>
>             <comment>Only shipped 10</comment>
>             <shipDate>1/14/00</shipDate>
>         </item>
>         <item partNum="123-BB">
>             <productName>Screw</productName>
>             <quantity>10</quantity>
>             <USPrice>0.30</USPrice>
>             <comment>None</comment>
>             <shipDate>1/14/00</shipDate>
>         </item>
>     </items>
>     </purchaseOrder>

How the Document Is Validated

SOM can be used to validate XML DOM documents by using the SOMSchema method isValid().The SOMElement class includes a corresponding isValid() method for validating an element instead of a DOM document.

The isValid() method determines whether a document or element is valid and, if it is not, isValid() compiles a list of errors. If the document is valid, isValid() returns true and the list of errors is empty.

Implementing isValid()

Listing B-15 shows two ways to implement isValid().

Listing B-15 Examples of isValid() Implementation

>     public boolean isValid(org.w3c.dom.Document doc,
>                            java.util.List errorList)
>     public boolean isValid(IDocument doc,
>                            List errorList)

The following parameters are used:

- doc - The document instance to be validated

- errorList - A list of errors found in the document, doc

isValid() returns a boolean value of true if the document is valid with respect to this schema. If the document is not valid with respect to the schema, isValid() returns false and the errorList is populated.

errorList is a java.util.List for reporting errors found in the document, doc. The error list is cleared before validating the document. Therefore, the list implementation used must support the clear() method. If isValid() returns false, the error list is populated with a list of errors found during the validation procedure. The items in the list are instances of the class com.bea.schema.SOMValidationException. If isValid() returns true, errorList is empty.

For complete information about the API, see the Javadoc for isValid() at the following URL:

WLI_HOME/docs/apidocs/com/bea/SOMSchema.html

isValid() Sample Implementation

Listing B-16 shows a sample implementation of isValid().

Listing B-16 Sample Implementation of isValid()

>     SOMSchema schema = ...;

>     IDocument doc = DocumentFactory.createDocument(new FileReader(f));
>     java.util.LinkedList errorList = new java.util.LinkedList();
>     boolean valid = schema.isValid(doc, errorList);...
>     if (! valid){
>        System.out.println("Document was invalid. Errors were:");
>        for (Iterator i = errorList.iterator; i.hasNext();)
>     {

>            System.out.println(((SOMValidationException) i.next).
>               toString());

>        }