Download FAQ History |  | API Search Feedback

> ## Basic Examples

> This section describes five basic examples (Unmarshal Read, Modify Marshal, Create Marshal, Unmarshal Validate, Validate-On-Demand) that demonstrate how to:

> - Unmarshal an XML document into a Java content tree and access the data contained within it
> - Modify a Java content tree
> - Use the `ObjectFactory` class to create a Java content tree from scratch and then marshal it to XML data
> - Perform validation during unmarshalling
> - Validate a Java content tree at runtime

> ### Unmarshal Read Example

> The purpose of the Unmarshal Read example is to demonstrate how to unmarshal an XML document into a Java content tree and access the data contained within it.

> 1. The `<``JWSDP_HOME``>/jaxb/samples/unmarshal-read/Main.java` class declares imports for four standard Java classes plus three JAXB binding framework classes and the `primer.po` package:

>     import java.io.FileInputStream
>     import java.io.IOException
>     import java.util.Iterator
>     import java.util.List
>     import javax.xml.bind.JAXBContext
>     import javax.xml.bind.JAXBException
>     import javax.xml.bind.Unmarshaller
>     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. `po.xml` is unmarshalled into a Java content tree comprising objects generated by the JAXB binding compiler into the `primer.po` package.

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

> 5. A simple string is printed to `system.out` to provide a heading for the purchase order invoice.

>     System.out.println( "Ship the following items to: " );

> 6. `get` and `display` methods are used to parse XML content in preparation for output.

>     USAddress address = po.getShipTo();
>         displayAddress( address );
>         Items items = po.getItems();
>         displayItems( items );

> 7. Basic error handling is implemented.

>     } catch( JAXBException je ) {
>         je.printStackTrace();
>     } catch( IOException ioe ) {
>         ioe.printStackTrace();

> 8. The `USAddress` branch of the Java tree is walked, and address information is printed to `system.out`.

>     public static void displayAddress( USAddress address ) {
>         // display the address
>         System.out.println( "\t" + address.getName() );
>         System.out.println( "\t" + address.getStreet() );
>         System.out.println( "\t" + address.getCity() +
>             ", " + address.getState() +
>             " "  + address.getZip() );
>         System.out.println( "\t" + address.getCountry() +
>             "\n");
>     }

> 9. The `Items` list branch is walked, and item information is printed to `system.out`.

>     public static void displayItems( Items items ) {
>         // the items object contains a List of
>         //primer.po.ItemType objects
>         List itemTypeList = items.getItem();

> 10. Walking of the `Items` branch is iterated until all items have been printed.

>     for( Iterator iter = itemTypeList.iterator(); iter.hasNext(); )
>     {
>         Items.ItemType item = (Items.ItemType)iter.next();
>         System.out.println( "\t" + item.getQuantity() +
>           " copies of \"" + item.getProductName() +
>           "\"" );
>     }

> #### Sample Output

> Running `java Main` for this example produces the following output:

>     Ship the following items to:
>        Alice Smith
>        123 Maple Street
>        Cambridge, MA 12345
>        US

>        5 copies of "Nosferatu - Special Edition (1929)"
>        3 copies of "The Mummy (1959)"
>        3 copies of "Godzilla and Mothra: Battle for Earth/Godzilla
>          vs. King Ghidora"

> ### Modify Marshal Example

> The purpose of the Modify Marshal example is to demonstrate how to modify a Java content tree.

> 1. The `<``JWSDP_HOME``>/jaxb/samples/modify-marshal/Main.java` class declares imports for three standard Java classes plus four JAXB binding framework classes and `primer.po` package:

>     import java.io.FileInputStream;
>     import java.io.IOException;
>     import java.math.BigDecimal;
>     import javax.xml.bind.JAXBContext;
>     import javax.xml.bind.JAXBException;
>     import javax.xml.bind.Marshaller;
>     import javax.xml.bind.Unmarshaller;
>     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, and `po.xml` is unmarshalled.

>     Unmarshaller u = jc.createUnmarshaller();
>     PurchaseOrder po =
>         (PurchaseOrder)u.unmarshal(
>             new FileInputStream( "po.xml" ) );

> 4. `set` methods are used to modify information in the `address` branch of the content tree.

>     USAddress address = po.getBillTo();
>     address.setName( "John Bob" );
>     address.setStreet( "242 Main Street" );
>     address.setCity( "Beverly Hills" );
>     address.setState( "CA" );
>     address.setZip( new BigDecimal( "90210" ) );

> 5. A `Marshaller` instance is created, and the updated XML content is marshalled to `system.out`. The `setProperty` API is used to specify output encoding; in this case formatted (human readable) XML format.

>     Marshaller m = jc.createMarshaller();
>     m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE
>     );
>     m.marshal( po, System.out );

> #### Sample Output

> Running `java Main` for this example produces the following output:

>     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
>     <purchaseOrder orderDate="1999-10-20-05:00">
>     <shipTo country="US">
>     <name>Alice Smith</name>
>     <street>123 Maple Street</street>
>     <city>Cambridge</city>
>     <state>MA</state>
>     <zip>12345</zip>
>     </shipTo>
>     <billTo country="US">
>     <name>John Bob</name>
>     <street>242 Main Street</street>
>     <city>Beverly Hills</city>
>     <state>CA</state>
>     <zip>90210</zip>
>     </billTo>
>     <items>
>     <item partNum="242-NO">
>     <productName>Nosferatu - Special Edition (1929)</productName>
>     <quantity>5</quantity>
>     <USPrice>19.99</USPrice>
>     </item>
>     <item partNum="242-MU">
>     <productName>The Mummy (1959)</productName>
>     <quantity>3</quantity>
>     <USPrice>19.98</USPrice>
>     </item>
>     <item partNum="242-GZ">
>     <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs.
>        King Ghidora</productName>
>     <quantity>3</quantity>
>     <USPrice>27.95</USPrice>
>     </item>
>     </items>
>     </purchaseOrder>

> ### Create Marshal Example

> The Create Marshal example demonstrates how to use the `ObjectFactory` class to create a Java content tree from scratch and then marshal it to XML data.

> 1. The `<``JWSDP_HOME``>/jaxb/samples/create-marshal/Main.java` class declares imports for four standard Java classes plus three JAXB binding framework classes and the `primer.po` package:

>     import java.math.BigDecimal;
>     import java.math.BigInteger;
>     import java.util.Calendar;
>     import java.util.List;
>     import javax.xml.bind.JAXBContext;
>     import javax.xml.bind.JAXBException;
>     import javax.xml.bind.Marshaller;
>     import primer.po.*;

> 2. A `JAXBContext` instance is created for handling classes generated in `primer.po`.

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

> 3. The `ObjectFactory` class is used to instantiate a new empty `PurchaseOrder` object.

>     // creating the ObjectFactory
>     ObjectFactory objFactory = new ObjectFactory();

>     // create an empty PurchaseOrder
>     PurchaseOrder po = objFactory.createPurchaseOrder();

> 4. Per the constraints in the `po.xsd` schema, the `PurchaseOrder` object requires a value for the `orderDate` attribute. To satisfy this constraint, the `orderDate` is set using the standard `Calendar.getInstance()` method from `java.util.Calendar`.

>     po.setOrderDate( Calendar.getInstance() );

> 5. The `ObjectFactory` is used to instantiate new empty `USAddress` objects, and the required attributes are set.

>     USAddress shipTo = createUSAddress( "Alice Smith",
>                                   "123 Maple Street",
>                                   "Cambridge",
>                                   "MA",
>                                   "12345" );
>       po.setShipTo( shipTo );

>     USAddress billTo = createUSAddress( "Robert Smith",
>                                   "8 Oak Avenue",
>                                   "Cambridge",
>                                   "MA",
>                                   "12345" );
>     po.setBillTo( billTo );

> 6. The `ObjectFactory` class is used to instantiate a new empty `Items` object.

>     Items items = objFactory.createItems();

> 7. A `get` method is used to get a reference to the `ItemType` list.

>     List itemList = items.getItem();

> 8. `ItemType` objects are created and added to the `Items` list.

>     itemList.add( createItemType(
>         "Nosferatu - Special Edition (1929)",
>                                   new BigInteger( "5" ),
>                                   new BigDecimal( "19.99" ),
>                                   null,
>                                   null,
>                                   "242-NO" ) );
>     itemList.add( createItemType( "The Mummy (1959)",
>                                   new BigInteger( "3" ),
>                                   new BigDecimal( "19.98" ),
>                                   null,
>                                   null,
>                                   "242-MU" ) );
>     itemList.add( createItemType(
>         "Godzilla and Mothra: Battle for Earth/Godzilla vs. King
>     Ghidora",
>                                   new BigInteger( "3" ),
>                                   new BigDecimal( "27.95" ),
>                                   null,
>                                   null,
>                                   "242-GZ" ) );

> 9. The `items` object now contains a list of `ItemType` objects and can be added to the `po` object.

>     po.setItems( items );

> 10. A `Marshaller` instance is created, and the updated XML content is marshalled to `system.out`. The `setProperty` API is used to specify output encoding; in this case formatted (human readable) XML format.

>     Marshaller m = jc.createMarshaller();
>     m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT,
>         Boolean.TRUE );
>     m.marshal( po, System.out );

> 11. An empty `USAddress` object is created and its properties set to comply with the schema constraints.

>     public static USAddress createUSAddress(
>                                      ObjectFactory objFactory,
>                                      String name, String street,
>                                      String city,
>                                      String state,
>                                      String zip )
>             throws JAXBException {

>             // create an empty USAddress objects
>             USAddress address = objFactory.createUSAddress();

>             // set properties on it
>             address.setName( name );
>             address.setStreet( street );
>             address.setCity( city );
>             address.setState( state );
>             address.setZip( new BigDecimal( zip ) );

>             // return it
>             return address;
>         }

> 12. Similar to the previous step, an empty `ItemType` object is created and its properties set to comply with the schema constraints.

>     public static Items.ItemType createItemType( ObjectFactory
>     objFactory,
>                                             String productName,
>                                             BigInteger quantity,
>                                             BigDecimal price,
>                                             String comment,
>                                             Calendar shipDate,
>                                             String partNum )
>             throws JAXBException {

>             // create an empty ItemType object
>             Items.ItemType itemType =
>                 objFactory.createItemsItemType();

>             // set properties on it
>             itemType.setProductName( productName );
>             itemType.setQuantity( quantity );
>             itemType.setUSPrice( price );
>             itemType.setComment( comment );
>             itemType.setShipDate( shipDate );
>             itemType.setPartNum( partNum );

>             // return it
>             return itemType;
>         }

> #### Sample Output

> Running `java Main` for this example produces the following output:

>     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
>     <purchaseOrder orderDate="2002-09-24-05:00">
>     <shipTo>
>     <name>Alice Smith</name>
>     <street>123 Maple Street</street>
>     <city>Cambridge</city>
>     <state>MA</state>
>     <zip>12345</zip>
>     </shipTo>
>     <billTo>
>     <name>Robert Smith</name>
>     <street>8 Oak Avenue</street>
>     <city>Cambridge</city>
>     <state>MA</state>
>     <zip>12345</zip>
>     </billTo>
>     <items>
>     <item partNum="242-NO">
>     <productName>Nosferatu - Special Edition (1929)</productName>
>     <quantity>5</quantity
>     <USPrice>19.99</USPrice>
>     </item>
>     <item partNum="242-MU">
>     <productName>The Mummy (1959)</productName>
>     <quantity>3</quantity>
>     <USPrice>19.98</USPrice>
>     </item>
>     <item partNum="242-GZ">
>     <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs.
>     King Ghidora</productName>
>     <quantity>3</quantity>
>     <USPrice>27.95</USPrice>
>     </item>
>     </items>
>     </purchaseOrder>

> ### Unmarshal Validate Example

> The Unmarshal Validate example demonstrates how to enable validation during unmarshalling (Unmarshal-Time Validation). 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 `<``JWSDP_HOME``>/jaxb/samples/unmarshal-validate/Main.java` class declares imports for three standard Java classes plus seven JAXB binding framework classes and the `primer.po` package:

>     import java.io.FileInputStream;
>     import java.io.IOException;
>     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 ) {
>           je.printStackTrace();
>        } catch( IOException ioe ) {
>           ioe.printStackTrace();

> #### Sample Output

> Running `java Main` for this example produces the following output:

>     DefaultValidationEventHandler: [ERROR]: "-1" does not satisfy
>     the "positiveInteger" type
>     Caught UnmarshalException

> ### Validate-On-Demand Example

> The Validate-On-Demand example demonstrates how to validate a Java content tree at runtime (On-Demand Validation). At any point, client applications can call the `Validator.validate` method on the Java content tree (or any subtree of it). All JAXB Providers are required to support this operation. Validation is explained in more detail in More About Validation.

> 1. The `<``JWSDP_HOME``>/jaxb/samples/ondemand-validate/Main.java` class declares imports for five standard Java classes plus nine JAXB Java classes and the `primer.po` package:

>     import java.io.FileInputStream;
>     import java.io.IOException;
>     import java.math.BigDecimal;
>     import java.math.BigInteger;
>     import java.util.List;
>     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.ValidationException;
>     import javax.xml.bind.Validator;
>     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, and a valid `po.xml` document is unmarshalled into a Java content tree. Note that `po.xml` is valid at this point; invalid data will be added later in this example.

>     Unmarshaller u = jc.createUnmarshaller();
>     PurchaseOrder po =
>        (PurchaseOrder)u.unmarshal( new FileInputStream( "po.xml" )
>     );

> 4. A reference is obtained for the first item in the purchase order.

>     Items items = po.getItems();
>     List itemTypeList = items.getItem();
>     Items.ItemType item = (Items.ItemType)itemTypeList.get( 0 );

> 5. Next, the item quantity is set to an invalid number. When validation is enabled later in this example, this invalid quantity will throw an exception.

>     item.setQuantity( new BigInteger( "-5" ) );

> Note: If `@enableFailFastCheck` was `"true"` and the optional `FailFast` validation method was supported by an implementation, a `TypeConstraintException` would be thrown here. Note that the JAXB implementation does not support the `FailFast` feature. Refer to the JAXB Specification for more information about `FailFast` validation.

> 1. A `Validator` instance is created, and the content tree is validated. Note that the `Validator` class is responsible for managing On-Demand validation, whereas the `Unmarshaller` class is responsible for managing Unmarshal-Time validation during unmarshal operations.

>     Validator v = jc.createValidator();
>     boolean valid = v.validateRoot( po );
>     System.out.println( valid );

> 2. The default validation event handler processes a validation error, generates output to `system.out`, and then an exception is thrown.

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

> #### Sample Output

> Running `java Main` for this example produces the following output:

>     DefaultValidationEventHandler: [ERROR]: "-5" does not satisfy
>     the "positiveInteger" type
>     Caught ValidationException

Download FAQ History |  | API Search Feedback

All of the material in The Java(TM) Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.