The primary goal of this example is to illustrate how Smooks can be used to perform a Model Driven Transformation using the Smooks Javabean and Templating Cartridges.
SVN - Download
NOTE: Take a look the at "java-basic " tutorial before reading this tutorial. To Build: "mvn clean install" The Input and Output MessagesThe input to the transformation is Shipping History message as follows: <history warehouse="2"> As you can see from this message, the <trackingNumbers> element contains the tracking numbers, but in a format that is not easily consumed. The above input message needs to be transformed into the following output message: <shipping-history date="2007-07-16"> We will transform this message by first using it to populate a Java Object Model and then from that model, we generate the required output using a FreeMarker template. The Object ModelWe have 3 basic types - ShippingHistory , Warehouse and TrackingNumber. The ShippingHistory (getters and setters not shown) contains a Warehouse and a TrackingNumber list: public class ShippingHistory {
The Warehouse (getters and setters not shown): public class Warehouse {
Note from the Warehouse Java source that this class also supports a "getName" method which returns a Warehouse name, which is looked up from a local hash. This is basic form of model enrichment. The TrackingNumber (getters and setters not shown): public class TrackingNumber {
Model PopulationThe model is populated (from the input message) using the <jb:binding> configurations of the Javabean Cartridge. The configuration to populate the model is as follows. See the <jb:bindings> configurations (also shows the FreeMarker templating resource): <?xml version="1.0"?> So we have <jb:binding> configurations, one for the ShippingHistory instance and one for the Warehouse instance. Because of the nature of the <trackingNumbers> element, where all the tracking records are bundled into a single text node (line separated), we need to write a "special" DataDecoder class for decoding this element into a list of TrackingNumber instances. This decoder is implemented in the TrackingNumberDecoder class. For more info on Javabean decoders, see the DataDecoder Javadocs. FreeMarker Template ApplicationOnce the Object Model has been populated, we want Smooks to apply the FreeMarker template to the model to produce the required output message (shown above). The template is configured in Smooks as follows (extract from smooks-config.xml ): <!-- And the actual template can be seen here . Note how concise the template is. Executing SmooksAs with the java-basic tutorial, we use the Smooks class as follows: Smooks smooks = new Smooks("smooks-config.xml");
Of course, you'd typically cache the Smooks instance. See the example/Main.java in the example source. |