I’ve just uploaded another example of using plugins in bemokoLive on our wiki . This technique is a pretty powerful one as it provides a very simple way of going from XML to Objects and back the other way. This is such a common task is important to have a clean way of doing it.

Essentially we use a library called XStream. Those of you familiar with .NET may have used the XmlSerializer which uses a very similar technique.

The crux of this example is essentially

…. load the XStream library and XPP dependency with the @Grab annotation. This technique allows you to bring in any old Java library into your bemoko stack.

1
2
@Grab(group='com.thoughtworks.xstream', module='xstream', version='1.3')
@Grab(group='xpp3', module='xpp3_min', version='1.1.3.4.O')

then define a file object which will be where we store our serialised XML file

1
2
@Lazy objectXmlFile = 
  new File("${Bemoko.config.tmp.directory}/example-xstream-object.xml")

This @Lazy annotation here means we only create this property when it is needed.

We can then write the XML file with

1
2
3
objectXmlFile.withOutputStream { out ->
   new XStream().toXML(group, out)
}

where group is our object we want to serialise to XML. We can then read the object back again from XML with:

1
2
3
objectXmlFile.withInputStream { input ->
  return new XStream().fromXML(input)
}

Pretty simple hey! I challenge anyone to achieve that with less code :) . See the full working example here along with link to download the source to save your fingers the typing.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks