Skip to main content

A complete working example

3 replies [Last post]
kirillcool
Offline
Joined: 2004-11-17
Points: 0

As https://jaxb.dev.java.net/ri20-ea.html (Hello world) example is still incomplete, here is the complete walk-through for running JAXB 2.0.

This work is being done for the BindMark project (http://bindmark.dev.java.net/). The schema can be found at https://bindmark.dev.java.net/files/documents/2714/10536/schema.xsd.

1. Copy the downloaded binary to a directory of your choice.
2. Execute the downloaded class file as: java -cp . wsisampleapp11
3. Scroll down and click "Accept" button. In the same directory you will have the JAXB 2.0 files. The important directory is lib. You will need jaxb-api.jar, jsr173_api.jar, and jaxb-impl.jar.
4. Run this command to generate classes: java -jar jaxb-xjc.jar abc.xsd. The generator creates a directory called generated with 8 Java files. The two important files are ObjectFactory and Organization. The second one represents the root object of the schema.
5. Create a NetBeans project (Eclipse 3.1M4 fails with internal compiler error on compiling the annotated classes).
6. Compile the generated classes. You'll need to add the above three jars to successfully compile.

Here is the sample code for marshalling and unmarshalling:
[pre]
package check;

import generated.*;
import java.io.*;
import java.math.BigInteger;
import javax.xml.bind.*;

public class CheckJaxb2 {

public CheckJaxb2() {
}

public static String marshal() {
try {
ObjectFactory oFact = new ObjectFactory();
Organization org = oFact.createOrganization();
HeadType head = oFact.createHeadType();
PersonType person = oFact.createPersonType();
person.setId(oFact.createId(new BigInteger("1")));
person.setName(oFact.createName("Alex"));
head.setPerson(person);
org.setHead(head);

JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
CharArrayWriter caw = new CharArrayWriter();
marshaller.marshal(org, new PrintWriter(caw));
return caw.toString();
} catch (Exception exc) {
exc.printStackTrace();
return null;
}
}

public static void unmarshal(String str) {
try {
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setValidating(true);
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
Organization instance = (Organization)unmarshaller.unmarshal(bais);
HeadType head = instance.getHead();
PersonType person = head.getPerson();
JAXBElement id = person.getId();
JAXBElement name = person.getName();
System.out.println("head : " + id.getValue().intValue() + ", " + name.getValue());
} catch (Exception exc) {
exc.printStackTrace();
}
}

public static void main(String[] args) {
String xml = marshal();
System.out.println(xml);
unmarshal(xml);
}

}
[/pre]

The result should be:
[pre]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

Alex
1

head : 1, Alex
[/pre]

Important notes:
1. The JAXBContext should be created with the name of the corresponding ObjectFactory and not the hierarchy root class as written in the Hello world example.
2. Each primitive attribute can be created only via ObjectFactory method.
3. The getter functions for attributes are stronlgy typed, both for primitive and for collections:
[pre]
public java.util.List getPerson();
[/pre]

Over the weekend i will provide the relative comparison of JAXB and JAXB 2.0 performance.

Kirill
http://weblogs.java.net/blog/kirillcool

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kohsuke
Offline
Joined: 2003-06-09
Points: 0

Cool. Do you mind if I take this note, make it an HTML, and put it on the web site?

kirillcool
Offline
Joined: 2004-11-17
Points: 0

Be my guest.
The xsd is:
[pre]















































[/pre]

The code for generating organization with a couple of hierarchy suborganizations:
[pre]
public final Organization createHierarchy(final int param1) {

final Organization org = objFactory.createOrganization();
final HeadType head = objFactory.createHeadType();
final PersonType headPerson = objFactory.createPersonType();
headPerson.setId(objFactory.createId(BigInteger.valueOf(100L)));
headPerson.setName(objFactory.createName("Bob" + param1));
head.setPerson(headPerson);
org.setHead(head);

final SecretaryType secretary = objFactory.createSecretaryType();
final PersonType secrPerson = objFactory.createPersonType();
secrPerson.setId(objFactory.createId(BigInteger.valueOf(101L)));
secrPerson.setName(objFactory.createName("Allis" + param1));
secretary.setPerson(secrPerson);
org.setSecretary(secretary);

final SuborganizationType sub1 = objFactory.createSuborganizationType();
final HeadType head1 = objFactory.createHeadType();
final PersonType headPerson1 = objFactory.createPersonType();
headPerson1.setId(objFactory.createId(BigInteger.valueOf(102L)));
headPerson1.setName(objFactory.createName("Mike" + param1));
head1.setPerson(headPerson1);
sub1.setHead(head1);

final StaffType staff = objFactory.createStaffType();
final String[] names = new String[]{"Ron", "Hewey", "Dan"};
for (int j = 0; j < names.length; j++) {
final PersonType person = objFactory.createPersonType();
person.setId(objFactory.createId(BigInteger.valueOf(
(long) (110 + param1 * 10 + j))));
person.setName(objFactory.createName(names[j] + param1));
staff.getPerson().add(person);
}
sub1.setStaff(staff);

final SuborganizationType sub2 = objFactory.createSuborganizationType();
final HeadType head2 = objFactory.createHeadType();
final PersonType headPerson2 = objFactory.createPersonType();
headPerson2.setId(objFactory.createId(BigInteger.valueOf(103L)));
headPerson2.setName(objFactory.createName("Jon" + param1));
head2.setPerson(headPerson2);
sub2.setHead(head2);

final StaffType staff2 = objFactory.createStaffType();
final String[] names2 = new String[]{"Drake", "Lily", "Shin"};
for (int j = 0; j < names2.length; j++) {
final PersonType person = objFactory.createPersonType();
person.setId(objFactory.createId(
BigInteger.valueOf((long) (210 + param1 * 10 + j))));
person.setName(objFactory.createName(names2[j] + param1));
staff2.getPerson().add(person);
}
sub2.setStaff(staff2);

sub1.setSuborganization(sub2);

final PartsType parts = objFactory.createPartsType();
parts.setSuborganization(sub1);

org.setParts(parts);

return org;
}
[/pre]

The code for marshalling
[pre]
javax.xml.bind.Marshaller marshaller;
try {
final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
marshaller = jc.createMarshaller();
marshaller.setProperty(
javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.valueOf(true));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Organization org = createHierarchy(2);
marshaller.marshal(org, baos);
String orgXml = new String(baos.getBytes());
}
catch (Exception exc) {
exc.printStackTrace();
}
}
[/pre]

The code for unmarshalling:
[pre]
javax.xml.bind.Unmarshaller unmarshaller;
try {
final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = jc.createUnmarshaller();
unmarshaller.setValidating(false);

byte[] bytes = xmlString.getBytes();
final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
final Organization organization = (Organization) this.unmarshaller .unmarshal(bais);
// print id of organization head
System.out.println(org.getHead().getPerson().getId().getValue().intValue());
}
catch (Exception exc) {
exc.printStackTrace();
}
}
[/pre]

kirillcool
Offline
Joined: 2004-11-17
Points: 0

Two little things:
1. There should be no space after [b]xmlns:[/b] in the schema, it's just that without this space the weblog software makes this emoticon :x
2. You may create the project in NetBeans 4.0+ or IntelliJ 4.5+. Eclipse 3.1M4 uses its own compiler which is not fully Tiger-compliant.