servicemix 实例 -- 参考open source ESBs in action这本书
1. 项目结构

2. bean服务处理单元
1)Person类
package esb.chapter3; import java.io.StringWriter; import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult; import org.jibx.runtime.JiBXException; import esb.util.framework.JiBXUtil; public class Person { private String customerNumber;
private String firstName;
private String lastName;
private String street;
private String city;
private String state;
private String zip;
private String phone; public String toString(){
return "[custNum=" + customerNumber + ", firstName=" + firstName
+ ", lastName=" + lastName + ", city=" + city + " ]";
} //省略setter,getter方法
public static void main(String[] args) throws JiBXException, TransformerException { Person person = new Person(); person.setCustomerNumber("0001");
person.setFirstName("wentang");
person.setLastName("xu");
person.setStreet("street-1");
person.setCity("city-1");
person.setState("state-1");
person.setZip("111111");
person.setPhone("11111111111"); Source source = JiBXUtil.marshalDocument(person, "utf-8"); /*
* Source => XML
*/
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(); StringWriter sw = new StringWriter();
transformer.transform(source, new StreamResult(sw)); System.out.println("result:\n" + sw.toString());
}
}
2) SimpleTransformerBean类
package esb.chapter3; import javax.annotation.Resource;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.jbi.servicedesc.ServiceEndpoint;
import javax.xml.namespace.QName; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.servicemix.MessageExchangeListener;
import org.jibx.runtime.JiBXException; import esb.util.framework.JiBXUtil; public class SimpleTransformerBean implements MessageExchangeListener { private static final Log LOGGER = LogFactory.getLog(SimpleTransformerBean.class); @Resource
private DeliveryChannel channel; @Resource
private ComponentContext compContext; @Override
public void onMessageExchange(MessageExchange exchange) throws MessagingException { if (exchange.getStatus() != ExchangeStatus.ACTIVE) return; try {
/*
* 从in中解析出Person对象
*/
Person p = (Person) JiBXUtil.unmarshalDocument(exchange.getMessage("in").getContent(), Person.class);
LOGGER.info("receive person " + p.getFirstName() + " " + p.getLastName());
p.setFirstName("John"); exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange); ServiceEndpoint targetEndpoint = compContext.getEndpoint(
new QName("http://opensourceesb/chapter3/", "JMSProviderService"),
"outQueueWriter");
MessageExchange exch = channel.createExchangeFactory(targetEndpoint).createInOnlyExchange();
NormalizedMessage normalizedMsg = exch.createMessage();
normalizedMsg.setContent(JiBXUtil.marshalDocument(p, "UTF-8"));
exch.setMessage(normalizedMsg, "in");
channel.send(exch);
} catch (JiBXException e) {
LOGGER.error("JBI bean exception: ", e);
throw new MessagingException("Error transforming object to or from XML");
}
}
}
3) Jibx工具转换类
package esb.util.framework; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter; import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource; import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.w3c.dom.Node; public class JiBXUtil { public static Object unmarshalDocument(Node node, Class targetClass) throws JiBXException {
return unmarshalDocument(new DOMSource(node), targetClass);
} /**
* 从源source中解封出目标类targetClass对象
* @param source
* @param targetClass
* @return
* @throws JiBXException
*/
public static Object unmarshalDocument(Source source, Class targetClass) throws JiBXException {
Object result = null;
try {
IUnmarshallingContext ctx = BindingDirectory.getFactory(targetClass).createUnmarshallingContext();
//toString(source), 把Source对象转换为XML字符串形式
result = ctx.unmarshalDocument(new StringReader(toString(source)));
} catch (Exception e) {
throw new JiBXException("Error unmarshalling XML to Object", e);
}
return result;
} /**
* 把对象src根据encoding编码封送到Source对象中
* @param src
* @param encoding -- utf-8
* @return
* @throws JiBXException
*/
public static Source marshalDocument(Object src, String encoding) throws JiBXException {
Source result = null; try {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
IMarshallingContext ctx = BindingDirectory.getFactory(src.getClass()).createMarshallingContext();
ctx.marshalDocument(src, encoding, null, bOut);
result = new StreamSource(new ByteArrayInputStream(bOut.toByteArray()));
} catch (Exception e) {
throw new JiBXException("Error marshalling XML to Object", e);
}
return result;
} /**
* 把Source对象转换为XML字符串形式
* @param source
* @return
* @throws TransformerException
*/
private static String toString(Source source) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
StringWriter sw = new StringWriter();
Transformer trans = tf.newTransformer();
trans.transform(source, new StreamResult(sw));
String result = sw.toString();
System.out.println("result " + result);
return result;
}
}
4) Person => XML 映射文件, mapping.xml
<binding>
<mapping name="person" class="esb.chapter3.Person">
<value name="customer-number" field="customerNumber" />
<value name="first-name" field="firstName" />
<value name="last-name" field="lastName" />
<value name="street" field="street" />
<value name="city" field="city" />
<value name="state" field="state" />
<value name="zip" field="zip" />
<value name="phone" field="phone" />
</mapping>
</binding>
5) 对eclipse项目z_servicemix/bin目录下的.class文件,进行绑定再编译
<?xml version="1.0" encoding="UTF-8"?>
<project name="JiBX-compiler" default="bind-compile" basedir=".">
<property name="jibx-lib" value="D:/osesbinaction/libraries/jibx/lib" />
<taskdef name="bind" classname="org.jibx.binding.ant.CompileTask"
classpath="D:/osesbinaction/libraries/jibx/lib/jibx-bind.jar" />
<target name="bind-compile">
<bind verbose="true" load="true" binding="resources/chapter3/mapping.xml">
<classpath>
<pathelement path="bin"/>
<pathelement location="${jibx-lib}/jibx-run.jar"/>
</classpath>
</bind>
</target>
</project>
6) 运行Person类main方法。查看转换效果

7) xbean.xml
<beans xmlns:bean="http://servicemix.apache.org/bean/1.0"
xmlns:esb="http://opensourceesb/chapter3/"> <classpath>
<location>.</location>
<location>bcel.jar</location>
<location>jibx-bind.jar</location>
<location>jibx-extras.jar</location>
<location>jibx-run.jar</location>
<location>qdox-1.6.1.jar</location>
<location>stax-api.jar</location>
<location>wstx-asl.jar</location>
<location>xmlpull_1_1_4.jar</location>
<location>xpp3.jar</location>
</classpath> <bean:endpoint service="esb:beanService" endpoint="beanEndpoint"
bean="#SimpleTransformer" /> <bean id="SimpleTransformer" class="esb.chapter3.SimpleTransformerBean" />
</beans>
8)chapter3-bean-su服务单元目录结构

打包:jar cvf chapter3-bean-su.zip .
2 文件轮询绑定组件配置 chapter3-file-su
xbean.xml
<beans xmlns="http://xbean.org/schemas/spring/1.0"
xmlns:file="http://servicemix.apache.org/file/1.0"
xmlns:esb="http://opensourceesb/chapter3/"> <file:sender service="esb:fileSender"
endpoint="simpleFromJMSSender"
directory="chapter3/out">
</file:sender> <file:poller service="esb:filePoller"
endpoint="simpleToJMSPoller"
targetService="esb:JMSProviderService"
targetEndpoint="inQueueWriter"
file="chapter3/in"
period="2000">
</file:poller>
</beans>
目录结构:

打包: jar cvf chapter3-file-su.zip .
3. JMS绑定组件 chapter3-jms-su
xbean.xml
<beans xmlns:jms="http://servicemix.apache.org/jms/1.0"
xmlns:esb="http://opensourceesb/chapter3/"> <!-- esb:filePoller[simpleFromJMSSender]
=> esb:JMSProviderService[inQueueWriter]
=> inQueue队列
=> esb:JMSConsumerService[inQueueReader]
=> esb:beanService[beanEndpoint] 目录chapter/in => 文件轮询绑定组件
=> 消息提供者 => 队列 => 消息消费者 ###通过JMS连接了filepoller文件轮询组件和bean服务处理单元
=> 转到bean服务处理单元
-->
<jms:provider service="esb:JMSProviderService"
endpoint="inQueueWriter"
destinationName="inQueue"
connectionFactory="#connectionFactory" />
<jms:consumer service="esb:JMSConsumerService"
endpoint="inQueueReader"
targetService="esb:beanService"
targetEndpoint="beanEndpoint"
destinationName="inQueue"
connectionFactory="#connectionFactory" /> <!-- esb:beanService[beanEndpoint]
=> esb:JMSProviderService[outQueueWriter] 消息提供者
=> outQueue队列
=> esb:JMSConsumerService[inQueueReader2] 消息消费者
=> esb:fileSender[simpleFromJMSSender] bean服务处理单元
=> 消息提供者 => outQueue队列 => 消息消费者 ####通过JMS使服务处理单元与文件绑定组件间能够通信
=> 文件发送绑定组件 => chapter3/out目录
-->
<jms:provider service="esb:JMSProviderService"
endpoint="outQueueWriter"
destinationName="outQueue"
connectionFactory="#connectionFactory" />
<jms:consumer service="esb:JMSConsumerService"
endpoint="inQueueReader2"
targetService="esb:fileSender"
targetEndpoint="simpleFromJMSSender"
destinationName="outQueue"
connectionFactory="#connectionFactory"/> <bean id="connectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
</beans>
打包: jar chapter3-jms-su.zip .
4. 服务装配(装配服务单元和绑定组件)

装配描述文件 META-INF/jbi.xml
<?xml version="1.0" encoding="UTF-8"?>
<jbi xmlns="http://java.sun.com/xml/ns/jbi" version="1.0">
<service-assembly> <identification>
<name>Chapter3-JMSBindingService</name>
<description>Example showing the jms binding component</description>
</identification> <service-unit>
<identification>
<name>SU-BEAN</name>
<description>The bean component</description>
</identification>
<target>
<artifacts-zip>chapter3-bean-su.zip</artifacts-zip>
<component-name>servicemix-bean</component-name>
</target>
</service-unit> <service-unit>
<identification>
<name>SU-JMS-Queue</name>
<description>A number of ftp pollers and senders</description>
</identification>
<target>
<artifacts-zip>chapter3-jms-su.zip</artifacts-zip>
<component-name>servicemix-jms</component-name>
</target>
</service-unit> <service-unit>
<identification>
<name>SU-JMS-File</name>
<description>A number of file pollers and senders files
</description>
</identification>
<target>
<artifacts-zip>chapter3-file-su.zip</artifacts-zip>
<component-name>servicemix-file</component-name>
</target>
</service-unit>
</service-assembly>
</jbi>
打包装配文件 jar cvf chapter3-jms-sa.zip META-INF chapter3-*-su.zip
部署装配文件chapter3-jms-sa.zip,把其拷贝到servicemix-3.2.1/hotdeploy目录下
启动 servicemix ESB
D:\osesbinaction\esb\apache-servicemix-3.2.1>bin\servicemix
Starting Apache ServiceMix ESB: 3.2.1 Loading Apache ServiceMix from servicemix.xml on the CLASSPATH
INFO - ConnectorServerFactoryBean - JMX connector available at: service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi INFO - JBIContainer - ServiceMix 3.2.1 JBI Container (ServiceMix) is starting
INFO - JBIContainer - For help or more informations please see: http://incubator.apache.org/servicemix/ INFO - ComponentMBeanImpl - Initializing component: #SubscriptionManager# INFO - jetty - Logging to org.apache.servicemix.http.jetty.JCLLogger@72f3a4a1 via org.apache.servicemix.http.jetty.JCLLogger INFO - DeploymentService - Restoring service assemblies ######
## 设置组件运行状态,并实例化组件
#####
INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-bean to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-bean INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-camel to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-camel INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-cxf-bc to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-cxf-bc INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-cxf-se to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-cxf-se INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-drools to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-drools INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-eip to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-eip INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-file to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-file INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-ftp to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-ftp INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-http to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-http INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-jms to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-jms INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-jsr181 to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-jsr181 INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-lwcontainer to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-lwcontainer INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-quartz to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-quartz
1 name = quartz.properties INFO - SimpleThreadPool - Job execution threads will use class loader of thread: main INFO - QuartzScheduler - Quartz Scheduler v.1.5.2 created. INFO - RAMJobStore - RAMJobStore initialized.
INFO - StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource fil
e in Quartz package: 'quartz.properties'
INFO - StdSchedulerFactory - Quartz scheduler version: 1.5.2
INFO - QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-saxon to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-saxon INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-script to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-script INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-truezip to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-truezip INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-wsn2005 to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-wsn2005 INFO - ComponentMBeanImpl - Setting running state for Component: servicemix-xmpp to Started
INFO - ComponentMBeanImpl - Initializing component: servicemix-xmpp ## 启动部署的服务装配组件
INFO - ServiceAssemblyLifeCycle - Starting service assembly: Chapter3-JMSBindingService INFO - ServiceUnitLifeCycle - Initializing service unit: SU-BEAN
INFO - ServiceUnitLifeCycle - Initializing service unit: SU-JMS-Queue
INFO - ServiceUnitLifeCycle - Initializing service unit: SU-JMS-File INFO - ServiceUnitLifeCycle - Starting service unit: SU-BEAN
INFO - ServiceUnitLifeCycle - Starting service unit: SU-JMS-Queue
INFO - ServiceUnitLifeCycle - Starting service unit: SU-JMS-File INFO - JBIContainer - ServiceMix JBI Container (ServiceMix) started
INFO - JDBCAdapterFactory - Database driver recognized: [apache_derby_embedded_jdbc_driver]
INFO - LogTask - Logging system reconfigured using file: file:/D:/osesbinaction/esb/apache-servicemix-3.2.1/conf/log4j.xml 在chapter3/in目录下拖入一个person.xml文件,控制台相关输出:
result <?xml version="1.0" encoding="UTF-8"?><person>
<customer-number>123</customer-number>
<first-name>John</first-name>
<last-name>Doe</last-name>
<street>1st Street</street>
<city>New York</city>
<state>NY</state>
<zip>567898</zip>
<phone>1768768768</phone>
</person>
INFO - SimpleTransformerBean - receivee person John Doe
servicemix 实例 -- 参考open source ESBs in action这本书的更多相关文章
- SQL/T-SQL实例参考
,D.[Score] B_Score ,'Distince'= CASE WHEN C.Score > D.Score THEN C.[Score] - D.[Score] WHEN C.Sco ...
- [AS3]as3用ByteArray来对SWF文件编码加密实例参考
[AS3]as3用ByteArray来对SWF文件编码加密实例参考,简单来说,就是将 swf 以 binary 的方式读入,并对 ByteArray 做些改变,再重新存成 swf 档.这个作业当然也可 ...
- SQL/T-SQL实例参考-2
对多关联查询,查询多中的记录,但是返回一的结果集 子查询语法 --一对多关联查询,查询多中的记录,但是返回一的结果集 SELECT C.* FROM ( SELECT A.BasicID FROM [ ...
- SQL/T-SQL实例参考-1
CASE ,D.[Score] B_Score ,'Distince'= CASE WHEN C.Score > D.Score THEN C.[Score] - D.[Score] WHEN ...
- Centos7 Firewall 防火墙配置应用实例参考(转)
时间:2016-06-02 02:40来源:linux.it.net.cn 作者:IT 简单的配置,参考学习:--permanent 当设定永久状态时 在命令开头或者结尾处加入此参数,否则重载或 ...
- ncl 实例参考
NCL中绘制中国任意省份的精确地图 NCL学习笔记(实战篇) 用NCL画垂直风场剖面图实例 NCL学习笔记(天气分析图)
- PlantUML的实例参考
project: blog target: plant-uml-instances.md date: 2015-12-24 status: publish tags: - PlantUML - UML ...
- R语言画图实例-参考R语言实战
dose <- c(, , , ,) drugA <- c(, , , , ) drugB <- c(, , , , ) # 数据准备 opar <- par(no.reado ...
- python搭建简易服务器实例参考
有关python搭建简易服务器的方法. 需求分析: 省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪, 每次打开都要缓上半天,甚至浏览器直接挂掉 采用python搭建一个最最简易的 w ...
随机推荐
- Linux下备份Mysql所有数据库
需求:备份除了mysql系统数据库的所有数据库 以下为Shell脚本,只需要修改用户密码即可 MYSQL_USER=root MYSQL_PASS=123456 MYSQL_CONN="-u ...
- OpenLayers图层
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head ...
- 阿里云发布SaaS生态战略,成就亿级营收独角兽
7月26日,在上海举办的阿里云合作伙伴峰会上,阿里云正式发布SaaS生态战略,计划用阿里云的品牌.渠道.资本.方法论.技术加持伙伴,成就亿级营收独角兽. 该生态战略计划招募10家一级SaaS合作伙伴, ...
- PHP学习(字符串操作)
在PHP中,字符串的定义可以使用英文单引号' ',也可以使用英文双引号" ".单引号和双引号到底有啥区别呢? PHP允许我们在双引号串中直接包含字串变量.而单引号串中的内容总被认 ...
- 苹果建议开发者在iOS 7正式发布之前把应用提交至App Store
今早在给开发者的邮件中,苹果建议开发者在下周9月18日正式发布iOS 7之前把应用提交至App Store.邮件特别提到了iOS 7的新功能,还提到了充分利用iPhone 5S功能的新API,比如M7 ...
- 【JZOJ4770】【NOIP2016提高A组模拟9.9】闭门造车
题目描述 自从htn体验了一把飙车的快感,他就下定决心要闭门造车!但是他两手空空怎么造得出车来呢?无奈的他只好来到了汽车零部件商店. 一走进商店,玲琅满目的各式零件看得htn眼花缭乱.但是他很快便反应 ...
- 【Django入坑之路】Django后台上传图片,以及前端的显示
#setting配置: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") # ...
- javascript如何将时间戳转为24小时制
var now = new Date(parseInt(1446634507) * 1000);console.log(now.toLocaleString('chinese',{hour12:fal ...
- PHP Laravel系列之环境搭建( VirtualBox+Vagrant+Homestead+系列网址)
搭建环境从来都是阻挡一门新技能的最致命的硬伤,为了这个环境,我又是花费了半天的时间,各种问题层出不穷,下面基于网上的一些教程(我看到的都多少有些问题) 开始的时候是在实验楼这个平台上开始学习的,不过 ...
- java8 各种时间转换方法
java8 各种时间转换方法 本来按照常理日期时间是一个很简单的东西,只需要根据一个时间戳就可以算出当前的时间了.但这其实只是初级的想法,是因为你的项目还没有到跨时区部署的程度,一旦你的项目要部署到其 ...