10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

import javax.xml.bind.Marshaller;<br />

import javax.xml.bind.UnmarshalException;<br />

import javax.xml.bind.Unmarshaller;<br />

import javax.xml.bind.ValidationEvent;<br />

import javax.xml.bind.util.ValidationEventCollector;<br />

import primer.po.*;<br />

2. A JAXBContext instance is created for handling classes generated in primer.po.<br />

JAXBContext jc = JAXBContext.newInstance( "primer.po" );<br />

3. An Unmarshaller instance is created.<br />

Unmarshaller u = jc.createUnmarshaller();<br />

4. <strong>The</strong> default JAXB Unmarshaller ValidationEventHandler is enabled to send to validation<br />

warnings and errors to system.out. <strong>The</strong> default configuration causes the unmarshal<br />

operation to fail upon encountering the first validation error.<br />

u.setValidating( true );<br />

5. An attempt is made to unmarshal po.xml into a <strong>Java</strong> content tree. For the purposes of this<br />

example, the po.xml contains a deliberate error.<br />

PurchaseOrder po = (PurchaseOrder)u.unmarshal( new FileInputStream("po.xml"));<br />

6. <strong>The</strong> default validation event handler processes a validation error, generates output to<br />

system.out, and then an exception is thrown.<br />

} catch( UnmarshalException ue ) {<br />

System.out.println( "Caught UnmarshalException" );<br />

} catch( JAXBException je ) {<br />

je.printStackTrace();<br />

} catch( IOException ioe ) {<br />

ioe.printStackTrace();<br />

}<br />

Building and Running the UnmarshalValidate Example Using<br />

NetBeans IDE<br />

Basic JAXB Examples<br />

Follow these instructions to build and run the Unmarshal Validate example on your<br />

Application Server instance using NetBeans IDE.<br />

1. In NetBeans IDE, select File→Open Project.<br />

2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxb/.<br />

3. Select the unmarshal-validate folder.<br />

4. Select the Open as Main Project check box.<br />

5. Click Open Project.<br />

6. Right-click the unmarshal-validate project and select Run.<br />

Chapter 17 • Binding between XML Schema and <strong>Java</strong> Classes 511

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!