New Post

Rss

Tampilkan postingan dengan label Integration. Tampilkan semua postingan
Tampilkan postingan dengan label Integration. Tampilkan semua postingan
Sabtu, 30 Maret 2013
Execution of Groovy scripts from Java - XmlSlurper and MarkupBuilder in mapping issues

Execution of Groovy scripts from Java - XmlSlurper and MarkupBuilder in mapping issues


Problem with mappings


In our project we came across a really big problem related to mapping. Having two systems that initially were defined by the BA to be somehwat simillar we have chosen the simple XSLT (done through Altova Mapforce) of the input message to the output one.

Afterwards it turned out that the functions required to perform a mapping are becoming enormous. An example of such a mapping is:
From the input message take a list of Cars iterate over it and find a Car whose field "prodcutionDate" is the lowest and the attribute "make" is equal to "Honda" and as the output return the "saleDate"
So in order to map it we decided to move to JBoss Drools. The decision tables were out of question since the logic was to complex and customized to be placed in the spreadsheet so we coded everything in the DRL files. Soon the rules got really big and some of our developers were forced to spend plenty of time on constant recreation of rules stated by the BA.

Out of frustration and after having seen all the amazing things at the 33rd degree conference I decided to start finding solutions to my problems which were:


  1. The DRL files are big and started to become unmaintainable (for a single field we had for example 4 rules)
  2. Since the BA has never coded a single Drools rule / XSLT  in his life adding a simple if... else... statement for him is not a problem
  3. The BA has to wait for the mapping implementation by the devs until he can test it
  4. The devs are spending far too much time on coding the mapping rules instead of developing other features
After stating these problems a research regarding mapping frameworks took place and one of the concepts that I began working on was trying to create the mapping in Groovy. Since Groovy (thanks to for example PropertyMissing and MethodMissing) is a perfect language for creating a DSL I decided to start right away. The only two things I had to remember about were:
  1. The current application is written purely in Java
  2. The mapping code (in order to perform fast testing) has to be detached from the application as such - it can't be compiled during deployment because we want to have the possibility of frequent substitutions of the mappings

Project structure 


Having defined the language, the constraints I created the following solution:


The project structure

As you can see the project structure is very simple. To begin with it is built in Gradle. The main function can be found in the XmlTransformer.java. The flow is such that the TransformerFactory creates a Transformer basing on the Groovy script that came out of the ScriptFactory (in our project for different types of products that we distinguish by a field in the XML file, we have different DRL files). The Groovy scripts are residing in the classpath in the /groovy/ folder (of course at the end of the day those scripts should be placed outside any jars). 

In the build.gradle 

apply plugin: 'java'

group = 'com.blogspot.toomuchcoding'
version = '1.0'

repositories {
mavenCentral()
}

dependencies {
compile 'org.codehaus.groovy:groovy-all:2.0.5'
compile 'org.slf4j:slf4j-log4j12:1.7.2'
compile 'log4j:log4j:1.2.16'
compile 'com.google.guava:guava:14.0'

testCompile group: 'junit', name: 'junit', version: '4.+'
}

task(executeMain, dependsOn: 'classes', type: JavaExec) {
main = 'com.blogspot.toomuchcoding.XmlTransformer'
classpath = sourceSets.main.runtimeClasspath
}


we can see that there is no groovy plugin - it has been done deliberately since we don't want our scripts to be compiled. Now let's take a look at the logic behind the TransformerFactory that compiles the Groovy script. What is really important is the fact that our Groovy class implements an interface created in our Java project - we want from the Java point of view to have no problems with execution of the Groovy code.

TransformerFactoryImpl.java

package com.blogspot.toomuchcoding.factory;

import com.blogspot.toomuchcoding.transformer.Transformer;
import com.google.common.io.Resources;
import groovy.util.GroovyScriptEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 22.03.13
* Time: 23:54
*/
public class TransformerFactoryImpl implements TransformerFactory<String, String> {
private static final String GROOVY_SCRIPTS_CLASSPATH = "groovy/";
private static Logger LOGGER = LoggerFactory.getLogger(TransformerFactoryImpl.class);

private ScriptFactory scriptFactory;
private GroovyScriptEngine groovyScriptEngine;

public TransformerFactoryImpl(ScriptFactory scriptFactory) {
this.scriptFactory = scriptFactory;
try {
groovyScriptEngine = new GroovyScriptEngine(GROOVY_SCRIPTS_CLASSPATH);
} catch (IOException e) {
LOGGER.error("Exception occurred while trying to create the Groovy script engine", e);
throw new RuntimeException(e);
}
}

@Override
public Transformer<String, String> createTransformer() {
Transformer<String, String> transformerFromScript = null;
try {
File scriptFile = scriptFactory.createScript();
URL scriptAsAClasspathResource = Resources.getResource(GROOVY_SCRIPTS_CLASSPATH + scriptFile.getName());
Class classFromScript = groovyScriptEngine.loadScriptByName(scriptAsAClasspathResource.getFile());
transformerFromScript = (Transformer<String, String>) classFromScript.newInstance();
} catch (Exception e) {
LOGGER.error("Exception occurred while trying to execute Groovy script", e);
}
return transformerFromScript;
}

}

A GroovyScriptEngine is used to load a script by name. I chose the GroovyScriptEngine (hopefully I used it in a good way ;) )  because:
The most complete solution for people who want to embed groovy scripts into their servers and have them reloaded on modification is the GroovyScriptEngine. You initialize the GroovyScriptEngine with a set of CLASSPATH like roots that can be URLs or directory names. You can then execute any Groovy script within those roots. The GSE will also track dependencies between scripts so that if any dependent script is modified the whole tree will be recompiled and reloaded.
I wanted to have some way of caching the compiled classes in order not to have any issues with PermGen.
Anyway you can see that I am doing some conversions to have the URL of the classpath Groovy script resource. At the end we are extracting a class from the Groovy script and we are casting it to the Transformer.

AbstractGroovyXmlTransformer.groovy

package groovy

import com.blogspot.toomuchcoding.transformer.Transformer
import groovy.util.slurpersupport.NodeChildren
import groovy.xml.MarkupBuilder

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 23.03.13
* Time: 02:16
*/
abstract class AbstractGroovyXmlTransformer implements Transformer<String, String> {

static Map<String, Object> MISSING_PROPERTIES = ["convertDate": new DateConverter(), "map": new Mapper()]

@Override
String transform(String input) {
def inputXml = new XmlSlurper().parseText input
def writer = new StringWriter()
def outputXml = new MarkupBuilder(writer)
doTransform inputXml, outputXml
writer.toString()
}

abstract void doTransform(inputXml, outputXml)

def propertyMissing(String name) {
Object property = MISSING_PROPERTIES[name]
assert property != null, "There is no function like [$name]. The ones that are supported are ${MISSING_PROPERTIES.keySet()}"
property
}



protected static class Mapper {
private Map<String, String> inputParameters

Mapper given(Map inputParameters) {
this.inputParameters = inputParameters
this
}

String from(NodeChildren nodeChildren) {
assert inputParameters != null, "The mapping can't be null!"
assert nodeChildren != null, "Node can't be null!"
String nodeText = nodeChildren.text()
String mappedValue = inputParameters[nodeText]
mappedValue ?: inputParameters.default
}

static Mapper map(Map<String, String> inputParameters) {
return new Mapper(inputParameters)
}
}

protected static class DateConverter {
private String inputDate
private String inputDateFormat

DateConverter from(NodeChildren nodeChildren) {
this.inputDate = nodeChildren.text()
this
}

DateConverter havingDateFormat(String inputDateFormat) {
this.inputDateFormat = inputDateFormat
this
}

String toOutputDateFormat(String outputDateFormat) {
assert inputDate != null, "The input date for which you are trying to do the conversion can't be null"
assert inputDateFormat != null, "The input date format for which you are trying to do the conversion can't be null"
assert outputDateFormat != null, "The output date format for which you are trying to do the conversion can't be null"
Date.parse(inputDateFormat, inputDate).format(outputDateFormat)
}

static DateConverter convertDate() {
new DateConverter()
}
}
}
In this abstract Groovy class I decided to place all the logic that could blur the image for the BA. In addition to that I created some helper classes and methods. In order to fully use the Groovy's DSL capabilities I used the propertyMissing method to map the words "map" and "convertDate" to create the instances of the helper classes which are used in the Builder design pattern way:

convertDate.from(inputXml.InputSystemContext.InputDate).havingDateFormat("dd/MM/yyyy").toOutputDateFormat("yy/MM/dd")

or

map.given("Some_action" : "Some_output_action", "default" : "something else").from(inputXml.AdditionalData.TypeOfAction)

If there is no such "function" (for example a BA makes a typo or sth) then an assertion error is being thrown and a list of supported "function" (which in reality are properties - but they are functions from the BA's perspective) is being printed. 

Now let's move to the script that would be used by the BA.

GroovyXmlTransformer.groovy

package groovy

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 22.03.13
* Time: 23:59
*
* additional functions:
*
* convertDate.from(Node).havingDateFormat("DateFormat").toOutputDateFormat("AnotherDateFormat")
* map.given("Value to be mapped from" : "Value to be mapped to", "default" : "default value").from(Node)
*
*/
class GroovyXmlTransformer extends AbstractGroovyXmlTransformer {

@Override
void doTransform(inputXml, outputXml) {
outputXml.OutputSystemEnvelope() {
OutputSystemContext {
ResponseID(inputXml.InputSystemContext.RequestID.text().reverse())
OutputSource('OUTPUT_SYSTEM')
OutputDate(convertDate.from(inputXml.InputSystemContext.InputDate).havingDateFormat("dd/MM/yyyy").toOutputDateFormat("yy/MM/dd"))
}
OutputAdditionalData {
OutputReferenceNo("SOME_PREFIX_${inputXml.AdditionalData.ReferenceNo.text()}_SOME_SUFIX")
OutputTypeOfAction(map.given("Some_action" : "Some_output_action", "default" : "something else").from(inputXml.AdditionalData.TypeOfAction))
OutputTransactions {
inputXml.AdditionalData.Transactions.Transaction.each {
OutputTransaction(Client: it.Client, ProductType: it.ProductType, 'Done')
}
}
OutputProducts {
def minProduct = inputXml.AdditionalData.Products.Product.list().min { it.Value.text() }
def maxProduct = inputXml.AdditionalData.Products.Product.list().max { it.Value.text() }
MinProduct(name: minProduct.Name.text(), minProduct.Value.text())
MaxProduct(name: maxProduct.Name.text(), maxProduct.Value.text())
}
}
}
}
}

This piece of code does the following mapping (You can check the /xml/SampleXml.xml ):

Mapped fromMapped to
InputSystemEnvelopeOutputSystemEnvelope
InputSystemContexOutputSystemContex
RequestIdResponseId (the Id should be reverted)
InputSourceOutputSoutce (constant "UTPUT_SYSTEM")
InputDateOutputDate (converted from dd/MM/yyyy to yy/MM/dd)
InputAdditionalDataOutputAdditionalData
InputReferenceNoOutputReferenceNo ( "SOME_PREFIX_" + value from InputReferenceNo + "_SOME_SUFIX")
InputTypeOfActionOutputTypeOfAction (mapped in such a way that if InputTypeOfAction is equal to "Some_action" then we will have "Some_output_action". Otherwise we get "something else")
TransactionsOutputTransactions
TransactionOutputTransaction ( Attribute Client from Transaction.Client, Attribute ProductType from Transaction.ProductType, and the value "Done")
ProductsOutputProducts
Product having min valueMinProduct
Product having max valueMaxProduct

The output


Converted from [<InputSystemEnvelope>
<InputSystemContext>
<RequestID>1234567890</RequestID>
<InputSource>INPUT_SYSTEM</InputSource>
<InputDate>22/03/2013</InputDate>
</InputSystemContext>
<AdditionalData>
<ReferenceNo>Ref1234567</ReferenceNo>
<TypeOfAction>Some_action</TypeOfAction>
<Transactions>
<Transaction>
<Client>ACME</Client>
<ProductType>IRS</ProductType>
</Transaction>
<Transaction>
<Client>Oracle</Client>
<ProductType>DB</ProductType>
</Transaction>
</Transactions>
<Products>
<Product>
<Name>Book</Name>
<Value>1</Value>
</Product>
<Product>
<Name>Car</Name>
<Value>10000</Value>
</Product>
<Product>
<Name>Boat</Name>
<Value>100000000</Value>
</Product>
<Product>
<Name>Spaceship</Name>
<Value>1000000000000000000</Value>
</Product>
</Products>
</AdditionalData>
</InputSystemEnvelope>]

to

[<OutputSystemEnvelope>
<OutputSystemContext>
<ResponseID>0987654321</ResponseID>
<OutputSource>OUTPUT_SYSTEM</OutputSource>
<OutputDate>13/03/22</OutputDate>
</OutputSystemContext>
<OutputAdditionalData>
<OutputReferenceNo>SOME_PREFIX_Ref1234567_SOME_SUFIX</OutputReferenceNo>
<OutputTypeOfAction>Some_output_action</OutputTypeOfAction>
<OutputTransactions>
<OutputTransaction Client='ACME' ProductType='IRS'>Done</OutputTransaction>
<OutputTransaction Client='Oracle' ProductType='DB'>Done</OutputTransaction>
</OutputTransactions>
<OutputProducts>
<MinProduct name='Book'>1</MinProduct>
<MaxProduct name='Spaceship'>1000000000000000000</MaxProduct>
</OutputProducts>
</OutputAdditionalData>
</OutputSystemEnvelope>]

Pros and cons

The pros and cons of this approach are as follows:

Pros:
  • The mapping is done sequentialy - field by field (it is easier to debug the problem)
  • The mapping consists of vocabulary understandable by the BA
  • Most of mappings could be done by the BA
  • The majority of non-mapping grammar is hidden in the abstraction
  • The compilation of the Groovy script is faster than creation of KnowledgeBases and compilation of Drools scripts
  • Independence on the XML schema (each change of the schema would require the recompilation of the JAXB classes)
Cons:
  • The BA would have to have some knowledge from the domain of computer science
  • No parallel mapping
  • The mapping might get less readable due to the fact that it is highly probable that the BA (out of lack of time) won't create a single function - all the logic will end up in the closures for a given Node.
  • There might be some memory issues with parsing and recompilation of the Groovy scripts
  • No XML schema may lead to improper output / input XML path setting

Summary

The problem with mapping that we encountered in our project turned out to be a very interesting issue to deal with. The example shown in this post is only a proposition of solving the issue and hopefully could be a starting point to a further discussion on the topic. If you have any ideas or opinions on this topic please leave a comment under this article.

The sources can be found on the Too Much Coding BitBucket repository and on GitHub.
Kamis, 22 November 2012
no image

Apache Camel with Spring, routing with enrichment service



Sorry for not having posted anything in some time but I had plenty of work. Anyway today I will continue the example with JMS that I've shown you some time ago.

The idea of the previous example was to simplify the work that we had to do in a manual way - we've sed JmsTemplate and Spring listener containers. The routing as such unfortunately was still done by us. In order to facilitate this process we can use Apache Camel.

The following example bases on the one that we've seen in this post Spring JMS, message automatic conversion, JMS template but with slight modifications:

CamelRouter.java

package pl.grzejszczak.marcin.camel;

import org.apache.camel.spring.Main;

public class CamelRouter {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Main main = new Main();
main.setApplicationContextUri("/camel/camelContext.xml");
main.run(args);
}

}


What we can see here is the usage of the Camel's Main class which you can reuse to more easily boot up Camel and keep it running until the JVM terminate.

Then we have a new file camelContext.xml in which we have the Camel context in the Spring configuration file.

camelContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

<import resource="classpath:/camel/jmsApplicationContext.xml" />

<camel:camelContext id="camel" xmlns:camel="http://camel.apache.org/schema/spring">
<camel:dataFormats>
<camel:jaxb id="jaxb" prettyPrint="true" contextPath="pl.grzejszczak.marcin.camel.jaxb.generated" />
</camel:dataFormats>

<camel:route>
<camel:from uri="activemq:topic:Initial.Topic" />
<camel:unmarshal ref="jaxb" />
<camel:bean ref="enrichingService" />
<camel:marshal ref="jaxb" />
<camel:to uri="activemq:topic:Routed.Topic" />
</camel:route>

</camel:camelContext>
</beans>

We are defining in this file in order to create a Camel Route - from the activemq topic called Initial.Topic to the one called Routed.Topic. In the meantime we are doing some unmarshalling and marshalling by means of Jaxb.

In the jmsApplicationContext we no longer define the sender to the final topic: Routed.Topic.

jmsApplicationContext.java

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

<!-- Spring configuration based on annotations -->
<context:annotation-config />
<!-- Show Spring where to search for the beans (in which packages) -->
<context:component-scan base-package="pl.grzejszczak.marcin.camel" />

<!-- Show Spring where to search for the properties files -->
<context:property-placeholder location="classpath:/camel/jms.properties" />

<!-- The ActiveMQ connection factory with specification of the server URL -->
<bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>

<!-- Spring's jms connection factory -->
<bean id="cachingConnectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="activeMQConnectionFactory" />
<property name="sessionCacheSize" value="10" />
</bean>

<!-- The name of the queue from which we will take the messages -->
<bean id="origin" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="${jms.origin}" />
</bean>
<!-- The name of the queue to which we will route the messages -->
<bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="${jms.destination}" />
</bean>

<!-- Configuration of the JmsTemplate together with the connection factory and the message converter -->
<bean id="producerTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory" />
<property name="messageConverter" ref="oxmMessageConverter" />
</bean>

<!-- Custom message sender sending messages to the initial queue -->
<bean id="originPlayerSender" class="pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl">
<property name="destination" ref="origin" />
</bean>

<!-- Custom message listener - listens to the destination queue -->
<bean id="destinationListenerImpl" class="pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl"/>


<!-- Spring's jms message listener container - specified the connection factory, the queue to be listened to and the component that listens to the queue -->
<bean id="jmsDestinationContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="cachingConnectionFactory" />
<property name="destination" ref="destination" />
<property name="messageListener" ref="destinationListenerImpl" />
</bean>

<!-- Message converter - automatically marshalls and unmarshalls messages using the provided marshaller / unmarshaller-->
<bean id="oxmMessageConverter" class="org.springframework.jms.support.converter.MarshallingMessageConverter">
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="marshaller" />
</bean>

<bean id="enrichingService" class="pl.grzejszczak.marcin.camel.service.EnrichingServiceImpl"/>

<!-- Spring's JAXB implementation of marshaller - provided a class the JAXB generated class -->
<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails" />
</oxm:jaxb2-marshaller>

</beans>

Once we have already initialized our camel context, what we need to do is to send a message to the Initial.Topic. We are doing it by means of our modified ActiveMQRouter class.

ActiveMQRouter.java


package pl.grzejszczak.marcin.camel.manual;

import java.io.File;
import java.util.Scanner;

import javax.jms.JMSException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import pl.grzejszczak.marcin.camel.jaxb.PlayerDetailsConverter;
import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;
import pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl;
import pl.grzejszczak.marcin.camel.manual.jms.Sender;

public class ActiveMQRouter {

/**
* @param args
* @throws JMSException
*/
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("/camel/jmsApplicationContext.xml");
@SuppressWarnings("unchecked")
Sender<PlayerDetails> sender = (Sender<PlayerDetails>) context.getBean("originPlayerSender");

Resource resource = new ClassPathResource("/camel/RobertLewandowski.xml");

Scanner scanner = new Scanner(new File(resource.getURI())).useDelimiter("\\Z");
String contents = scanner.next();

PlayerDetailsConverter converter = context.getBean(PlayerDetailsConverter.class);

FinalListenerImpl listener = (FinalListenerImpl) context.getBean("finalListenerImpl");

sender.sendMessage(converter.unmarshal(contents));
}
}

The class is reading the file and sending it to the initial topic. We also initialize a FinalListenerImpl - a class that will listen to the messages coming to the final topic - to prove that everything is working correctly.

That's it! Now let's check out the logs. Logs of CamelRouter:


2012-11-22 22:51:39,429 INFO  [main] org.apache.camel.main.MainSupport:300 Apache Camel 2.9.2 starting
2012-11-22 22:51:40,028 INFO [main] org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4c5e176f: startup date [Thu Nov 22 22:51:40 CET 2012]; root of context hierarchy
2012-11-22 22:51:40,213 INFO [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/camelContext.xml]
2012-11-22 22:51:40,746 INFO [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/jmsApplicationContext.xml]
2012-11-22 22:51:41,120 INFO [main] org.springframework.context.annotation.ClassPathBeanDefinitionScanner:210 JSR-330 'javax.inject.Named' annotation found and supported for component scanning
2012-11-22 22:51:43,219 INFO [main] org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:177 Loading properties file from class path resource [camel/jms.properties]
2012-11-22 22:51:43,233 INFO [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor:139 JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2012-11-22 22:51:43,274 INFO [main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@19d03a4e: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,AgeEnricher,ClubEnricher,PlayerDetailsConverter,finalListenerImpl,playerDetailsSenderImpl,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,activeMQConnectionFactory,cachingConnectionFactory,origin,destination,producerTemplate,originPlayerSender,destinationListenerImpl,jmsDestinationContainer,oxmMessageConverter,enrichingService,marshaller,template,consumerTemplate,camel:beanPostProcessor,camel,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-11-22 22:51:43,424 INFO [main] org.springframework.oxm.jaxb.Jaxb2Marshaller:436 Creating JAXBContext with classes to be bound [class pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails]
2012-11-22 22:51:44,521 INFO [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:51:45,061 INFO [main] org.springframework.jms.connection.CachingConnectionFactory:291 Established shared JMS Connection: ActiveMQConnection {id=ID:marcin-SR700-47684-1353621104666-1:1,clientId=null,started=false}
2012-11-22 22:51:45,608 INFO [main] org.apache.camel.spring.SpringCamelContext:1374 Apache Camel 2.9.2 (CamelContext: camel) is starting
2012-11-22 22:51:45,611 INFO [main] org.apache.camel.management.ManagementStrategyFactory:38 JMX enabled. Using ManagedManagementStrategy.
2012-11-22 22:51:45,850 INFO [main] org.apache.camel.management.DefaultManagementLifecycleStrategy:790 StatisticsLevel at All so enabling load performance statistics
2012-11-22 22:51:45,961 INFO [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:119 Found 3 packages with 15 @Converter classes to load
2012-11-22 22:51:45,995 INFO [main] org.apache.camel.impl.converter.DefaultTypeConverter:405 Loaded 170 core type converters (total 170 type converters)
2012-11-22 22:51:46,002 INFO [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:109 Loaded 2 @Converter classes
2012-11-22 22:51:46,023 INFO [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:119 Found 1 packages with 1 @Converter classes to load
2012-11-22 22:51:46,024 WARN [main] org.apache.camel.impl.converter.DefaultTypeConverter:257 Overriding type converter from: StaticMethodTypeConverter: public static org.apache.activemq.command.ActiveMQDestination org.apache.camel.component.activemq.ActiveMQConverter.toDestination(java.lang.String) to: StaticMethodTypeConverter: public static org.apache.activemq.command.ActiveMQDestination org.apache.activemq.camel.converter.ActiveMQConverter.toDestination(java.lang.String)
2012-11-22 22:51:46,043 INFO [main] org.apache.camel.impl.converter.DefaultTypeConverter:431 Loaded additional 3 type converters (total 173 type converters) in 0.041 seconds
2012-11-22 22:51:46,360 INFO [main] org.apache.camel.converter.jaxb.JaxbDataFormat:277 Creating JAXBContext with contextPath: pl.grzejszczak.marcin.camel.jaxb.generated and ApplicationContextClassLoader: sun.misc.Launcher$AppClassLoader@35a16869
2012-11-22 22:51:46,500 INFO [main] org.apache.camel.spring.SpringCamelContext:1980 Route: route1 started and consuming from: Endpoint[activemq://topic:Initial.Topic]
2012-11-22 22:51:46,509 INFO [main] org.apache.camel.spring.SpringCamelContext:1409 Total 1 routes, of which 1 is started.
2012-11-22 22:51:46,510 INFO [main] org.apache.camel.spring.SpringCamelContext:1410 Apache Camel 2.9.2 (CamelContext: camel) started in 0.901 seconds
2012-11-22 22:51:46,519 INFO [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:52:08,375 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.service.EnrichingServiceImpl:21 Enriching player details
2012-11-22 22:52:08,377 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.enricher.AgeEnricher:17 Enriching player [Lewandowski] with age data
2012-11-22 22:52:10,379 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.enricher.ClubEnricher:16 Enriching player [Lewandowski] with club data
2012-11-22 22:52:12,462 DEBUG [jmsDestinationContainer-1] pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl:35 Message already enriched! Shutting down the system

We can see that the Camel Context has been initialized and then the bean that we have created in the jmsApplicationContext.xml that is listening to the final destination is acknowledging that the message has been enriched properly.

What about the ActiveMQRouter.java logs?


2012-11-22 22:52:06,077 INFO  [main] org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@43462851: startup date [Thu Nov 22 22:52:06 CET 2012]; root of context hierarchy
2012-11-22 22:52:06,153 INFO [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/jmsApplicationContext.xml]
2012-11-22 22:52:06,417 INFO [main] org.springframework.context.annotation.ClassPathBeanDefinitionScanner:210 JSR-330 'javax.inject.Named' annotation found and supported for component scanning
2012-11-22 22:52:06,721 INFO [main] org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:177 Loading properties file from class path resource [camel/jms.properties]
2012-11-22 22:52:06,733 INFO [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor:139 JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2012-11-22 22:52:06,758 INFO [main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@362f0d54: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,AgeEnricher,ClubEnricher,PlayerDetailsConverter,finalListenerImpl,playerDetailsSenderImpl,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,activeMQConnectionFactory,cachingConnectionFactory,origin,destination,producerTemplate,originPlayerSender,destinationListenerImpl,jmsDestinationContainer,oxmMessageConverter,enrichingService,marshaller,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-11-22 22:52:07,224 INFO [main] org.springframework.oxm.jaxb.Jaxb2Marshaller:436 Creating JAXBContext with classes to be bound [class pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails]
2012-11-22 22:52:07,628 INFO [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:52:07,883 INFO [main] org.springframework.jms.connection.CachingConnectionFactory:291 Established shared JMS Connection: ActiveMQConnection {id=ID:marcin-SR700-53586-1353621127755-1:1,clientId=null,started=false}
2012-11-22 22:52:08,093 DEBUG [main] pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl:26 Sending [pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails@3ea86d12] to topic [topic://Initial.Topic]
2012-11-22 22:52:12,463 DEBUG [jmsDestinationContainer-1] pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl:35 Message already enriched! Shutting down the system

First we see that our spring Context has been initialized and then we see that a message has been sent to the Initial.Topic. At the end of the processing we can see that the listener is confirming that the message has been properly enriched - so all the Camel work has been done in a proper way.

This example is showing how easy and simple it can be to create a routing / enriching service by means of Spring and Camel (integrated with Spring).

The sources are available at Too Much Coding's repository at bitbucket.

Copyright © 2012 Codding News All Right Reserved