Thursday, 8 March 2012

JAVAEE5-JAXB examples solution example1

The JAVAEE5 tutorial at http://docs.oracle.com/javaee/5/tutorial/doc/index.html has dedicated a directory for JAXB examples. Most of the examples provided here work OK after a while of effort spent.

This blog entry will solve the worst example among these JAXB examples and provide a sample approach to solve the other simpler ones. Although the example belongs to the owners of the URL sited above the solution which makes it work belongs to me. I happily provide every detail of my solution here to the possibly interested people.

You can also contact me the working solutions of the other examples which I may consequently send you by e-mail(arsaral(at)yahoo.com).


J2s-create-marshall example of JAVAEE5 tutorial



Main.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import cardfile.BusinessCard;
import cardfile.Address;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import javax.xml.bind.ValidationEventLocator;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import org.xml.sax.SAXException;


public class Main {
public static void main(String[] args) throws Exception {
final File f = new File("src/bcard.xml");

// Illustrate two methods to create JAXBContext for j2s binding.
// (1) by root classes newInstance(Class ...)
JAXBContext context1 = JAXBContext.newInstance(BusinessCard.class);

// (2) by package, requires jaxb.index file in package cardfile.
// newInstance(String packageNames)
JAXBContext context2 = JAXBContext.newInstance("cardfile");

Marshaller m = context1.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(
getCard(),
System.out);

// illustrate optional unmarshal validation.
Marshaller m2 = context1.createMarshaller();
m2.marshal(
getCard(),
new FileOutputStream(f));

Unmarshaller um = context2.createUnmarshaller();
um.setSchema(getSchema("cardfile/schema1.xsd"));

Object bce = um.unmarshal(f);
m.marshal(bce, System.out);
}

/** returns a JAXP 1.3 schema by parsing the specified resource. */
static Schema getSchema(String schemaResourceName)
throws SAXException {
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

try {
URL schemaURL = Main.class.getResource(schemaResourceName);

return sf.newSchema(schemaURL);
} catch (SAXException se) {
// this can only happen if there's a deployment error and the resource is missing.
throw se;
}
}

private static BusinessCard getCard() {
return new BusinessCard(
"John Doe",
"Sr. Widget Designer",
"Acme, Inc.",
new Address(
null,
"123 Widget Way",
"Anytown",
"MA",
(short) 12345),
"123.456.7890",
null,
"123.456.7891",
"John.Doe@Acme.ORG");
}
}

Bcard.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <businessCard>
- <address>
<city>Anytown</city>
<state>MA</state>
<street>123 Widget Way</street>
<zip>12345</zip>
</address>
<company>Acme, Inc.</company>
<email>John.Doe@Acme.ORG</email>
<fax>123.456.7891</fax>
<name>John Doe</name>
<phone>123.456.7890</phone>
<title>Sr. Widget Designer</title>
</businessCard>

Cardfile/address.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.*;


@XmlType
public class Address {
private String city;
private String name;
private String state;
private String street;
private short zip;

public Address() {
}

public Address(
String name,
String street,
String city,
String state,
short zip) {
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public short getZip() {
return zip;
}

public void setZip(short zip) {
this.zip = zip;
}

public String toString() {
StringBuilder s = new StringBuilder();

if (name != null) {
s.append(name)
.append('\n');
}

s.append(street)
.append('\n')
.append(city)
.append(", ")
.append(state)
.append(" ")
.append(zip);

return s.toString();
}
}


Cardfile/BusinessCard.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.*;


@XmlRootElement
public class BusinessCard {
private Address address;
private String cellPhone;
private String company;
private String email;
private String fax;
private String name;
private String phone;
private String title;

public BusinessCard() {
}

public BusinessCard(
String name,
String title,
String company,
Address address,
String phone,
String cellPhone,
String fax,
String email) {
this.name = name;
this.title = title;
this.company = company;
this.address = address;
this.phone = phone;
this.cellPhone = cellPhone;
this.fax = fax;
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCompany() {
return company;
}

public void setCompany(String company) {
this.company = company;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getFax() {
return fax;
}

public void setFax(String fax) {
this.fax = fax;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCellPhone() {
return cellPhone;
}

public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}

public String toString() {
StringBuilder s = new StringBuilder();

if (name != null) {
s.append(name)
.append('\n');
}

if (title != null) {
s.append(title)
.append('\n');
}

if (company != null) {
s.append(company)
.append('\n');
}

if (address != null) {
s.append(address.toString())
.append('\n');
}

if (phone != null) {
s.append("phone: ")
.append(phone)
.append('\n');
}

if (cellPhone != null) {
s.append("cell: ")
.append(cellPhone)
.append('\n');
}

if (fax != null) {
s.append("fax: ")
.append(fax)
.append('\n');
}

if (email != null) {
s.append(email)
.append('\n');
}

return s.toString();
}
}

Cardfile/ObjectFactory.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.03.06 at 08:51:41 PM EET
//


package cardfile;

import javax.xml.bind.annotation.XmlRegistry;


/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {


/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
*
*/
public ObjectFactory() {
}

/**
* Create an instance of {@link Contact }
*
*/
public Address createAddress() {
return new Address();
}

/**
* Create an instance of {@link AddressBook }
*
*/
public BusinessCard createBusinessCard() {
return new BusinessCard();
}

}

Cardfile/jaxb.index
BusinessCard
Address

Cardfile/package-info.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.XmlAccessorType;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;

cardfile/schema1.xsd
<?xml version="1.0"?>

<!--
Copyright 2011 ali R+ SARAL
Please use this freely making sure that you indicate my name.
-->

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">


<xs:element name="businessCard">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="Address"/>
<!--xs:element name="cellPhone" type="xs:string" /-->
<xs:element name="company" type="xs:string" />
<xs:element name="email" type="xs:string" />
<xs:element name="fax" type="xs:string" />
<xs:element name="name" type="xs:string" />
<xs:element name="phone" type="xs:string" />
<xs:element name="title" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="Address">
<xs:sequence>
<!--xs:element name="name" type="xs:string"/-->
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="zip" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

The solutions for the other JAVAEE5 – JAXB examples are available from
Arsaral(at)yahoo.com.

Kind regards.

Ali R+ SARAL