在做系统集成的时候,必不可少的任务就是将数据从一种格式转换为另一种格式,再把转换后的格式发到目标系统,在此用实例介绍一下Camel中利用Freemarker做数据转换.
1,Freemarker的模板如下:
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:h="http://www.w3.org/TR/html4/">
<#escape x as x?xml>
<#list body.peopleList as p>
<person age="20">
<name>
<family>${p.fname}</family>
<given>${p.gname}</given>
</name>
<email>${p.email}</email>
<link manager="${p.manager}" />
<#if p.level == "L1">
<l1tag>xxx</l1tag>
</#if>
</person>
</#list>
</#escape>
</people>
2,与之对应的Java对象如下:每一个person节点对应一个ValueObject放在XMLTemplateParameter的peopleList里面.
public class XMLTemplateParameter {
private String fileName;
private List<ValueObject> peopleList = new ArrayList<ValueObject>();
public List<ValueObject> getPeopleList() {
return peopleList;
}
public void setPeopleList(List<ValueObject> peopleList) {
this.peopleList = peopleList;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
private String fname;
private String gname;
private String email;
private String manager;
private String level;
3,Route代码如下:
public class CamelFreemarkerRoute extends RouteBuilder {
public void configure() throws Exception {
from("quartz://report?cron=10 * * * * ?&stateful=true")
.beanRef("fmBean","prepareFMValues")
.to("freemarker:com/test/camel/freemarker/test.ftl")
.to("file:d:/temp/outbox?fileName=fm.xml");
}
}
4,Route里用到的bean如下:xmlTemplateParameter做为顶级对象放在body里面,Freemarker里取数据的body.peopleList就对应于xmlTemplateParameter.peopleList
public class FmProcessorBean {
public void prepareFMValues(Exchange exchange){
XMLTemplateParameter xmlTemplateParameter = new XMLTemplateParameter();
ValueObject val = null;
for(int i=0;i<3;i++){
val = new ValueObject();
val.setFname("Yao");
val.setGname("Yorker" +i);
val.setEmail("test@mail.com");
val.setManager("m&an<ager");
val.setLevel("L" + i);
xmlTemplateParameter.getPeopleList().add(val);
}
exchange.getIn().setBody(xmlTemplateParameter);
}
}