Use Saddle directly in your Java application
- Details
- Published on Monday, 26 March 2012 13:59
You probably know about Saddle's parsing and mapping functionalities. If not, have a look here and here. What we want to show here, is that now you can benefit from these functionalities directly in any Java program, without even having to use Mule! You still use Saddle to define the template, but then you can use it anywhere. And if you find Saddle too heavy just for template creation, you will soon be able to have the Template Designer and its Tester as Netbeans plugins.
We'll use a simple example of a pipe-separated file with the following structure: First Name | Last Name | Item ordered. We'll transform the Item by adding "- TEST" in the end and put everything in a xml structure.
Here is the input file:
And that's the result:
The template we use looks like this:
First step : download
- Go to the Download Page and grab the latest MessageLib
- Extract the content of the zip file in any folder of your choice
Second step : import libs into your IDE. For example, with Eclipse:
- Create a new, empty Java project
- Configure its buld path by right-clicking on the project and select Buil Path -> Configure Build Path
- Go to the "Libraries" tab and select "Add External Jars"
- Include all jars you have previously extracted, and validate with OK
Third step : create a class and use the following code in the main() method
// Load the file
File sampleFile = new File("/home/user/sampleCSV.txt");
// Initiate the transformer, using the mandatory template file as constructor parameter
MixedStringToMessageTransformer inputTransformer = new MixedStringToMessageTransformer("/home/user/Test/Orders.xml");
// Transform the file, using the encoding defined on the template
Field f = inputTransformer.transformToMessage(FileUtils.readFileToString(sampleFile, inputTransformer.getEncoding()));
// Use Saddle API to go through each line...
for (Field line : f.getAllInstances("/Orders/Line")) {
// ... and set the Item to be the read item + " - TEST"
line.setChildValue("Item", line.getChildValueAsString("Item") + " - TEST");
}
// Initiate the output transformer
MessageToMixedStringTransformer outputTransformer = new MessageToMixedStringTransformer();
// Get the XML representation
String output = outputTransformer.transformToXMLString(f);
// Write the result
FileUtils.writeStringToFile(new File("/home/user/Test/Out/Result.txt"), output);
In the for loop, we use Saddle's API to retrieve information about the incoming message. The API description is here. And yes, in only these few lines of code, you parse a file, transform it, and write it as XML!
Don't hesitate to try it by yourself! If you have any question or requests, don't hesitate to contact us via the forum.