The Java EE 5 Tutorial

Unmarshal Validate Example

The Unmarshal Validate example demonstrates how to enable validation during unmarshalling. Note that JAXB provides functions for validation during unmarshalling but not during marshalling. Validation is explained in more detail in More about Validation.

  1. The tut-install/javaeetutorial5/examples/jaxb/unmarshal-validate/src/unmarshalvalidate/ class declares imports for three standard Java classes plus seven JAXB binding framework classes and the primer.po package:

    import java.math.BigDecimal;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.UnmarshalException;
    import javax.xml.bind.Unmarshaller;
    import javax.xml.bind.ValidationEvent;
    import javax.xml.bind.util.ValidationEventCollector;
    import primer.po.*;
  2. A JAXBContext instance is created for handling classes generated in primer.po.

    JAXBContext jc = JAXBContext.newInstance( "primer.po" );
  3. An Unmarshaller instance is created.

    Unmarshaller u = jc.createUnmarshaller();
  4. The default JAXB Unmarshaller ValidationEventHandler is enabled to send to validation warnings and errors to system.out. The default configuration causes the unmarshal operation to fail upon encountering the first validation error.

    u.setValidating( true );
  5. An attempt is made to unmarshal po.xml into a Java content tree. For the purposes of this example, the po.xml contains a deliberate error.

    PurchaseOrder po = (PurchaseOrder)u.unmarshal( new FileInputStream("po.xml"));
  6. The default validation event handler processes a validation error, generates output to system.out, and then an exception is thrown.

    } catch( UnmarshalException ue ) {
        System.out.println( "Caught UnmarshalException" );
    } catch( JAXBException je ) { 
    } catch( IOException ioe ) {

Building and Running the Unmarshal Validate Example Using NetBeans IDE

Follow these instructions to build and run the Unmarshal Validate example on your Application Server instance using the NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

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

  3. Select the unmarshal-validate folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click the unmarshal-validate project and select Run.

Building and Running the Unmarshal Validate Example Using Ant

To compile and run the Unmarshal Validate example using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/jaxb/unmarshal-validate/ directory and type the following:

ant runapp