The requirement is very simple. Route an XML message from rabbitMQ to MongoDB. MongoDB BSON as the data storage and network transfer format for “documents”. BSON is a binary-encoded serialization of JSON-like documents. So, the source message is in a XML format, after getting it from rabbitMQ is necessary to translate into a JSON format compatible with MongoDB.
To translate a message from XML to JSON is possible to use Marshalling function available in Camel extension XmlJson. The pom.xml file needs this new entry:
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-xmljson</artifactId> <version>${org.camel.version}</version> </dependency> |
Of course, to send communicate with MongoDB another entry has to be added to pom.xml:
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-mongodb</artifactId> <version>${org.camel.version}</version> </dependency> |
Now, is possible to change the route on camel ApplicationContext file:
<!-- Camel route --> <camelContext xmlns="http://camel.apache.org/schema/spring"> <dataFormats> <xmljson id="xmljson"/> </dataFormats> <route> <from uri="spring-amqp:TPDirect:TPQueue:TPRouting?type=direct&autodelete=true&durable=true" /> <marshal ref="xmljson"/> <log message="From XML to Json: DONE!" /> <convertBodyTo type="java.lang.String"/> <to uri="mongodb:myDb?database=flights&collection=tickets&operation=save" /> </route> </camelContext> <!-- Mongo DB --> <bean id="myDb" class="com.mongodb.Mongo"> <constructor-arg index="0" value="localhost"/> </bean> |
Bean myDB contains the information to reach MongoDB. It’s also possible to define it using the full url:
<bean id="myDb" class="com.mongodb.Mongo"> <constructor-arg index="0"> <bean class="com.mongodb.MongoURI"> <constructor-arg index="0" value="mongodb://username:password@host:port/db" /> </bean> </constructor-arg> </bean> |
To avoid this exception:
Caused by: No type converter available to convert from type: byte[] to the required type: org.apache.camel.component.mongodb.converters.MongoDbBasicConverters with value |
The JSON translated message has to be converted into String.
That’s all!