Serialize Java Data Objects to XML (Continued)
If we edit the XML file so the property name is x instead of s, to simulate an old program reading an ostensibly newer XML file:
<void property="x">
<string>goodbye</string>
</void>
then the XMLDecoder emits an exception warning to System.err and continues. Your users will see:
"java.lang.NoSuchMethodException:
<unbound>=Stuff0.setX(
"goodbye"); Continuing ... "
The ReadStuffBetter program (see Listing 2) and this WarningListener:
package xmlpersist;
import java.beans.
ExceptionListener;
public class WarningListener
implements ExceptionListener {
public void exceptionThrown(
Exception e) {
System.out.println(
"Time to update your software");
}
}
show how to trap these messages from the decoder with a listener; then you can present your users with a more relevant message like "Time to upgrade!" No doubt, you'll want to log the message in some way. Encoder errors usually mean that what you're saving doesn't have an empty constructor or follow other bean conventions. You can listen to the encoder, too, but once you've debugged the encoding it seems more likely in the field that errors will occur during decoding as various versions are in use. The error listener must be passed in as an argument to the decoder constructor. The middle argument is the owner of the stream and sometimes used for calling methods on the owner during the decoding process. It is not relevant for this example and can be set to null.
Save Collections
If you have a set of old XML files that were created by different users and you cannot easily create them in the "new and improved" format, you can still read in the old ones. Just ignore warning messages and then write them out in the new format. If necessary, you could write an upgrade program using standard XML parsers to read in the old XML format and convert it to the new format.
Java Collections aren't beans, but the encoder knows about them and can save them easily. The LessSimple.java example (see Listing 3) shows how to save items in a HashMap, which produces this XML file:
<?xml version="1.0" encoding=
"UTF-8"?>
<java version="1.4.1" class=
"java.beans.XMLDecoder">
<object class=
"java.util.HashMap">
<void method="put">
<string>item1</string>
<object id="Stuff0" class=
"xmlpersist.Stuff">
<void property="k">
<int>3</int>
</void>
<void property="s">
<string>goodbye</string>
</void>
</object>
</void>
<void method="put">
<string>item2</string>
<object idref="Stuff0"/>
</void>
</object>
</java>
Back to top
|