Sharing the Code

Programming stuff that might be useful to others

Using JAXB 2

JAXB is a Java library for converting XML files into Java classes. It’s main use is in web services i.e. using WSDL files to generate Java classes but I also find it very useful for XML configuration files. So instead of transversing an XML configuration file using verbose DOM you transverse it as an object hierarchy instead. Unlike version 1, version 2 uses Java 1.5 generics which makes iterating over collections a lot easier.

1. Download the installation jar from here. Expand releases and select the latest stable version i.e. 2.1.9 and click on the link that says something like JAXB RI 2.1.9
2. Open a console panel and run the jar by typing:
java -jar JAXB2_20081030.jar
your JAR filename might be different
3. Move the newly created directory to someplace more permanent
4. In the lib directory copy the JARs to your project’s lib directory and add them to your project’s Java build path in Eclipse
5. I use Ant to generate the classes from an XML Schema file. The following will output them to src/generated, which you will need to add as a source folder in Eclipse.

build.xml:
[sourcecode language=’xml’]









[/sourcecode]

Snippet from XML Schema file (config.xsd):

[sourcecode language=’xml’]









[/sourcecode]

6. To read or “unmarshall” the config file you would use something like the following:

[sourcecode language=’java’]
public static Config newInstance(){
FileInputStream fin=null;
Config config=null;
try {
JAXBContext jc = JAXBContext.newInstance(“com.markhorgan.spider.config”);
Unmarshaller u = jc.createUnmarshaller();
fin = new FileInputStream(new File(“config/config.xml”));
config = (JAXBElement)u.unmarshal( fin );
} catch (IOException e){
sLogger.error(“Problem opening config file: “+e);
} catch (Exception e){
sLogger.error(“Problem setting up configuration: “+e);
} finally{
if (fin!=null) {
try {
fin.close();
} catch (IOException ignored) {}
}
}
return config;
}
[/sourcecode]

7. And iterating through it might look something like this:

[sourcecode language=’java’]
Config config=ConfigBuilder.newInstance();
for (SpiderNode spiderNode:config.getSpider()) {

}
[/sourcecode]

Comments are closed