Reputation: 99
I am having trouble finding clear documentation on how to do the following transformation:
Java Object -> Smooks/Freemarker Template -> XML Output
Here is the example I am trying:
Java POJO (I have a separate DAO clas that populates this object):
package Transformer;
public class JavaObject {
String name;
}
Main transformer class:
package Transformer;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.transform.stream.StreamResult;
import org.milyn.Smooks;
import org.milyn.container.ExecutionContext;
import org.milyn.payload.JavaSource;
import org.xml.sax.SAXException;
public class Transformer {
protected static String runSmooksTransform(Object javaObject) throws IOException, SAXException {
Smooks smooks = new Smooks("smooks-config.xml");
try {
ExecutionContext executionContext = smooks.createExecutionContext();
StringWriter writer = new StringWriter();
smooks.filterSource(executionContext, new JavaSource("smooks-config.xml"), new StreamResult(writer));
return writer.toString();
} finally {
smooks.close();
}
}
public static void main(String args[]) {
try {
Transformer.runSmooksTransform(javaObject);
} catch(Throwable ex){
System.err.println("Uncaught exception - " + ex.getMessage());
ex.printStackTrace(System.err);
}
}
}
So here is the point where I am confused... I have seen a few different ways to "map" the template
here are some examples I have seen:
A .ftl template file with mapping like this:
<Nm> ${Name} </Nm>
An XML mapping like this:
<medi:segment minOccurs="0" maxOccurs="1" segcode="" xmltag="Group">
<medi:field xmltag="Name" />
</medi:segment>
Mapping in the smooks-config.xml itself:
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.0.xsd"
xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">
<resource-config selector="global-parameters">
<param name="stream.filter.type">SAX</param>
</resource-config>
<reader mappingModel="example.xml" />
<ftl:freemarker applyOnElement="order">
<ftl:template>
<Nm>${name}</Nm>
</ftl:template>
</ftl:freemarker>
</smooks-resource-list>
So can anyone please explain the correct way to use Smooks + a Freemarker template to convert a java object to a specified XML output?
Or point me to documentation/example specific to this use case?
Thank you
Upvotes: 0
Views: 586
Reputation: 31162
I don't know anything about how it's done in Smooks, but it's very likely that you need to add a public String getName() { return name; }
to the JavaObject
class, or else it won't be visible form the FreeMarker template. It actually depends on the FreeMarker configuration settings (and I don't know how Smooks configures it), so anything is possible in theory, but it's likely that you need a getter method, but if not then at least the field need to be public
.
Also you don't pass javaObject
to Smooks in your example code, though I guess it's not a the real code.
Upvotes: 0