Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JavaTM Technology to XML Binding Tools JAXB, Castor, XMLBeans, JiBX Aaron Mulder Chief Technical Officer Chariot Solutions 1 | 2004 JavaOneSM 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 JavaOneSM Conference | Session 2841 Agenda Overview of XML binding tools Introduction to each tool in this talk Sample code Tool comparison Q&A 3 | 2004 JavaOneSM 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 JavaOneSM 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 JavaOneSM Conference | Session 2841 XML Binding • JAXP provides SAX and DOM, which are • • • • 6 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. | 2004 JavaOneSM 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 JavaOneSM Conference | Session 2841 Customer street city Name firstName lastName 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 JavaOneSM 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 JavaOneSM 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 JavaOneSM 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 JavaOneSM Conference | Session 2841 What’s Different, cont. • Whether you can unmarshal a subset of a • • • • • 12 large document GUI tools or IDE plugins Parser/J2SETM platform prerequisites Speed & memory usage Size of redistributable JAR(s) Whether generated classes are plain JavaBeansTM objects or extend XML-related base classes | 2004 JavaOneSM 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 JavaOneSM 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 ProcessSM (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 JavaOneSM Conference | Session 2841 JAXB RI v1.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 JavaOneSM 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 • • • • • Leverage J2SE 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/aboutJava/communityprocess/edr/jsr222 16 | 2004 JavaOneSM Conference | Session 2841 The Castor Project http://www.castor.org/ • Can map existing classes to XML • XML documents can be unmarshalled directly into • • • • 17 JavaBeans components without preconfigured mapping Likewise, any JavaBeans 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 XML documents can be unmarshalled into existing objects to save memory Reflection based, but able to call custom getters and setters as well | 2004 JavaOneSM Conference | Session 2841 Castor, cont. • Generated classes are plain JavaBeans • • • • 18 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 FieldHandlers for extensibility Supports optional validation including invoking the validator by hand | 2004 JavaOneSM 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 • Supports all of XML Schema • Provides full schema object model API • Preserves the full XML Infoset • Can validate after any change to the objects 19 | 2004 JavaOneSM Conference | Session 2841 XMLBeans, cont. • Generated code extends XML base classes with special XML/Schema features ─ Provides access to XmlCursor 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 JavaOneSM Conference | Session 2841 JiBX http://www.jibx.org/ • JiBX 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 3c release in widespread production use 21 | 2004 JavaOneSM Conference | Session 2841 JiBX 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 JavaOneSM 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 JavaOneSM Conference | Session 2841 Scenario • I’m working on an application server or • • • • 24 deployment tool I am given a J2EE 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 J2EE Connector 1.5 deployment descriptor (ra.xml) This is a complex set of schemas! | 2004 JavaOneSM Conference | Session 2841 J2EE 1.4 Schemas • • • • • • • • • • • 25 application_1_4.xsd application-client_1_4.xsd connector_1_5.xsd ejb-jar_2_1.xsd j2ee_1_4.xsd j2ee_web_services_1_1.xsd j2ee_web_services_client_1_1.xsd jsp_2_0.xsd web-app_2_4.xsd web-jsptaglibrary_2_0.xsd xml.xsd | 2004 JavaOneSM Conference | Session 2841 Sample Deployment Descriptor (ra.xml) <?xml version="1.0" encoding="UTF-8" ?> <connector xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/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 v1.0</eis-type> <resourceadapter-version>1.0</resourceadapter-version> <resourceadapter> <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>HostName</config-property-name> <config-property-type>java.lang.String</config-property-type> </config-property> <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> <messageadapter> <messagelistener> <messagelistener-type>com.chariotsolutions.rfid.event.RFIDListener</messagelistener-type> <activationspec> <activationspec-class>com.chariotsolutions.rfid.ra.in.ScanSpec</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> </resourceadapter> </connector> <description>…</description> <display-name>…</display-name> … </connector> 26 | 2004 JavaOneSM 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 JavaOneSM 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 JavaOneSM Conference | Session 2841 XMLBeans Usage ConnectorDocument doc = ConnectorDocument.Factory.parse(new FileReader("ra.xml")); ConnectorType con = doc.getConnector(); System.out.println("Connector: "+con); System.out.println("Description: " +con.getDescriptionArray()[0].getStringValue()); System.out.println("Display Name: " +con.getDisplayNameArray()[0].getStringValue()); • No casts! • Generated code has interface/implementation separation 29 | 2004 JavaOneSM 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 J2EE schemas • Generates Java code for us to compile 30 | 2004 JavaOneSM Conference | Session 2841 JAXB Usage JAXBContext jc = JAXBContext.newInstance( "com.sun.java.xml.ns.j2ee" ); Unmarshaller u = jc.createUnmarshaller(); Connector con = (Connector)u.unmarshal(new FileInputStream( "ra.xml" ) ); System.out.println("Connector: "+con); System.out.println("Description: " +((DescriptionType)con.getDescription().get(0)).getValue()); System.out.println("Display Name: " +((DisplayNameType)con.getDisplayName().get(0)).getValue()); • Needed to cast from a List • Generated code has interface/implementation separation with very clean interfaces 31 | 2004 JavaOneSM Conference | Session 2841 Castor Schema Compiler export CASTOR_HOME=/usr/local/java/castor-0.9.5.3 export PATH=$PATH:$CASTOR_HOME export CLASSPATH=.../xercesImpl.jar sourceGen -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 JavaOneSM Conference | Session 2841 Castor Usage Connector con = (Connector) Connector.unmarshal(new FileReader("ra.xml")); System.out.println("Connector: "+con); System.out.println("Description: " +con.getDescriptionGroup().getDescription()[0].getCont ent()); System.out.println("Display Name: " +con.getDescriptionGroup().getDisplayName()[0].getCont ent()); • No casts! • Generated objects with their own marshall/unmarshall methods 33 | 2004 JavaOneSM Conference | Session 2841 JiBX Schema Compiler • No such thing! • I wrote my own POJOs instead public class Connector { private String description; private String displayName; //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 JavaOneSM Conference | Session 2841 JiBX Mapping File <binding> <mapping name="connector" class="example.jibx.Connector"> <namespace uri="http://java.sun.com/xml/ns/j2ee" default="elements" /> <value name="description" field="description" /> <value name="display-name" field="displayName" /> <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 JavaOneSM Conference | Session 2841 JiBX Binding Tool export JIBX_HOME=/usr/local/java/jibx-beta3c export CLASSPATH=$JIBX_HOME/lib/bcel.jar:$JIBX_HOME/lib/ jibx-bind.jar:$JIBX_HOME/lib/jibxrun.jar:$JIBX_HOME/lib/xpp3.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 JavaOneSM Conference | Session 2841 JiBX Usage IBindingFactory bfact = BindingDirectory.getFactory(Connector.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); Object obj = uctx.unmarshalDocument(new FileInputStream("ra.xml"), null); Connector con = (Connector) obj; System.out.println("Connector: "+con); System.out.println("Description: "+con.getDescription()); System.out.println("Display Name: " +con.getDisplayName()); • I get to use my lovely POJOs (bugs and all!) • Use JiBX API calls to marshall/unmarshall 37 | 2004 JavaOneSM 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 JavaOneSM 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 JavaOneSM 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 JavaOneSM 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 for on-the-fly mapping 41 | 2004 JavaOneSM Conference | Session 2841 JiBX 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 JavaOneSM 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 JavaOneSM 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 JavaOneSM Conference | Session 2841 Java to XML Binding Tools JAXB, Castor, XMLBeans, JiBX Aaron Mulder 45 | 2004 JavaOneSM Conference | Session 2841 java.sun.com/javaone/sf