Showing posts with label JAXB. Show all posts
Showing posts with label JAXB. Show all posts

Monday, 4 April 2016

What is the default Data type binding ?


XML Schema Type    Java Data Type
------------------------------------------------------------------
xsd:string                     java.lang.String        
xsd:integer                   java.math.BigInteger    
xsd:int                          int                     
xsd:long                       long                    
xsd:short                      short                   
xsd:decimal                  java.math.BigDecimal    
xsd:float                       float                   
xsd:double                   double                  
xsd:boolean                 boolean                 
xsd:byte                       byte                    
xsd:QName                 javax.xml.namespace.QName
xsd:dataTime               java.util.Calendar
xsd:base64Binary       byte[]           
xsd:hexBinary             byte[]           
xsd:unsignedInt          long             
xsd:unsignedShort      int              
xsd:unsignedByte       short            
xsd:time                      java.util.Date   
xsd:date                      java.util.Date   
xsd:anySimpleType    java.lang.String

JAXP vs. JAXB


Whether one chooses JAXP (Java API for XML) or JAXB (Java API for XMLBinding) depends on the requirements of the application.
If one needs only a part of data then one should use the SAX parser because it parses data based on events and is really fast.

On the other hand is the document is not too large and nodes have to be inserted or removed then one should go for a DOM parser which allows the manupulation of the in memory XML file by allowing additions and deletion of nodes from this tree.
If the requirement is to transform the XML document from one format to another then the best choice is JAXP because it has a built in XSLT transformer that allows one to transform XML documents, SAX events and even a DOM tree.

If the document is too large for DOM to handle and also one needs an object reprentation of the XML data then you should use the JAXBAPI. However classes in JAXB do not allow tree manipulation capability and thus they occupy lesser memory footprint.

Another important advantageof JAXB over JAXP is that JAXB makes it mandatory for an XML document to have a DTD which is not necessary in case of JAXP. This ensures that the XML documents that are being parsed are valid documents.
JAXB also allows one to specify how the code is generated from the DTD including the data types that an element binding will accept and return.

However JAXB does not have any capability to transform an XML document into different formats which is available in the JAXP API's.

JAXB 2.0 Improvements over JAXB 1.0


Improvements
  • Support for all W3C XML Schema features.
    (JAXB 1.0 did not specify bindings for some of the W3C XML Schema features.)
  • Support for binding Java-to-XML, with the addition of the javax.xml.bind.annotation package to control this binding.
    (JAXB 1.0 specified the mapping of XML Schema-to-Java, but not Java-to-XML Schema.)
  • A significant reduction in the number of generated schema derived classes.
  • Additional validation capabilities through the JAXP 1.3 validation APIs.
  • Smaller runtime libraries

Differences
  • JAXB 1.0 provided validation at unmarshal time and also enabled on-demand validation on a JAXB content tree.
  • JAXB 2.0 only allows validation at unmarshal and marshal time.

What is Marshalling and how to marshal ?


Content tree may be marshalled by passing it to marshal method of Marshaller object.

javax.xml.bind.Marshaller
An interface that governs the process of serializing Java content trees back into XML data.


Marshalling examples

Marshalling to a File
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
OutputStream os = new FileOutputStream( "genius.xml" );
m.marshal( obj, os );

Marshalling to a OutputStream
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
m.marshal( obj, System.out );

Marshalling to a Writer
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
m.marshal( obj, new PrintWriter( System.out ) );

Marshalling to a javax.xml.transform.StreamResult
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
StreamResult result = new StreamResult( System.out );
m.marshal( obj, result );

What is UnMarshalling and how to unmarshal ?


UnMarshalling

Generates content tree from XML document instance through JAXB binding framework.
Sources for unMarshalling can be: Files/documents, inputStream, String buffers, DOM nodes, SAX Sources.

javax.xml.bind.JAXBContext
  • Provides entry point to the JAXB API and created via newInstance(contextPath)
    contextPath contains a list of Java package names that contain schema derived interfaces and classes :

    JAXBContext 
    jc = JAXBContext.newInstance("com.genius.foo:com.genius.bar");
  • Unmarshaller, Marshaller, Validator object are created from JAXBContext object

javax.xml.bind.Unmarshaller
Java Interface that governs the process of deserializing XML data (XML document instance) into newly created Java content tree.
Optionally, validates XML data as it is unmarshalled.


Unmarshalling Examples

Unmarshalling from a File
// Create JAXBContext object
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
// Create Unmarshaller object
Unmarshaller u = jc.createUnmarshaller();
// Unmarshall a XML document which is in the form of File
Object o = u.unmarshal( new File( "example.xml" ) );

Unmarshalling from an InputStream
InputStream is = new FileInputStream( "example.xml" );
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal( is );

Unmarshalling from a URL
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
URL url = new URL( "http: //genius.prog/example.xml" );
Object o = u.unmarshal( url );

Unmarshalling from a StringBuffer
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
StringBuffer xmlStr = new StringBuffer( "..." );
Object o = u.unmarshal( new StreamSource( new StringReader(xmlStr.toString() ) ) );

Turn off validation during Unmarshalling
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(false);
Object o = u.unmarshal( new File( "example.xml" ) );

What are the goals and usage of JAXB ?


JAXB provides API, tools, and a framework that automate the mapping between XML documents and Java objects.
Provides compiler that compiles XML schema to Java classes.
Provides an efficient and standard way of mapping between XML and Java code.

JAXB is high-level language while JAXP/SAX/DOM are assembly language for XML document management.

What you can do ?
  • Unmarshal XML content (XML document instance) to Java representations.
  • Access, update and validate the Java representation against schema constraints.
  • Marshal the Java representation of the XML content into XML content.


JAXB Design Goals

Easy to use
  • Lower “barrier to entry” to manipulating XML documents within Java programs
  • Don't have to deal with complexities of SAX and DOM

Customizable
  • Sophisticated applications sometimes require fine control over the structure and content of schema-derived classes
  • Allows keeping pace with schema evolution

Portable
  • JAXB components can be replaced without having to make significant changes to the rest of the source code.

Validation on demand
  • Validate the tree against the constraints in the source schema

Clean “round-tripping”
  • Converting a Java content tree to XML content and back to Java content again should result in equivalent Java content trees before and after the conversion.

What are the 2 phases of Binding Process ?



Design time
  • Generate JAXB classes from a source schema
  • Compile the JAXB classes
  • Build an application that uses these classes

Run time (Binding runtime)
  • Unmarshal XML content tree
  • Process (Access & Modify) XML content tree
  • Validate XML content tree
  • Marshal XML content tree