Use Saddle directly in your Java application

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:

Input File

And that's the result:

XML Result

 

The template we use looks like this:

Template Structure

 

First step : download

  1. Go to the Download Page and grab the latest MessageLib  
  2. Extract the content of the zip file in any folder of your choice

Second step : import libs into your IDE. For example, with Eclipse:

 

  1. Create a new, empty Java project

  2. Configure its buld path by right-clicking on the project and select Buil Path -> Configure Build Path
  3. Configure Build Path Menu

  4. Go to the "Libraries" tab and select "Add External Jars"
  5. Add External Jars

  6. Include all jars you have previously extracted, and validate with OK
  7. Eclipse Build Path Configured

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.

Add comment

Security code
Refresh