New Post

Rss

Tampilkan postingan dengan label Apache Camel. Tampilkan semua postingan
Tampilkan postingan dengan label Apache Camel. Tampilkan semua postingan
Minggu, 03 Februari 2013
Drools decision tables with Camel and Spring

Drools decision tables with Camel and Spring



Hi!

As I've shown it in my previous post JBoss Drools are a very useful rules engine. The only problem is that creating the rules in the Rule language might be pretty complicated for a non-technical person. That's why one can provide an easy way for creating business rules - decision tables created in a spreadsheet!

In the following example I will show you a really complicated business rule example converted to a decision table in a spreadsheet. As a backend we will have Drools, Camel and Spring.




To begin with let us take a look at our imaginary business problem. Let us assume that we are running a business that focuses on selling products (either Medical or Electronic). We are shipping our products to several countries (PL, USA, GER, SWE, UK, ESP) and depending on the country there are different law regulations concerning the buyer's age. In some countries you can buy products when you are younger than in others. What is more depending on the country from which the buyer and the product comes from and on the quantity of products, the buyer might get a discount. As you can see there is a substantial number of conditions needed to be fullfield in this scenario (imagine the number of ifs needed to program this :P ).

Another problem would be the business side (as usual). Anybody who has been working on a project knows how fast the requirements are changing. If one entered all the rules in the code he would have to redeploy the software each time the requirements changed. That's why it is a good practice to divide the business logic from the code itself. Anyway, let's go back to our example.

To begin with let us take a look at the spreadsheets (before that it is worth taking a look at the JBoss website with precise description of how the decision table should look like):


The point of entry of our program is the first spreadsheet that checks if the given user should be granted with the possibility of buying a product (it will be better if you download the spreadsheets and play with them from Too Much Coding's repository at Bitbucket: user_table.xls and product_table.xls, or Github user_table.xls and product_table.xls):

user_table.xls (tables worksheet)


Once the user has been approved he might get a discount:


product_table.xls (tables worksheet)


product_table.xls (lists worksheet)



As you can see in the images the business problem is quite complex. Each row represents a rule, and each column represents a condition. Do you remember the rules syntax from my recent post? So you would understand the hidden part of the spreadsheet that is right above the first visible row:



The rows from 2 to 6 represent some fixed configuration values such as rule set, imports ( you've already seen that in my recent post) and functions. Next in row number 7 you can find the name of the RuleTable. Then in row number 8 you have in our scenario either a CONDITION or an ACTION - so in other words either the LHS or rhe RHS respectively. Row number 9 is both representation of types presented in the condition and the binding to a variable. In row number 10 we have the exact LHS condition. Row number 11 shows the label of columns. From row number 12 we have the rules one by one. You can find the spreadsheets in the sources.

Now let's take a look at the code. Let's start with taking a look at the schemas defining the Product and the User.

Person.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:include schemaLocation="user.xsd"/>

<xsd:element name="Product">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Name" type="xsd:string"/>
<xsd:element name="Type" type="ProductType"/>
<xsd:element name="Price" type="xsd:double"/>
<xsd:element name="CountryOfOrigin" type="CountryType"/>
<xsd:element name="AdditionalInfo" type="xsd:string"/>
<xsd:element name="Quantity" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

<xsd:simpleType name="ProductType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="MEDICAL"/>
<xsd:enumeration value="ELECTRONIC"/>
</xsd:restriction>
</xsd:simpleType>

</xsd:schema>

User.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:include schemaLocation="product.xsd"/>

<xsd:element name="User">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="UserName" type="xsd:string"/>
<xsd:element name="UserAge" type="xsd:int"/>
<xsd:element name="UserCountry" type="CountryType"/>
<xsd:element name="Decision" type="DecisionType"/>
<xsd:element name="DecisionDescription" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

<xsd:simpleType name="CountryType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="PL"/>
<xsd:enumeration value="USA"/>
<xsd:enumeration value="GER"/>
<xsd:enumeration value="SWE"/>
<xsd:enumeration value="UK"/>
<xsd:enumeration value="ESP"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="DecisionType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="ACCEPTED"/>
<xsd:enumeration value="REJECTED"/>
</xsd:restriction>
</xsd:simpleType>

</xsd:schema>

Due to the fact that we are using maven we may use a plugin that will convert the XSD into Java classes.

part of the pom.xml

 <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<packageName>pl.grzejszczak.marcin.drools.decisiontable.model</packageName>
<schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory>
</configuration>
</plugin>
</plugins>
</build>

Thanks to this plugin we have our generated by JAXB classes in the pl.grzejszczak.marcin.decisiontable.model package.

Now off to the drools-context.xml file where we've defined all the necessary beans as far as Drools are concerned:

<?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:drools="http://drools.org/schema/drools-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://drools.org/schema/drools-spring http://drools.org/schema/drools-spring.xsd">

<!-- Grid Node identifier that is registered in the CamelContext -->
<drools:grid-node id="node1"/>

<drools:kbase id="productsKBase" node="node1">
<drools:resources>
<drools:resource type="DTABLE" source="classpath:rules/product_table.xls"/>
</drools:resources>
</drools:kbase>

<drools:ksession id="productsKSession" name="productsKSession" type="stateless" kbase="productsKBase" node="node1"/>

<drools:kbase id="usersKBase" node="node1">
<drools:resources>
<drools:resource type="DTABLE" source="classpath:rules/user_table.xls"/>
</drools:resources>
</drools:kbase>

<drools:ksession id="usersKSession" name="usersKSession" type="stateless" kbase="usersKBase" node="node1"/>

</beans>

As you can see in comparison to the application context from the recent post there are some differences. First instead of passing the DRL file as the resource inside the knowledge base we are providing the Decision table (DTABLE). I've decided to pass in two seperate files but you can provide one file with several worksheets and access those worksheets (through the decisiontable-conf element). Also there is an additional element called node. We have to choose an implementation of the Node interface (Execution, Grid...) for the Camel route to work properly as you will see in a couple of seconds in the Spring application context file. 

applicationContext.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"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:context="http://www.springframework.org/schema/context"
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://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring-2.8.0.xsd">

<import resource="classpath:drools-context.xml"/>
<!-- Show Spring where to search for the beans (in which packages) -->
<context:component-scan base-package="pl.grzejszczak.marcin.drools.decisiontable" />

<camel:camelContext id="camelContext">
<camel:route id="acceptanceRoute">
<camel:from uri="direct:acceptanceRoute"/>
<camel:to uri="drools:node1/usersKSession"/>
</camel:route>
<camel:route id="discountRoute">
<camel:from uri="direct:discountRoute"/>
<camel:to uri="drools:node1/productsKSession"/>
</camel:route>
</camel:camelContext>

</beans>

As you can see in order to access the Drools Camel Component we have to provide the node through which we will access the proper knowledge session. We have defined two routes - the first one ends at the Drools component that accesses the users knowledge session and the other the products knowledge session. 

We have a ProductService interface implementation called ProductServiceImpl that given an input User and Product objects pass them through the Camel's Producer Template to two Camel routes each ending at the Drools components. The concept behind this product service is that we are first processing the User if he can even buy the software and then we are checking what kind of a discount he would receive. From the service's point of view in fact we are just sending the object out and waiting for the response. Finally having reveived the response we are passing the User and the Product to the Financial Service implementation that will bill the user for the products that he has bought or reject his offer if needed.

ProductServiceImpl.java

package pl.grzejszczak.marcin.drools.decisiontable.service;

import org.apache.camel.CamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.decisiontable.model.Product;
import pl.grzejszczak.marcin.drools.decisiontable.model.User;

import static com.google.common.collect.Lists.newArrayList;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@Component("productServiceImpl")
public class ProductServiceImpl implements ProductService {

private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);

@Autowired
CamelContext camelContext;

@Autowired
FinancialService financialService;

@Override
public void runProductLogic(User user, Product product) {
LOGGER.debug("Running product logic - first acceptance Route, then discount Route");
camelContext.createProducerTemplate().sendBody("direct:acceptanceRoute", newArrayList(user, product));
camelContext.createProducerTemplate().sendBody("direct:discountRoute", newArrayList(user, product));
financialService.processOrder(user, product);
}

}

Another crucial thing to remember about is that the Camel Drools Component requires the Command object as the input. As you can see, in the body we are sending a list of objects (and these are not Command objects). I did it on purpose since in my opinion it is better not to bind our code to a concrete solution. What if we find out that there is a better solution than Drools? Will we change all the code that we have created or just change the Camel route to point at our new solution? That's why Camel has the TypeConverters. We have our own here as well. First of all let's take a look at the implementation.

ProductTypeConverter.java


package pl.grzejszczak.marcin.drools.decisiontable.converter;

import org.apache.camel.Converter;
import org.drools.command.Command;
import org.drools.command.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzejszczak.marcin.drools.decisiontable.model.Product;

import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 30.01.13
* Time: 21:42
*/
@Converter
public class ProductTypeConverter {

private static final Logger LOGGER = LoggerFactory.getLogger(ProductTypeConverter.class);

@Converter
public static Command toCommandFromList(List inputList) {
LOGGER.debug("Executing ProductTypeConverter's toCommandFromList method");
return CommandFactory.newInsertElements(inputList);
}

@Converter
public static Command toCommand(Product product) {
LOGGER.debug("Executing ProductTypeConverter's toCommand method");
return CommandFactory.newInsert(product);
}
}

There is a good tutorial on TypeConverters on the Camel website - if you needed some more indepth info about it. Anyway, we are annotating our class and the functions used to convert different types into one another. What is important here is that we are showing Camel how to convert a list and a single product to Commands. Due to type erasure this will work regardless of the provided type that is why even though we are giving a list of Product  and User, the toCommandFromList function will get executed. 

In addition to this in order for the type converter to work we have to provide the fully quallified name of our class (FQN) in the /META-INF/services/org/apache/camel/TypeConverter file.

TypeConverter


pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter

In order to properly test our functionality one should write quite a few tests that would verify the rules. A pretty good way would be to have input files stored in the test resources folders that are passed to the rule engine and then the result would be compared against the verified output (unfortunately it is rather impossible to make the business side develop such a reference set of outputs). Anyway let's take a look at the unit test that verifies only a few of the rules and the logs that are produced from running those rules:

ProductServiceImplTest.java

package pl.grzejszczak.marcin.drools.decisiontable.service.drools;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.grzejszczak.marcin.drools.decisiontable.model.*;
import pl.grzejszczak.marcin.drools.decisiontable.service.ProductService;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.02.13
* Time: 16:06
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ProductServiceImplTest {

private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImplTest.class);

@Autowired
ProductService objectUnderTest;

@Test
public void testRunProductLogicUserPlUnderageElectronicCountryPL() throws Exception {
int initialPrice = 1000;
int userAge = 6;
int quantity = 10;

User user = createUser("Smith", CountryType.PL, userAge);
Product product = createProduct("Electronic", initialPrice, CountryType.PL, ProductType.ELECTRONIC, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);

assertTrue(product.getPrice() == initialPrice);
assertEquals(DecisionType.REJECTED, user.getDecision());
}

@Test
public void testRunProductLogicUserPlHighAgeElectronicCountryPLLowQuantity() throws Exception {
int initialPrice = 1000;
int userAge = 19;
int quantity = 1;

User user = createUser("Smith", CountryType.PL, userAge);
Product product = createProduct("Electronic", initialPrice, CountryType.PL, ProductType.ELECTRONIC, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);

assertTrue(product.getPrice() == initialPrice);
assertEquals(DecisionType.ACCEPTED, user.getDecision());
}

@Test
public void testRunProductLogicUserPlHighAgeElectronicCountryPLHighQuantity() throws Exception {
int initialPrice = 1000;
int userAge = 19;
int quantity = 8;

User user = createUser("Smith", CountryType.PL, userAge);
Product product = createProduct("Electronic", initialPrice, CountryType.PL, ProductType.ELECTRONIC, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);
double expectedDiscount = 0.1;

assertTrue(product.getPrice() == initialPrice * (1 - expectedDiscount));
assertEquals(DecisionType.ACCEPTED, user.getDecision());
}

@Test
public void testRunProductLogicUserUsaLowAgeElectronicCountryPLHighQuantity() throws Exception {
int initialPrice = 1000;
int userAge = 19;
int quantity = 8;

User user = createUser("Smith", CountryType.USA, userAge);
Product product = createProduct("Electronic", initialPrice, CountryType.PL, ProductType.ELECTRONIC, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);

assertTrue(product.getPrice() == initialPrice);
assertEquals(DecisionType.REJECTED, user.getDecision());
}

@Test
public void testRunProductLogicUserUsaHighAgeMedicalCountrySWELowQuantity() throws Exception {
int initialPrice = 1000;
int userAge = 22;
int quantity = 4;

User user = createUser("Smith", CountryType.USA, userAge);
Product product = createProduct("Some name", initialPrice, CountryType.SWE, ProductType.MEDICAL, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);

assertTrue(product.getPrice() == initialPrice);
assertEquals(DecisionType.ACCEPTED, user.getDecision());
}

@Test
public void testRunProductLogicUserUsaHighAgeMedicalCountrySWEHighQuantity() throws Exception {
int initialPrice = 1000;
int userAge = 22;
int quantity = 8;

User user = createUser("Smith", CountryType.USA, userAge);
Product product = createProduct("Some name", initialPrice, CountryType.SWE, ProductType.MEDICAL, quantity);

printInputs(user, product);

objectUnderTest.runProductLogic(user, product);

printInputs(user, product);
double expectedDiscount = 0.25;

assertTrue(product.getPrice() == initialPrice * (1 - expectedDiscount));
assertEquals(DecisionType.ACCEPTED, user.getDecision());
}

private void printInputs(User user, Product product) {
LOGGER.debug(ReflectionToStringBuilder.reflectionToString(user, ToStringStyle.MULTI_LINE_STYLE));
LOGGER.debug(ReflectionToStringBuilder.reflectionToString(product, ToStringStyle.MULTI_LINE_STYLE));
}

private User createUser(String name, CountryType countryType, int userAge){
User user = new User();
user.setUserName(name);
user.setUserCountry(countryType);
user.setUserAge(userAge);
return user;
}

private Product createProduct(String name, double price, CountryType countryOfOrigin, ProductType productType, int quantity){
Product product = new Product();
product.setPrice(price);
product.setCountryOfOrigin(countryOfOrigin);
product.setName(name);
product.setType(productType);
product.setQuantity(quantity);
return product;
}

}

Of course the log.debugs in the tests are totally redundant but I wanted you to quickly see that the rules are operational :) Sorry for the length of the logs but I wrote a few tests to show different combinations of rules (in fact it's better too have too many logs than the other way round :) )



pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@1d48043[
userName=Smith
userAge=6
userCountry=PL
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1e8f2a0[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=10
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Sorry, according to your age (< 18) and country (PL) you can't buy this product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:29 Sorry, user has been rejected...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@1d48043[
userName=Smith
userAge=6
userCountry=PL
decision=REJECTED
decisionDescription=Sorry, according to your age (< 18) and country (PL) you can't buy this product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1e8f2a0[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=10
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@b28f30[
userName=Smith
userAge=19
userCountry=PL
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@d6a0e0[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=1
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations, you have successfully bought the product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Sorry, no discount will be granted.
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:25 User has been approved - processing the order...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@b28f30[
userName=Smith
userAge=19
userCountry=PL
decision=ACCEPTED
decisionDescription=Congratulations, you have successfully bought the product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@d6a0e0[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=Sorry, no discount will be granted.
quantity=1
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@14510ac[
userName=Smith
userAge=19
userCountry=PL
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1499616[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=8
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations, you have successfully bought the product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations - you've been granted a 10% discount!
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:25 User has been approved - processing the order...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@14510ac[
userName=Smith
userAge=19
userCountry=PL
decision=ACCEPTED
decisionDescription=Congratulations, you have successfully bought the product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1499616[
name=Electronic
type=ELECTRONIC
price=900.0
countryOfOrigin=PL
additionalInfo=Congratulations - you've been granted a 10% discount!
quantity=8
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@17667bd[
userName=Smith
userAge=19
userCountry=USA
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@ad9f5d[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=8
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Sorry, according to your age (< 18) and country (USA) you can't buy this product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:29 Sorry, user has been rejected...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@17667bd[
userName=Smith
userAge=19
userCountry=USA
decision=REJECTED
decisionDescription=Sorry, according to your age (< 18) and country (USA) you can't buy this product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@ad9f5d[
name=Electronic
type=ELECTRONIC
price=1000.0
countryOfOrigin=PL
additionalInfo=<null>
quantity=8
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@9ff588[
userName=Smith
userAge=22
userCountry=USA
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1b0d2d0[
name=Some name
type=MEDICAL
price=1000.0
countryOfOrigin=SWE
additionalInfo=<null>
quantity=4
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations, you have successfully bought the product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:25 User has been approved - processing the order...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@9ff588[
userName=Smith
userAge=22
userCountry=USA
decision=ACCEPTED
decisionDescription=Congratulations, you have successfully bought the product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@1b0d2d0[
name=Some name
type=MEDICAL
price=1000.0
countryOfOrigin=SWE
additionalInfo=<null>
quantity=4
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@1b27882[
userName=Smith
userAge=22
userCountry=USA
decision=<null>
decisionDescription=<null>
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@5b84b[
name=Some name
type=MEDICAL
price=1000.0
countryOfOrigin=SWE
additionalInfo=<null>
quantity=8
]
pl.grzejszczak.marcin.drools.decisiontable.service.ProductServiceImpl:31 Running product logic - first acceptance Route, then discount Route
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations, you have successfully bought the product
pl.grzejszczak.marcin.drools.decisiontable.converter.ProductTypeConverter:25 Executing ProductTypeConverter's toCommandFromList method
pl.grzejszczak.marcin.drools.decisiontable.service.ProductService:8 Congratulations, you are granted a discount
pl.grzejszczak.marcin.drools.decisiontable.service.FinancialServiceImpl:25 User has been approved - processing the order...
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@1b27882[
userName=Smith
userAge=22
userCountry=USA
decision=ACCEPTED
decisionDescription=Congratulations, you have successfully bought the product
]
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:151 pl.grzejszczak.marcin.drools.decisiontable.model.Product@5b84b[
name=Some name
type=MEDICAL
price=750.0
countryOfOrigin=SWE
additionalInfo=Congratulations, you are granted a discount
quantity=8
]

In this post I've presented how you can push some of your developing work to your BA by giving him a tool which he can be able to work woth - the Decision Tables in a spreadsheet. What is more now you will now how to integrate Drools with Camel. Hopefully you will see how you can simplify (thus minimize the cost of implementing and supporting) the implementation of business rules bearing in mind how prone to changes they are. I hope that this example will even better illustrate how difficult it would be to implement all the business rules in Java than in the previous post about Drools.

If you have any experience with Drools in terms of decision tables, integration with Spring and Camel please feel free to leave a comment - let's have a discussion on that :)

All the code is available at Too Much Coding repository at Bitbucket and GitHub.


Cheers!
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