Tutorial : Unmarshaling and Marshaling Data : Implementation
Implementation
The JAXB Insurance Profile System (JAXBIPS) sample application
implements several features defined in the Oracle JAXB specifications, including:
Usage of the JAXB
class generator
Usage of the Marshaler and Unmarshaler classes
Marshaling and Unmarshaling from File and StreamSource
Using JAXB in conjunction with XMLType
Binding of XML Schema and Complex types
Using collection types in schema definition (Multiple claim
information)
Unmarshal-time validation
This tutorial highlights one of the most important features
of JAXB - Unmarshaling and Marshaling Data. In this section we will look at
how the design decisions for the JAXBIPS are implemented in the application,
by looking at related code snippets.Before writing code, we need to generate
support classes with the help of the Oracle JAXB compiler that is part of the
oracle.xml.jaxb package. In order for us to use this, we need to have the xmlparserv2.jar
in the CLASSPATH:
On the command / shell prompt execute following command:
To describe the XML document structure, we need to have a
schema definition file. Using profile.xsd we build the classes that allow us
to marshal, unmarshal and validate XML document instances against the schema
definition file. The Schema definition file in our case is the profile.xsd.
Marshaling and Unmarshaling - FileSystem
We will now look at the code that marshals the Java instances
into the File System:
public void saveRecord(Record rec) {
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);
String filename = null;
if ( !dirPath.endsWith(".xml"))
filename = dirPath + "/" + currentRecord.getCustomerID() +".xml";
else filename = dirPath;
textArea.append(" Saving file " + filename + "\n");
File f = new File(filename);
f.delete();
//Create a marshaler object
Marshaller m = jc.createMarshaller();
StringWriter swriter = new StringWriter();
//Marshal the record object
m.marshal(rec, swriter);
//Store the marshaled object in the String
String s = swriter.toString();
//Output this String to a file
FileOutputStream fout = new FileOutputStream(filename);
PrintWriter pw = new PrintWriter(fout);
pw.write(s);
//Flush and close file and printWriter
pw.flush();
if (pw != null) {
pw.close();
}
if (fout != null) {
fout.close();
}
textArea.append("Record saved... \n");
} catch (Exception e) {
e.printStackTrace();
}
}
Here's the code that unmarshals the document instances from
the File System:
public void loadSingleRecord() {
textArea.append("This may take some time. Please wait... \n");
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);
//Create an unmarshaler instance
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(true);
textArea.append("\nReading file " + dirPath + "\n");
//Unmarshal the Record object from FileInputStream
Record rec = (Record) u.unmarshal(fileToURL(dirPath));
//Store the object in the list
list.add(rec);
textArea.append("One record loaded.\n Size of the list is " +
list.size() + " \n"
);
} catch (Exception ex) {
textArea.append("There was an error while parsing \n" + dirPath +
"\nThis file will be ignored. \n"
);
textArea.append(
"Please note that this error is thrown when the source XML does not "
);
textArea.append(
"confirm to the Profile Record \nSchema definition. The error is given below \n"
);
textArea.append(ex.toString() +"\n\n");
} finally {
}
}
Marshaling and Unmarshaling - Database
Here's the code to marshal and save the records into the
database:
public void saveRecord(Record rec) {
Statement st = null;
JAXBContext jc = null;
Marshaller m = null;
OraclePreparedStatement stmt = null;
try {
st = con.createStatement();
textArea.append("Saving record with customer id " +
rec.getCustomerID() + " \n"
);
//Delete previous record if any
st.execute(
"DELETE profile_tab pt WHERE pt.c1.extract('//Record/@CustomerID').getStringVal() ='" +
rec.getCustomerID() + "'"
);
if (st != null) {
st.close();
}
//Insert updated record
stmt = (OraclePreparedStatement) con.prepareStatement(
"INSERT INTO profile_tab VALUES (XMLType.CreateXML(?).CreateSchemaBasedXML('http://jaxbderived.profile/profile.xsd'))"
);
//Create JAXBContext instance
jc = JAXBContext.newInstance("jaxbderived.profile");
//Create Marshaler instance
m = jc.createMarshaller();
StringWriter swriter = new StringWriter();
//Marshal record object to a StringWriter
m.marshal(rec, swriter);
//Set the parameter
stmt.setString(1, swriter.toString());
//Execute the insert statement
stmt.execute();
con.commit();
textArea.append("One record has been added / updated \n");
} catch (Exception e) {
textArea.append(
"There was problem while adding / updating profile record in the database\n"
);
textArea.append("Error message is \n");
textArea.append(e.toString() + "\n");
} finally {
try {
if (st != null) {
st.close();
}
} catch (Exception e1) {
}
}
}
Here is the code that unmarshals the document instances from
the database:
private void createListFromDatabase() {
// Create a list instance
list = Collections.synchronizedList(new ArrayList());
Statement st = null;
ResultSet rs = null;
Unmarshaller u = null;
JAXBContext jc = null;
try {
//Create a JAXBContext instance
jc = JAXBContext.newInstance("jaxbderived.profile");
//Create unmarshaler object
u = jc.createUnmarshaller();
u.setValidating(false);
textArea.append("Reading records from the database \n");
st = con.createStatement();
//Select all records from profile_tab
rs = st.executeQuery(
"SELECT pt.c1.getStringVal() FROM profile_tab pt"
);
int i = 0;
while (rs.next()) {
//Retrieve the XMLType object as a String
String s = rs.getString(1);
//Get byte array from the String object
byte[] bytes = s.getBytes();
//Create ByteArrayInputStream object
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try {
//Unmarshal the record
Record rec = (Record) u.unmarshal(new StreamSource(bais));
//Add the record to the list
list.add(rec);
} catch (Exception e1) {
textArea.append("There was an error while parsing " + i +
" th record from the result set \n" +
" This record has been skipped"
);
}
i++;
}
textArea.append("Number of records retrieved from the database : " +
list.size() + "\n"
);
listiterator = list.listIterator(0);
try {
listiterator.next();
} catch (Exception ex) {
}
if (st != null) {
st.close();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (Exception ex1) {
}
}
}