Java TM Technology to XML Binding Tools JAXB
Java. TM Technology to XML Binding Tools JAXB, Castor, XMLBeans, Ji. BX Aaron Mulder Chief Technical Officer Chariot Solutions 1 | 2004 Java. One. SM Conference | Session 2841 java. sun. com/javaone/sf
Goal of This Talk Moving beyond SAX and DOM Learn how to use XML binding tools to read, write, and manipulate XML documents by interacting with simple Java objects 2 | 2004 Java. One. SM Conference | Session 2841
Agenda Overview of XML binding tools Introduction to each tool in this talk Sample code Tool comparison Q&A 3 | 2004 Java. One. SM Conference | Session 2841
Credentials & Use Cases • Aaron Mulder ─ XML binding user • When XML binding? ─ XML configuration files ─ XML data exchange files ─ Save objects to XML when exceptions crop up, reload from XML in test cases ─ Anywhere you’d otherwise use a lower-level API • When not XML binding? ─ Large files (bulk data load) ─ Multiple versions of same XML format (maybe) 4 | 2004 Java. One. SM Conference | Session 2841
Agenda Progress Overview of XML binding tools Introduction to each tool in this talk Sample code Tool comparison Q&A 5 | 2004 Java. One. SM Conference | Session 2841
XML Binding • JAXP provides SAX and DOM, which are manual APIs to extract information from an XML document • The JAXP spec addresses input; output is provided indirectly via XSLT • There are higher-level tools like JDOM, but we’re still dealing with data, not objects • XML binding tools allow us to directly map XML documents to Java objects without manual effort • This talk covers 4 tools; there are more. 6 | 2004 Java. One. SM Conference | Session 2841
XML Binding Example <customer> <name> <first-name>Aaron</first-name> <last-name>Mulder</last-name> </name> <street>165 Indiana Ave</street> <city>Fort Washington</city> … </customer> • Complex type definitions are mapped to classes • Child elements & attributes are mapped to fields • May be able to adjust depth 7 | 2004 Java. One. SM Conference | Session 2841 Customer street city Name first. Name last. Name
XML Binding Approaches • May start from: ─ ─ Schema DTD (legacy) one or more XML Documents Existing Java classes • May generate Java classes based on XML document/DTD/schema • Any way you slice it, you get marshalling (Java to XML), unmarshalling (XML to Java), modification, and validation • Each tool offers value-added features 8 | 2004 Java. One. SM Conference | Session 2841
When to Use These Approaches • Schema-centric (generating) is best when you: ─ Have a stable Schema ─ Must get up and running quickly ─ Want to validate according to the Schema • Java technology-centric (mapping) is best when you: ─ Don’t want object model tied to schema ─ Need to support different versions of the schema with the same object model ─ Want a common data exchange format for existing objects 9 | 2004 Java. One. SM Conference | Session 2841
What’s the Same Across These Tools • Schema support • Can generate new Java objects to represent an XML document • Can customize the generated code to some degree (i. e. package/class names) • Free to use (though specific license varies) • Documentation available • Command-line and Ant tools 10 | 2004 Java. One. SM Conference | Session 2841
What’s Different • Support for XML documents without a • • • 11 corresponding schema Support for DTDs (in some cases via conversion to schema) Points at which the tool validates (may be automatically or programmatically) Events/listeners for changes to XML objects Mapping a schema to existing classes without generating any code Unmarshalling into existing objects to reuse memory for multiple documents | 2004 Java. One. SM Conference | Session 2841
What’s Different, cont. • Whether you can unmarshal a subset of a large document • • • 12 GUI tools or IDE plugins Parser/J 2 SETM platform prerequisites Speed & memory usage Size of redistributable JAR(s) Whether generated classes are plain Java. Beans. TM objects or extend XML-related base classes | 2004 Java. One. SM Conference | Session 2841
Agenda Progress Overview of XML binding tools Introduction to each tool in this talk Sample Code Tool comparison Q&A 13 | 2004 Java. One. SM Conference | Session 2841
Java Architecture for XML Binding (JAXB) http: //java. sun. com/xml/jaxb/ • JAXB 1. 0 Specification (JSR 31) ─ Developed within Java Community Process. SM (JCPSM) ─ Specification, Reference Implementation (RI) and Technology Compatibility Kit (TCK) ─ Only supported subset of XML Schema • JAXB 1. 0 RI is tool discussed today • JAXB 2. 0 Specification is under development (JSR-222) ─ All tools on panel participate in this effort • Vendor-specific extensions ─ Enable additional schema support than originally specified 14 | 2004 Java. One. SM Conference | Session 2841
JAXB RI v 1. 0. 3 Features • Supports subset of XML Schema ─ Vendor extensions ─ Element and Type Substitution ─ DTD and RELAX/NG • Customizable ─ Schema-derived code and XML output format • Smaller memory footprint ─ JAXB 1. 0 does not require XML infoset preservation • Unmarshal and On-Demand Validation • Active forums & weekly bugfix releases at https: //jaxb. dev. java. net/ 15 | 2004 Java. One. SM Conference | Session 2841
JAXB 2. 0 Specification Goals • Full XML Schema support • Java technology-centric Binding Model ─ Bind Java class to XML Schema ─ Customize binding with annotations • • • 16 Leverage J 2 SE 5. 0 platform features Provide JAX-RPC 2. 0 databinding Updateable Partial Binding Schema Evolution JAXB 2. 0 Early Draft available for review at http: //jcp. org/about. Java/communityprocess/edr/jsr 222 | 2004 Java. One. SM Conference | Session 2841
The Castor Project http: //www. castor. org/ • Can map existing classes to XML • XML documents can be unmarshalled directly into • • 17 Java. Beans components without preconfigured mapping Likewise, any Java. Beans component can be marshalled to XML via introspection without preconfigured mapping Includes a tool to generate a schema from a DTD or existing XML documents can be unmarshalled into existing objects to save memory Reflection based, but able to call custom getters and setters as well | 2004 Java. One. SM Conference | Session 2841
Castor, cont. • Generated classes are plain Java. Beans components, along with generated or manually provided compile-time descriptor classes • Developer can customize generated source code via the binding file, including event support (namely, bound properties) • Developer can customize the marshalled XML formatting via the mapping file • Supports custom Field. Handlers for extensibility • Supports optional validation including invoking the validator by hand 18 | 2004 Java. One. SM Conference | Session 2841
XMLBeans http: //xmlbeans. apache. org/ • Originally a BEA tool, then incubated at Apache, now a top-level Apache project • Version 1. 03 just approved, Version 2 in development • • 19 Supports all of XML Schema Provides full schema object model API Preserves the full XML Infoset Can validate after any change to the objects | 2004 Java. One. SM Conference | Session 2841
XMLBeans, cont. • Generated code extends XML base classes with special XML/Schema features ─ Provides access to Xml. Cursor API ─ Developer can switch between XML/Java technology features • Does not create Java objects at parse time ─ Java objects created lazily as necessary • Upcoming version 2: ─ ─ ─ 20 Reduces JAR and memory footprint Adds DOM Level II support over XML Store Adds support for Java technology-centric approach Ability to extend generated objects with custom functionality Pre- and post- events on generated methods | 2004 Java. One. SM Conference | Session 2841
Ji. BX http: //www. jibx. org/ • Ji. BX uses binding definitions ─ You define how XML relates to Java objects ─ Allows structural changes going to and from XML ─ Start from schema, code, or both • Binding code compiled into your class files ─ At build time, or on-the-fly at runtime ─ Allows compact and fast runtime • Fundamentally a Java technology-centric approach • Current beta 3 c release in widespread production use 21 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Binding Definition Flexibility • Current code supports: ─ Complex types with simple content, mixed content, etc. ─ Input-output, input-only, or output-only bindings ─ Multiple bindings, even for the same classes ─ Easy extension hooks (pre-set, post-set, pre-get) ─ Custom marshallers / unmarshallers ─ Selective marshalling / unmarshalling, streaming • More features planned for future. . . 22 | 2004 Java. One. SM Conference | Session 2841
Agenda Progress Overview of XML binding tools Introduction to each tool in this talk Sample code Tool comparison Q&A 23 | 2004 Java. One. SM Conference | Session 2841
Scenario • I’m working on an application server or deployment tool • I am given a J 2 EE 1. 4 application with deployment descriptors (based on XML Schema) • I need to extract the information from those deployment descriptors • To narrow it down even further, I’m working with a J 2 EE Connector 1. 5 deployment descriptor (ra. xml) • This is a complex set of schemas! 24 | 2004 Java. One. SM Conference | Session 2841
J 2 EE 1. 4 Schemas • • • 25 application_1_4. xsd application-client_1_4. xsd connector_1_5. xsd ejb-jar_2_1. xsd j 2 ee_1_4. xsd j 2 ee_web_services_1_1. xsd j 2 ee_web_services_client_1_1. xsd jsp_2_0. xsd web-app_2_4. xsd web-jsptaglibrary_2_0. xsd xml. xsd | 2004 Java. One. SM Conference | Session 2841
Sample Deployment Descriptor (ra. xml) <? xml version="1. 0" encoding="UTF-8" ? > <connector xmlns="http: //java. sun. com/xml/ns/j 2 ee" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //java. sun. com/xml/ns/j 2 ee/connector_1_5. xsd" version="1. 5"> <description>Resource Adapter to interact with an RFID savant. Currently supports SOAP over HTTP savant MTB. </description> <display-name>Chariot RFID Adapter</display-name> <vendor-name>Chariot Solutions LLC</vendor-name> <eis-type>Auto-ID Savant v 1. 0</eis-type> <resourceadapter-version>1. 0</resourceadapter-version> <resourceadapter-class>com. chariotsolutions. rfid. ra. RFIDAdapter</resourceadapter-class> <config-property> <description>The TCP/IP hostname where the savant can be reached</description> <config-property-name>Host. Name</config-property-name> <config-property-type>java. lang. String</config-property-type> </config-property> <description>The TCP/IP port where the savant can be reached. Used for HTTP transport. </description> <config-property-name>Port</config-property-name> <config-property-type>java. lang. Integer</config-property-type> </config-property> <connector> <inbound-resourceadapter> <messagelistener> <messagelistener-type>com. chariotsolutions. rfid. event. RFIDListener</messagelistener-type> <activationspec-class>com. chariotsolutions. rfid. ra. in. Scan. Spec</activationspec-class> <required-config-property> <description>Network port to listen on for incoming messages</description> <config-property-name>Port</config-property-name> </required-config-property> </activationspec> </messagelistener> </messageadapter> </inbound-resourceadapter> </connector> <description>…</description> <display-name>…</display-name> … </connector> 26 | 2004 Java. One. SM Conference | Session 2841
Sample Code • Run the schema compiler to generate the code • Load from an XML file into Java objects • Print the object representing the Connector element ─ For XMLBeans, this prints an XML fragment including the entire contents of that element ─ Other tools print the object class/ID • Print the values of the description and display name child elements • Customized mapping avoided where possible 27 | 2004 Java. One. SM Conference | Session 2841
XMLBeans Schema Compiler export XMLBEANS_HOME=/usr/local/java/xmlbeans-1. 0. 3 export PATH=$PATH: $XMLBEANS_HOME/bin scomp -src java/xmlbeans -out lib/xmlbeans/schema. jar -verbose schema/ • Compiled all schemas at once! • No complaints or problems • Generates a JAR containing the necessary runtime “stuff”, plus source code for reference 28 | 2004 Java. One. SM Conference | Session 2841
XMLBeans Usage Connector. Document doc = Connector. Document. Factory. parse(new File. Reader("ra. xml")); Connector. Type con = doc. get. Connector(); System. out. println("Connector: "+con); System. out. println("Description: " +con. get. Description. Array()[0]. get. String. Value()); System. out. println("Display Name: " +con. get. Display. Name. Array()[0]. get. String. Value()); • No casts! • Generated code has interface/implementation separation 29 | 2004 Java. One. SM Conference | Session 2841
JAXB Schema Compiler export JWSDP_HOME=/usr/local/java/jwsdp-1. 4 export PATH=$PATH: $JWSDP_HOME/jaxb/bin xjc. sh -extension -d java/jaxb schema/connector_1_5. xsd • Takes one schema at a time • Did not successfully compile ejb-jar_2_1. xsd • Needed an updated weekly build to handle other J 2 EE schemas • Generates Java code for us to compile 30 | 2004 Java. One. SM Conference | Session 2841
JAXB Usage JAXBContext jc = JAXBContext. new. Instance( "com. sun. java. xml. ns. j 2 ee" ); Unmarshaller u = jc. create. Unmarshaller(); Connector con = (Connector)u. unmarshal(new File. Input. Stream( "ra. xml" ) ); System. out. println("Connector: "+con); System. out. println("Description: " +((Description. Type)con. get. Description(). get(0)). get. Value()); System. out. println("Display Name: " +((Display. Name. Type)con. get. Display. Name(). get(0)). get. Value()); • Needed to cast from a List • Generated code has interface/implementation separation with very clean interfaces 31 | 2004 Java. One. SM Conference | Session 2841
Castor Schema Compiler export CASTOR_HOME=/usr/local/java/castor-0. 9. 5. 3 export PATH=$PATH: $CASTOR_HOME export CLASSPATH=. . . /xerces. Impl. jar source. Gen -i schema/connector_1_5. xsd -dest java/castor -verbose -f • Takes one schema at a time • Did not successfully compile ejb-jar_2_1. xsd • Needed to override endless prompting and ignore a number of warnings • Generates code for us to compile (however, required manual mapping for it to compile!) 32 | 2004 Java. One. SM Conference | Session 2841
Castor Usage Connector con = (Connector) Connector. unmarshal(new File. Reader("ra. xml")); System. out. println("Connector: "+con); System. out. println("Description: " +con. get. Description. Group(). get. Description()[0]. get. Cont ent()); System. out. println("Display Name: " +con. get. Description. Group(). get. Display. Name()[0]. get. Cont ent()); • No casts! • Generated objects with their own marshall/unmarshall methods 33 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Schema Compiler • No such thing! • I wrote my own POJOs instead public class Connector { private String description; private String display. Name; //getters & setters } • Very tight Java code, but… • …does anyone see the error I’ve introduced already? Schemas are hard to read and XML files aren’t representative. 34 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Mapping File <binding> <mapping name="connector" class="example. jibx. Connector"> <namespace uri="http: //java. sun. com/xml/ns/j 2 ee" default="elements" /> <value name="description" field="description" /> <value name="display-name" field="display. Name" /> <structure name="vendor-name" usage="optional"/> <structure name="eis-type" usage="optional"/> <structure name="resourceadapter-version" usage="optional"/> <structure name="resourceadapter" usage="optional"/> </mapping> </binding> 35 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Binding Tool export JIBX_HOME=/usr/local/java/jibx-beta 3 c export CLASSPATH=$JIBX_HOME/lib/bcel. jar: $JIBX_HOME/lib/ jibx-bind. jar: $JIBX_HOME/lib/jibxrun. jar: $JIBX_HOME/lib/xpp 3. jar: classes java org. jibx. binding. Compile jibx. binding • First compile the Java code • Then run this tool to mangle the classes • Now binding features are available at runtime (but not directly at development time) 36 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Usage IBinding. Factory bfact = Binding. Directory. get. Factory(Connector. class); IUnmarshalling. Context uctx = bfact. create. Unmarshalling. Context(); Object obj = uctx. unmarshal. Document(new File. Input. Stream("ra. xml"), null); Connector con = (Connector) obj; System. out. println("Connector: "+con); System. out. println("Description: "+con. get. Description()); System. out. println("Display Name: " +con. get. Display. Name()); • I get to use my lovely POJOs (bugs and all!) • Use Ji. BX API calls to marshall/unmarshall 37 | 2004 Java. One. SM Conference | Session 2841
Agenda Progress Overview of XML binding tools Introduction to each tool in this talk Sample code Tool Comparison Q&A 38 | 2004 Java. One. SM Conference | Session 2841
XMLBeans Thoughts • Advantages ─ Full schema support ─ Navigation & query of documents ─ Lots of metadata available • Disadvantages ─ More overhead at runtime ─ Likes its generated JAR, doesn’t like it so much if you just compile the code it generates • Overall ─ My favorite when starting with complex schemas and generating code ahead of time 39 | 2004 Java. One. SM Conference | Session 2841
JAXB RI Thoughts • Advantages ─ Standards-based (other implementations out there, or coming) ─ Supports DTDs, Relax-NG, etc. ─ Interfaces look quite nice • Disadvantages ─ Incomplete schema support ─ Generated code required casts (JAXB 2 should be better with Generics, etc. ) • Overall ─ Not my first choice… yet. 40 | 2004 Java. One. SM Conference | Session 2841
Castor Thoughts • Advantages ─ Can operate without the schema compiler step (using reflection only) ─ All generated code goes in one package, no class bloat ─ Castor offers O/R features too • Disadvantages ─ Incomplete schema support ─ Required manual mapping; some rough edges • Overall ─ First choice for on-the-fly mapping 41 | 2004 Java. One. SM Conference | Session 2841
Ji. BX Thoughts • Advantages ─ Small & fast ─ You write the code • Disadvantages ─ You write the code – hopefully the right code ─ Bytecode mangling makes debugging hard ─ Still under active development (mapping file format changes between beta releases, etc. ) • Overall ─ Best for small schemas, existing Java code, version conflicts, etc. 42 | 2004 Java. One. SM Conference | Session 2841
Agenda Progress Overview of XML binding tools Introduction to each tool in this talk Sample code Tool comparison Q&A 43 | 2004 Java. One. SM Conference | Session 2841
Q&A http: //java. sun. com/xml/jaxb/ http: //www. castor. org/ http: //xml. apache. org/xmlbeans/ http: //www. jibx. org/ 44 | 2004 Java. One. SM Conference | Session 2841
Java to XML Binding Tools JAXB, Castor, XMLBeans, Ji. BX Aaron Mulder 45 | 2004 Java. One. SM Conference | Session 2841 java. sun. com/javaone/sf
- Slides: 45