jQuery UI Dialog Wrapper
Jquery UI dialog is a must for a application I am developing, but it is pretty annoying to use. I decided to create a small jquery dialog wrapper because I wanted to combine the beautifulness of jquery dialog and the simplicity of javascript alert dialog.
The code I wrote is:
function createButtonDialog(title, text, width, height, acceptFunction, cancelFunction) {
var date = new Date();
var id = date.getMinutes().toString() + date.getSeconds().toString() + date.getMilliseconds().toString();
$(document.body).append('<div id="' + id + '" style="display: none;">' + text + '</div>');
var buttons = {};
if (acceptFunction) {
buttons["OK"] = acceptFunction;
}
if (cancelFunction) {
buttons["Cancel"] = cancelFunction;
}
$("#" + id).dialog({
buttons: buttons,
title: title,
height: height,
width: width,
modal: true,
resizable: false
});
}
function createDialog(title, text, width, height) {
createButtonDialog(title, text, width, height, function () { $(this).dialog("close") }, undefined);
}
function createSmallDialog(title, text) {
createDialog(title, text, 300, 140);
}
Now I can simply call:
showSmallDialog(“Error”, “Something went wrong”);
Removing a lot of unnecessary lines and making the code more clear
Jenkins configuration
Jenkins is an open source continuous integration server, it is a MUST if your working with many projects at the same time or if your trying to test your application in multiple platforms.
The first step is to download the Jenkins war from http://mirrors.jenkins-ci.org/war/latest/ .
I am going to deploy Jenkins with JBoss 7, so our next step is to download it from http://www.jboss.org/jbossas/downloads/ and then unzip it.
Then move the Jenkins war to <jboss_folder>/standalone/deployments and execute <jboss_folder>/bin/standalone.bat (or standalone.sh if your using linux) in order to deploy Jenkins.
Then you have to open your favourite browser and go to http://localhost:8080/jenkins/.
Now we have to configure Jenkins. Go to Manage Jenkins and then to Configure System.
Now click on the Add JDK, add the jdk home and then do the same to the Add Maven and Add Git options.
DON’T FORGET TO SAVE THE CONFIGURATION!
Now your probably back in the dashboard, click on Add Job to add our first project to Jenkins. Click on maven2/3 project, write the job name and click OK.
Now we have to configure where to get the source code and how ofter we run the builds, we are going to use Git as our revision control system and we are going to check for updates to build every 15 minutes.
Save your configuration and run your new Jenkins job!
Drools: Good practices writing rules
Writing rules that do their job, are easy to read and are efficient is everyone's goal, but how can we achieve that? The idea of this post is to share some tips that will help you improve your rule writing skills.
No matter what programming language you are using, premature optimization always leads to complex code with almost no profit at all. Drools is the exception to this rule, often improving its performance leads to cleaner and simpler code.
Avoid unnecessary constrain expressions (CE):
Unnecessary CE lead to complex code, always try to check if your contrains overlap with each other.
Eval:
When you want to call an object method that doesn't follow the JavaBeans convention you have to use the eval function. The eval function allows you to execute any Java code that returns a boolean as result. Although it might sound as a solution for everything, it has a HUGE drawback, it cannot be optimized by Drools. The expression has to be reevaluated every time a fact is added, modified or removed.
In other words, use it only when you run out of choices.
Testing:
In my opinion, testing is essential in any application. I strongly recommend you to have one test per rule. Having one test per rule allows you be certain that your rules are working, allowing you to refactor your rules without the fear of breaking anything. I might go deeper on testing in another article because it is an important topic.
You can see some examples of rule testing here: https://github.com/plugtree/spotplug/blob/master/spotplug-core/src/test/java/RulesTest.java
Right order of patterns:
When choosing the right order of patterns you have to take a few things into
account:
- The rete algorithm does not evaluate unnecessary constrains, it stops evaluating constrains as soon as one of them fails. Most of the times, those constrains that are more likely to fail should be before those that are not.
- One way to improve the performance and memory consumption of your drools application is node sharing. Node sharing happens when two or more patterns start in the same way. The Rete algorithm optimizes this situation using only one constrain-node [1] for the shared constrain instead of one for each rule. If you use node sharing, you will not only achieve a lower memory consumption but now the shared constrain is evaluated only once!
For example in the following two rules, the patterns share three constrains:
rule “rule A”
when
ClassA(constrain1, constrain2, constrain3)
then
// Do something.
end
rule “rule B”
when
ClassA(constrain1, constrain2, constrain3, constrain4)
then
// Do something.
end
Our rete tree will look like this:
If you take a close look to the rete tree, you can see that three constrains (blue circles) are one after the other, that formation means they are shared by the rules.
Many equal patterns:
When you are writing rules, you might end up with many rules that share the same pattern order. Writing the same patterns over and over again is a waste of time. Luckily, there is an elegant way to solve it.
The solution is to add a new rule that inserts a new fact when the shared pattern is matched. Then we match that new fact as a replace of the full pattern in the other rules.
Following the example above, our rules will end up looking like this:
Rule “Match a, b and c”
when
A()
B()
C()
then
insert(new MatchABC())
end
Rule “A”
when
MatchABC()
D()
then
//Do something
end
Rule “B”
when
MatchABC()
E()
then
//Do something
end
Another way to do it is using inheritance between rules:
Rule “Match a, b and c”
when
A()
B()
C()
then
end
Rule “A” extends “Match a, b and c”
when
D()
then
//Do something
end
Rule “B” extends “Match a, b and c”
when
E()
then
//Do something
end
The problem with inheritance is that multiple inheritance is not allowed so you might need to use the former approach I mentioned.
Conclusion:
The good practices I mentioned above are going to help you to write cleaner, faster and error-prone rules
I will try to gather more tips and create a new post about them
[1] The Rete algorithm use 1 node for each constrain, for example the pattern User(name == "Leandro", nick == "Dx9") will use 2 nodes.
Drools with Maven and Spring
The idea of this post is to explain how to create a simple Drools project using maven. After creating it, we are going to use Spring to improve it.
If you don’t know what drools is, you can read What is Drools.
The first step in our journey is to create a POJO object to work with. We are going to create a Car class with the attributes price, model and colour.
public class Car {
private int price;
private String colour;
private String model;
// Getters and Setters.
}
Then we are going to create a drools file called rules.drl with two rules. The first rule identifies the cars that are painted in pink and the latter one identifies the cars whose price is higher that 40000.
If your using eclipse, I recommend you to download the Drools Eclipse plugin, using the update-site. This plugin will help you in the task of creating rules.
Our rules will look like this:
rule "Cars painted in pink"
when
$car : Car(colour == pink)
then
//Do something.
end
rule "Cars whose price is higher that 40000"
when
$car : Car(price > 40000)
then
//Do something.
end
In order to use Drools, we need to add the Drools dependencies to the maven configuration file:
<repositories>
<repository>
<id>repository.jboss.org</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-api</artifactId>
<version>5.1.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>5.1.1</version>
<type>jar</type>
</dependency>
</dependencies>
The Drools configuration can be done in a programmatic (plain Java) or declarative way (XML). The first approach I am going to explain is the programmatic way.
Plain Java way:
First we create a KnowledgeBuilder and add our drl file to it.
KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kBuilder.add(ResourceFactory.newFileResource("rules.drl"), ResourceType.DRL);
Then we create a KnowledgeBase and add the packages created by the KnowledgeBuilder.
KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(); kBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
Then we create a session and call a method that inserts facts to it:
StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession(); insertFacts(kSession);
Our main class will end up looking like this:
public class MainNoSpring {
public static void main(String[] args) {
KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kBuilder.add(ResourceFactory.newFileResource("rules.drl"), ResourceType.DRL);
KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
kBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
insertFacts(kSession);
kSession.dispose();
}
private static void insertFacts(StatefulKnowledgeSession kSession) {
Car expensiveCar = new Car("Expensive", "red", 100000);
Car expensivePinkCar = new Car("ExpensivePink", "pink", 80000);
Car commonCar = new Car("Common", "black", 30000);
// Rule “Cars painted in pink" should be fired.
kSession.insert(expensiveCar);
kSession.fireAllRules();
// Both rules should be fired
kSession.insert(expensivePinkCar);
kSession.fireAllRules();
// No rules should be fired
kSession.insert(commonCar);
kSession.fireAllRules();
}
}
Spring way:
First of all, we have to add the Spring dependencies to Maven:
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-spring</artifactId>
<version>5.1.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
Then we need to create the spring configuration file which is trivial:
<drools:kbase id="kBase">
<drools:resources>
<drools:resource type="DRL" source="classpath:rules.drl" />
</drools:resources>
</drools:kbase>
<drools:ksession id="session" type="stateful" kbase="kBase"></drools:ksession>
The last step is to create the main function, which is indeed much simpler:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"/spring.xml"});
StatefulKnowledgeSession session = (StatefulKnowledgeSession)context.getBean("session");
insertFacts(session);
session.dispose();
}
You can download the full code from my git repository. The README contains information about how to execute it.



