package com.drighetto.jaxb.test;
import com.drighetto.jaxb.MarshallerListener;
import com.drighetto.jaxb.UnmarshallerListener;
import com.drighetto.jaxb.vo.Catalog;
import com.drighetto.jaxb.vo.ObjectFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.xml.XMLConstants;
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.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.util.GregorianCalendar;
/**
* Simple test class showing sample of use of JAXB<br>
* <br>
* <b>The JAXBContext class is thread safe, but the Marshaller, Unmarshaller,
* and Validator classes are not thread safe.</b>
*
* <br>
* <i>Dealing with large documents</i> :
* https://jaxb.dev.java.net/guide/Dealing_with_large_documents.html
*
* @author Dominique RIGHETTO (dominique.righetto@logica.com)
*
*/
public class MainTest {
/** JAXB Context */
private static JAXBContext context = null;
/**
* Initialize the test suite creating the JAXB context...
*
* @throws javax.xml.bind.JAXBException
*/
@BeforeClass
public static void initTestSuite() throws JAXBException {
context = JAXBContext.newInstance(Catalog.class);
}
/**
* Unmarshall XML file to Object
*/
@SuppressWarnings("boxing")
@Test
public void sampleUnmarshalling() {
try {
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Unmarshall XML to Object
Catalog catalog = (Catalog) unmarshaller.unmarshal(new File("books.xml"));
// Display object infos to valide unmarshalling
System.out.printf("Books count : %s\n", catalog.getBook().size());
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
/**
* Unmarshall XML file to Object and show behavior of the default value for
* a element
*/
@Test
public void sampleUnmarshallingUsingElementDefaultValue() {
try {
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Unmarshall XML to Object
Catalog catalog = (Catalog) unmarshaller.unmarshal(new File("books.xml"));
// Display object infos to valide unmarshalling
System.out.printf("Books description of book[0] : %s\n", catalog.getBook().get(0).getDescription());
System.out.printf("Books description of book[1] : %s\n", catalog.getBook().get(1).getDescription());
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
/**
* Marshall Object to XML file
*/
@SuppressWarnings("static-access")
@Test
public void sampleMarshalling() {
try {
// Create an Marshaller
Marshaller marshaller = context.createMarshaller();
// Create an object using ObjectFactory class generated by XJC
// during
// mapping generation
ObjectFactory factory = new ObjectFactory();
Catalog catalog = factory.createCatalog();
Catalog.Book book = factory.createCatalogBook();
book.setAuthor("Dominique");
book.setDescription("Spring par la pratique");
book.setGenre("IT");
book.setId("bk155");
book.setPrice(22.50f);
book.setTitle("Spring");
book.setAvailable(Boolean.TRUE);
book.setPublishDate(DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance()));
catalog.getBook().add(book);
// Marshall Object to XML file
marshaller.marshal(catalog, new File("books_sampleMarshalling.xml"));
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
/**
* Marshall Object to XML and after unmarshall the same XML to a Object in
* order to show use of Java Type Adapter
*/
@SuppressWarnings( { "boxing", "static-access" })
@Test
public void sampleJavaTypeAdapter() {
File sampleFile = new File("books_sampleJavaTypeAdapter.xml");
try {
/* Step 1 : Marshall Object to XML */
// Create an Marshaller
Marshaller marshaller = context.createMarshaller();
// Create an object using ObjectFactory class generated by XJC
// during
// mapping generation
ObjectFactory factory = new ObjectFactory();
Catalog catalog = factory.createCatalog();
Catalog.Book book = factory.createCatalogBook();
book.setAuthor("Dominique");
book.setDescription("Spring par la pratique");
book.setGenre("IT");
book.setId("bk155");
book.setPrice(22.50f);
book.setTitle("Spring");
book.setAvailable(Boolean.TRUE);
book.setPublishDate(DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance()));
catalog.getBook().add(book);
// Marshall Object to XML file
marshaller.marshal(catalog, sampleFile);
// Save "catalog" object hash code in order to check that object
// reference are different before and after unmarshalling
int hcBefore = catalog.hashCode();
/* Step 2 : Unmarshall XML to Object */
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Unmarshall XML to Object
catalog = (Catalog) unmarshaller.unmarshal(sampleFile);
/* Step 3 : Check behavior of the "StockAdapter" adapter */
Assert.assertFalse((hcBefore == catalog.hashCode()));
Assert.assertNotNull(catalog);
Assert.assertEquals(catalog.getBook().size(), 1);
Assert.assertNotNull(catalog.getBook().get(0));
Assert.assertTrue(catalog.getBook().get(0).isAvailable());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
/**
* Unmarshall XML to Object with XML validation using XSD schema, stop
* unmarshalling on validation error...
*
* @throws java.lang.Exception
*/
@Test(expected = UnmarshalException.class)
public void sampleUnmarshallingWithValidation() throws Exception {
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Specify the XSD shema that the Unmarshaller will use
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("books.xsd"));
unmarshaller.setSchema(schema);
// Unmarshall XML to Object
unmarshaller.unmarshal(new File("books_sampleUnmarshallingWithValidation.xml"));
// If we reach this point the test failed...
Assert.fail("This test must throw a SAXException because the XML is invalid !!!");
}
/**
* Show marshalling and unmarshalling listeners
*/
@SuppressWarnings("static-access")
@Test
public void sampleListener() {
File sampleFile = new File("books_sampleListener.xml");
try {
/* Step 1 : Marshall Object to XML */
// Create an Marshaller
Marshaller marshaller = context.createMarshaller();
// Set listener
marshaller.setListener(new MarshallerListener());
// Create an object using ObjectFactory class generated by XJC
// during
// mapping generation
ObjectFactory factory = new ObjectFactory();
Catalog catalog = factory.createCatalog();
Catalog.Book book = factory.createCatalogBook();
book.setAuthor("Dominique");
book.setDescription("Spring par la pratique");
book.setGenre("IT");
book.setId("bk155");
book.setPrice(22.50f);
book.setTitle("Spring");
book.setAvailable(Boolean.TRUE);
book.setPublishDate(DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance()));
catalog.getBook().add(book);
// Marshall Object to XML file
marshaller.marshal(catalog, sampleFile);
// Save "catalog" object hash code in order to check that object
// reference are different before and after unmarshalling
@SuppressWarnings("unused")
int hcBefore = catalog.hashCode();
/* Step 2 : Unmarshall XML to Object */
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Set listener
unmarshaller.setListener(new UnmarshallerListener());
// Unmarshall XML to Object
catalog = (Catalog) unmarshaller.unmarshal(sampleFile);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}