How to write a transformer
Your transformer class needs to extend org.mule.transformers.AbstractTransformer and implement two methods (optionally also contain a private static final long serialVersionUID for being serializable, this may throw a warning if not done)
eg.
private static final long serialVersionUID = 1L;
The methods are:
- a no input parameter contructor which registers the source data type to the transformer method (below) and constructs using a call to super();
- eg. this constructor registers the source transformer input type as a String.
public StringToStringArray() {
super();
this.registerSourceType(String.class);
}
- the method: doTransform(Object src, String encoding) throws TransformerException
- eg. this transformer converts a colon delimited string into an ArrayList
public ArrayList doTransform(Object src, String encoding) throws TransformerException {
StringTokenizer st = new StringTokenizer((String)src, ":");
ArrayList<String> stringout = new ArrayList<String>();
String temp;
for(int i = 0;st.hasMoreTokens(); i++){
temp = st.nextToken();
stringout.add(temp);
}
return stringout;
}
This method implementation can be set to return any class you want but the return class needs to be registered in the mule configuration - see below.
<transformers>
<transformer name="StringToStringArray"
className="net.customware.enterprise.StringToStringArray"
returnClass="java.util.ArrayList" />
</transformers>
Your transformer is now setup for use, you can use it by adding a transformers attribute to an enpoint in your mule descriptor. eg.
<mule-descriptor name="CreateRow"
implementation="net.customware.enterprise.insertData">
<inbound-router>
<endpoint address="file:
transformers="FileToString StringToStringArray">
<filter pattern="create.txt"
className="org.mule.providers.file.filters.FilenameWildcardFilter" />
<properties>
<property name="pollingFrequency" value="5000" />
</properties>
</endpoint>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.MulticastingRouter">
<endpoint address="stream: />
</router>
</outbound-router>
</mule-descriptor>
This code is an alteration on the SFDC example. The toString() method will be called on the ArrayList to be printed out to System.out.