New Post
Rss
Tampilkan postingan dengan label JBoss Drools. Tampilkan semua postingan
Tampilkan postingan dengan label JBoss Drools. Tampilkan semua postingan
Kamis, 25 Juli 2013
Sabtu, 30 Maret 2013
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:
- The DRL files are big and started to become unmaintainable (for a single field we had for example 4 rules)
- 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
- The BA has to wait for the mapping implementation by the devs until he can test it
- 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:
- The current application is written purely in Java
- 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 from | Mapped to |
|---|---|
| InputSystemEnvelope | OutputSystemEnvelope |
| InputSystemContex | OutputSystemContex |
| RequestId | ResponseId (the Id should be reverted) |
| InputSource | OutputSoutce (constant "UTPUT_SYSTEM") |
| InputDate | OutputDate (converted from dd/MM/yyyy to yy/MM/dd) |
| InputAdditionalData | OutputAdditionalData |
| InputReferenceNo | OutputReferenceNo ( "SOME_PREFIX_" + value from InputReferenceNo + "_SOME_SUFIX") |
| InputTypeOfAction | OutputTypeOfAction (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") |
| Transactions | OutputTransactions |
| Transaction | OutputTransaction ( Attribute Client from Transaction.Client, Attribute ProductType from Transaction.ProductType, and the value "Done") |
| Products | OutputProducts |
| Product having min value | MinProduct |
| Product having max value | MaxProduct |
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.
Label:
Builder,
Decision table,
DSL,
Gradle,
Groovy,
Integration,
JBoss Drools,
MarkupBuilder,
property missing,
XmlSlurper,
XSLT
Minggu, 03 Februari 2013
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);
}
}
ProductTypeConverter.java
package pl.grzejszczak.marcin.drools.decisiontable.converter;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.
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);
}
}
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;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 :) )
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;
}
}
pl.grzejszczak.marcin.drools.decisiontable.service.drools.ProductServiceImplTest:150 pl.grzejszczak.marcin.drools.decisiontable.model.User@1d48043[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.
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
]
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!
Label:
Apache Camel,
Calc,
Decision table,
Excel,
JBoss Drools,
Spring
Rabu, 23 Januari 2013
Drools - Rete Alogrithm explanation
Quite recently I have found a very nice article about the Rete Algorithm.Selasa, 15 Januari 2013
Drools integration with Spring vs manual rules creation
Hi!
Often in your work you can come across with issues related to business logic. Let us assume that you have dozens of rules (for the time being in our project we have more than 50 and I used to work on a project where we had hundreds of those rules) that you have to implement, divide into some classes, subclasses, abstractions and of course unit test. This can be difficult and timeconsuming to both write and support. There are many ways of dealing with this problem and I will show you one of them - JBoss Drools.
Drools is a library specifically created for such purposes like implementing rules. As presented in Wikipedia:
"Drools is a rule engine implementaion based on Charles Forgy's Rete Algorithm tailored for the Java language."It contains a rule engine that can process rules wirtten using the Drools language (you can also provide rules in Excel spreadsheets! - perfect for Business side to support and maintain).
In the following example we will take a look at the way one can integrate JBoss Drools with Spring and an example of solving a similar problem without Drools.
Let us assume that we hava a POJO - a product that can represent either a Medical or Electronic product.
Product.java
package pl.grzejszczak.marcin.drools.springintegration.model;What defines the type of a product is the TypeEnum. It also has an outputString - let's assume that it defines a brand of a product (or whatever you want ;) )
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
public class Product {
private final TypeEnum typeEnum;
private String productName;
public Product(TypeEnum typeEnum) {
this.typeEnum = typeEnum;
productName = typeEnum.getSomeOutputString();
}
public TypeEnum getTypeEnum() {
return typeEnum;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
TypeEnum.java
package pl.grzejszczak.marcin.drools.springintegration.enums;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
public enum TypeEnum {
MEDICAL("medical", "aaabbbccc"), ELECTRONIC("electronic", "cccbbbaaa");
private final String type;
private final String someOutputString;
private TypeEnum(String type, String someOutputString) {
this.type = type;
this.someOutputString = someOutputString;
}
public String getType() {
return type;
}
public String getSomeOutputString() {
return someOutputString;
}
}
Let's say that the logic behind our rools is such that depending on the type of the enum we want to have some processing done (in our case we will have the same type of processing - converting each 'a' to 'b' in the output string).
NoRulesProductServiceImpl.java
package pl.grzejszczak.marcin.drools.springintegration.service.nondrools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.service.Processor;
import pl.grzejszczak.marcin.drools.springintegration.service.ProductService;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@Component("NoRulesProductServiceImpl")
public class NoRulesProductServiceImpl implements ProductService {
private static final Logger LOGGER = LoggerFactory.getLogger(NoRulesProductServiceImpl.class);
@Autowired
@Qualifier("ProductProcessingService")
private Processor<List<Product>> productProcessingService;
@Override
public void runProductLogic() {
LOGGER.debug("Running product logic without Drools");
Product medicalProduct = new Product(TypeEnum.MEDICAL);
Product electronicProduct = new Product(TypeEnum.ELECTRONIC);
LOGGER.debug("Running rules for products...");
productProcessingService.process(newArrayList(medicalProduct, electronicProduct));
LOGGER.debug("...finished running products.");
}
}
The ProductProcessingService is itterating over the given products, finds a producer for them and processes them.
ProductProcessingService.java
package pl.grzejszczak.marcin.drools.springintegration.service.nondrools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.springintegration.factory.ProcessingFactory;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.service.Processor;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@Component("ProductProcessingService")
public class ProductProcessingService implements Processor<List<Product>> {
@Autowired
@Qualifier("NoRulesProcessingFactory")
private ProcessingFactory<Processor, Product> processingFactory;
@Override
public void process(List<Product> input) {
for(Product product : input){
Processor<Product> processor = processingFactory.createProcessingObject(product);
processor.process(product);
}
}
}
The ProcessingFactory is an interface that basing on the given input (Product) produces an ouput (Processor) that afterwards does further processing. In our case we have a factory that instead of using a bunch of ifs (imagine that we have more than just two types of products) is using a map that matches a type of product with an implementation of a processor. As you can see we change a sequence of ifs into a single get.
NoRulesProcessingFactory.java
package pl.grzejszczak.marcin.drools.springintegration.factory.nondrools;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.factory.ProcessingFactory;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.service.nondrools.ElectronicProductProcessingService;
import pl.grzejszczak.marcin.drools.springintegration.service.nondrools.MedicalProductProcessingService;
import pl.grzejszczak.marcin.drools.springintegration.service.Processor;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@Component("NoRulesProcessingFactory")
public class NoRulesProcessingFactory implements ProcessingFactory<Processor, Product> {
private static final Map<TypeEnum, Processor> PROCESSOR_MAP = new ImmutableMap.Builder<TypeEnum, Processor>().
put(TypeEnum.MEDICAL, new MedicalProductProcessingService()).
put(TypeEnum.ELECTRONIC, new ElectronicProductProcessingService()).
build();
/**
* By using the map we don't have any ifs
* @param inputObject
* @return
*/
@Override
public Processor createProcessingObject(Product inputObject) {
return PROCESSOR_MAP.get(inputObject.getTypeEnum());
}
}
I will present here only one ProcessingService since the other one is exactly the same (I just wanted to show the concept).
ElectronicProductProcessingService.java
package pl.grzejszczak.marcin.drools.springintegration.service.nondrools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.service.Processor;
import pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
public class ElectronicProductProcessingService implements Processor<Product> {
private static final Logger LOGGER = LoggerFactory.getLogger(ElectronicProductProcessingService.class);
@Override
public void process(Product input) {
checkArgument(TypeEnum.ELECTRONIC.equals(input.getTypeEnum()), "This processing service works only for electronic devices");
checkArgument(!SomeUtil.replaceAWithB(input.getProductName()).equals(input.getProductName()), "The input has already been processed");
LOGGER.debug("Running processing for Electronic Product");
input.setProductName(SomeUtil.replaceAWithB(input.getProductName()));
LOGGER.debug(format("ELECTRONIC rule applied without Drools, product name is now equal to [%s]", input.getProductName()));
}
}
As you can see there are quite a few things that need to be tested and supported here. Imagine what would happen if we had 100 of types with more sophisticated rules than merely replacing one letter with the other. So how can we do it with Drools? Let's start with taking a look at the pom.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"Let's take a look at the applicationContext.xml and the drools-context.xml. As for the first one what we do in fact is just showing where to scan for classes in terms of Spring and where to import the drools context from.
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.grzejszczak.marcin</groupId>
<artifactId>drools-spring-integration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<spring.version>3.1.1.RELEASE</spring.version>
</properties>
<repositories>
<repository>
<id>spring-release</id>
<url>http://maven.springframework.org/release</url>
</repository>
</repositories>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>13.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-spring</artifactId>
<version>5.4.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
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: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">
<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.springintegration" />
</beans>
The context for drools. Take a look at the aliases for productsKSession. By providing alias we are joining two potential knowledge sessions into a single one. A single knowledge session is defined for a single knowledge base. For the knowledge base we are providing the list (in our case just a single resource) of drl files (we could have provided an excel spreadsheet).
drools-context.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: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">
<!-- KNOWLEDGE BASE FOR A GIVEN TYPE -->
<drools:kbase id="productsKBase">
<drools:resources>
<drools:resource type="DRL"
source="classpath:rules/products.drl"/>
</drools:resources>
</drools:kbase>
<drools:ksession id="productsKSession" name="productsKSession" type="stateless" kbase="productsKBase"/>
<alias name="productsKSession" alias="electronicKSession"/>
<alias name="productsKSession" alias="medicalKSession"/>
</beans>
Let's check the drl file.
We define two rules - "MEDICAL rule" and "ELECTRONIC rule". For each case we are checking:
- whether the input object is of Product type
- whether it has typeEnum equal to either Medical or Electronic
- whether it hasn't already had it's productName changed
Then we are addressing the product by means of a variable $product. We are modifying the product using the modify keyword (which means that all the rules are rechecked - try removing the condition 'productName != replaceAWithB($product.typeEnum.someOutputString' and you will have an endless loop) by setting a new productName. Take a look at all the imports and imports of functions. You can execute a static function (pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil.replaceAWithB or org.drools.core.util.StringUtils.isEmpty) by importing it in the drl file.
At the end we are logging that a rule has been applied.
products.drl
package pl.grzejszczak.marcin
import org.slf4j.LoggerFactory
import pl.grzejszczak.marcin.drools.springintegration.DroolsSpring
import pl.grzejszczak.marcin.drools.springintegration.model.Product
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum
import function pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil.replaceAWithB
import function org.drools.core.util.StringUtils.isEmpty
rule "MEDICAL rule"
dialect "mvel"
when
$product : Product( typeEnum == TypeEnum.MEDICAL, productName != replaceAWithB($product.typeEnum.someOutputString) )
then
modify ($product) {productName = replaceAWithB($product.typeEnum.someOutputString)}
LoggerFactory.getLogger(DroolsSpring.class).debug(String.format("MEDICAL rule applied, product name is now equal to [%s]", $product.productName))
end
rule "ELECTRONIC rule"
dialect "mvel"
when
$product : Product( typeEnum == TypeEnum.ELECTRONIC, productName != replaceAWithB($product.typeEnum.someOutputString) )
then
modify ($product) {productName = replaceAWithB($product.typeEnum.someOutputString)}
LoggerFactory.getLogger(DroolsSpring.class).debug(String.format("ELECTRONIC rule applied, product name is now equal to [%s]", $product.productName))
end
We use a factory that is choosing a proper StatelessKnowledgeSession - since we only want to modify an input object. In order to run Drools rules we are running the execute method with a list of input objects.
ProductServiceImpl.java
package pl.grzejszczak.marcin.drools.springintegration.service.drools;Now let's have a look on how the factory is implemented. We are using aliases in the applicationContext.xml
import org.drools.runtime.StatelessKnowledgeSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.factory.ProcessingFactory;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.service.ProductService;
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
@Qualifier("ProductProcessingFactory")
ProcessingFactory<StatelessKnowledgeSession, Product> processingFactory;
@Override
public void runProductLogic() {
LOGGER.debug("Running product logic");
Product medicalProduct = new Product(TypeEnum.MEDICAL);
Product electronicProduct = new Product(TypeEnum.ELECTRONIC);
StatelessKnowledgeSession statelessKnowledgeSession = processingFactory.createProcessingObject(medicalProduct);
LOGGER.debug("Running rules for products...");
statelessKnowledgeSession.execute(newArrayList(medicalProduct, electronicProduct));
LOGGER.debug("...finished running products.");
}
}
ProductProcessingFactory.java
package pl.grzejszczak.marcin.drools.springintegration.factory.drools;Now how can we test if it works? I have two unit tests that prove it (they are not running in perfect isolation but they functionality of both approaches). Starting with the test for the manual rules creation test.
import org.drools.runtime.StatelessKnowledgeSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import pl.grzejszczak.marcin.drools.springintegration.factory.ProcessingFactory;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@Component("ProductProcessingFactory")
public class ProductProcessingFactory implements ProcessingFactory<StatelessKnowledgeSession, Product> {
@Autowired
private ApplicationContext applicationContext;
@Override
public StatelessKnowledgeSession createProcessingObject(Product inputObject) {
return (StatelessKnowledgeSession)applicationContext.getBean(inputObject.getTypeEnum().getType() + "KSession");
}
}
NoRulesProductServiceImplTest.java
package pl.grzejszczak.marcin.drools.springintegration.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class NoRulesProductServiceImplTest {
@Autowired
@Qualifier("ProductProcessingService")
private Processor<List<Product>> productProcessingService;
/**
* Test is not run in perfect isolation - the purpose is to show the outcome of processing without Drools
*
* @throws Exception
*/
@Test
public void testRunProductLogic() throws Exception {
Product medicalProduct = new Product(TypeEnum.MEDICAL);
Product electronicProduct = new Product(TypeEnum.ELECTRONIC);
String initialMedicalProductName = medicalProduct.getProductName();
String initialElectronicProduct = electronicProduct.getProductName();
System.out.println(format("Initial productName for Medical [%s]", medicalProduct.getProductName()));
System.out.println(format("Initial productName for Electronic [%s]", electronicProduct.getProductName()));
productProcessingService.process(newArrayList(medicalProduct, electronicProduct));
String finalMedicalProduct = medicalProduct.getProductName();
String finalElectronicProduct = electronicProduct.getProductName();
assertNotSame(finalMedicalProduct, initialMedicalProductName);
assertNotSame(finalElectronicProduct, initialElectronicProduct);
assertEquals(SomeUtil.replaceAWithB(initialMedicalProductName), finalMedicalProduct);
assertEquals(SomeUtil.replaceAWithB(initialElectronicProduct), finalElectronicProduct);
System.out.println(format("Final productName for Medical [%s]", medicalProduct.getProductName()));
System.out.println(format("Final productName for Electronic [%s]", electronicProduct.getProductName()));
}
}
And the unit test for the Drools approach.
ProductServiceImplTest.java
package pl.grzejszczak.marcin.drools.springintegration.service;Now let's take a look at the logs - take a look that 'Executing some logic' took place 6 times for Drools since when you modify an object the rules are revalidated and rerun:
import org.drools.runtime.StatelessKnowledgeSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.grzejszczak.marcin.drools.springintegration.enums.TypeEnum;
import pl.grzejszczak.marcin.drools.springintegration.factory.ProcessingFactory;
import pl.grzejszczak.marcin.drools.springintegration.model.Product;
import pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 14.01.13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ProductServiceImplTest {
@Autowired
@Qualifier("ProductProcessingFactory")
ProcessingFactory<StatelessKnowledgeSession, Product> processingFactory;
/**
* Test is not run in perfect isolation - the purpose is to show the outcome of processing with Drools
* @throws Exception
*/
@Test
public void testRunProductLogic() throws Exception {
Product medicalProduct = new Product(TypeEnum.MEDICAL);
Product electronicProduct = new Product(TypeEnum.ELECTRONIC);
String initialMedicalProductName = medicalProduct.getProductName();
String initialElectronicProduct = electronicProduct.getProductName();
System.out.println(format("Initial productName for Medical [%s]", medicalProduct.getProductName()));
System.out.println(format("Initial productName for Electronic [%s]", electronicProduct.getProductName()));
StatelessKnowledgeSession statelessKnowledgeSessionForMedical = processingFactory.createProcessingObject(medicalProduct);
StatelessKnowledgeSession statelessKnowledgeSessionForElectronic = processingFactory.createProcessingObject(electronicProduct);
assertTrue(statelessKnowledgeSessionForMedical == statelessKnowledgeSessionForElectronic);
System.out.println("References for stateless sessions are the same, executing rules...");
statelessKnowledgeSessionForMedical.execute(newArrayList(medicalProduct, electronicProduct));
String finalMedicalProduct = medicalProduct.getProductName();
String finalElectronicProduct = electronicProduct.getProductName();
assertNotSame(finalMedicalProduct, initialMedicalProductName);
assertNotSame(finalElectronicProduct, initialElectronicProduct);
assertEquals(SomeUtil.replaceAWithB(initialMedicalProductName), finalMedicalProduct);
assertEquals(SomeUtil.replaceAWithB(initialElectronicProduct), finalElectronicProduct);
System.out.println(format("Final productName for Medical [%s]", medicalProduct.getProductName()));
System.out.println(format("Final productName for Electronic [%s]", electronicProduct.getProductName()));
}
}
org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@743399: startup date [Tue Jan 15 16:32:30 CET 2013]; root of context hierarchy
org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [applicationContext.xml]
org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [drools-context.xml]
[main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3b1d04: defining beans [productsKBase,productsKSession,ProductProcessingFactory,NoRulesProcessingFactory,ProductServiceImpl,NoRulesProductServiceImpl,ProductProcessingService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
pl.grzejszczak.marcin.drools.springintegration.service.drools.ProductServiceImpl:32 Running product logic
pl.grzejszczak.marcin.drools.springintegration.service.drools.ProductServiceImpl:36 Running rules for products...
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.DroolsSpring:? ELECTRONIC rule applied, product name is now equal to [cccbbbbbb]
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.DroolsSpring:? MEDICAL rule applied, product name is now equal to [bbbbbbccc]
pl.grzejszczak.marcin.drools.springintegration.service.drools.ProductServiceImpl:38 ...finished running products.
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.NoRulesProductServiceImpl:33 Running product logic without Drools
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.NoRulesProductServiceImpl:36 Running rules for products...
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.MedicalProductProcessingService:26 Running processing for Medical Product
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.MedicalProductProcessingService:28 MEDICAL rule applied without Drools, product name is now equal to [bbbbbbccc]
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.ElectronicProductProcessingService:26 Running processing for Electronic Product
pl.grzejszczak.marcin.drools.springintegration.utils.SomeUtil:19 Executing some logic
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.ElectronicProductProcessingService:28 ELECTRONIC rule applied without Drools, product name is now equal to [cccbbbbbb]
pl.grzejszczak.marcin.drools.springintegration.service.nondrools.NoRulesProductServiceImpl:38 ...finished running products.
Viola! That's how you can write some rules with Drools that can save plenty of time and effort as far as business logic is concerned. You can find the sources here at my BitBucket repository.
Langganan:
Postingan (Atom)




