Drools and Maven example project

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

In the following tutorial we will learn how to create a basic Maven based Drools project and run a sample rule on it.

Please note this tutorial has been updated to run with the lastest Drools 6.x version.

The prerequisite to this tutorial is that you have installed Maven on your pc. We will learn at first how to create a project from the shell. As an alternative, you can use an IDE like Eclipse with jBPM plugin or JBoss Developer Studio.

Create a new Maven Project

In order to get started you just need a basic Maven archetype which can be used to set up an initial structure for our projects. The maven-archetype-quickstart can be used for this purpose. From a shell, issue the following command:

mvn archetype:generate -DgroupId=com.sample.app -DartifactId=my-app

       -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Add Drools dependencies

Once done with the archetype, let's work on the pom.xml file which contains our Maven project model. There, we are going to set the Drools dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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>com.sample</groupId>
	<artifactId>DroolsMaven</artifactId>
	<version>1.0.0-SNAPSHOT</version>

	<name>Drools :: Sample Maven Project</name>
	<description>A sample Drools Maven project</description>

	<properties>
		<runtime.version>6.4.0.Final</runtime.version>
	</properties>

	<repositories>
		<repository>
			<id>jboss-public-repository-group</id>
			<name>JBoss Public Repository Group</name>
			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
				<updatePolicy>never</updatePolicy>
			</releases>
			<snapshots>
				<enabled>true</enabled>
				<updatePolicy>daily</updatePolicy>
			</snapshots>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>org.kie</groupId>
			<artifactId>kie-api</artifactId>
			<version>${runtime.version}</version>
		</dependency>
		<dependency>
			<groupId>org.drools</groupId>
			<artifactId>drools-core</artifactId>
			<version>${runtime.version}</version>
		</dependency>
		<dependency>
			<groupId>org.drools</groupId>
			<artifactId>drools-compiler</artifactId>
			<version>${runtime.version}</version>
		</dependency>
	</dependencies>
</project>

Add Classes and Rules

Ok, now we need to set up a simple Rule which is based on the Account class. This rule will issue a warning if the Account class' balance will drop below a certain value.

package com.sample.model;

public class Account {
    private Integer balance;


    public Account() {}
    public Integer getBalance() {
        return balance;
    }
    public void setBalance(Integer balance) {
        this.balance = balance;
    }
    public Account(Integer balance) {
        super();
        this.balance = balance;
    }
    public void withdraw(int money) {
        balance -= money;
    }
}

And here's our simple Rule:

package demo
import com.sample.model.Account
rule "accountBalanceAtLeast"
  when
  $account : Account( balance < 100 )
  then
  System.out.println("Warning! money running out!");
end
						

And now, let's code a simple Main class which will instantiate our process:

package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import com.sample.model.Account;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsTest {

    public static final void main(String[] args) {
        try {
            // load up the knowledge base
	        KieServices ks = KieServices.Factory.get();
    	    KieContainer kContainer = ks.getKieClasspathContainer();
        	KieSession kSession = kContainer.newKieSession("ksession-rules");

            // go !
            Account account = new Account(200);
            account.withdraw(150);
            kSession.insert(account);
            kSession.fireAllRules();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

The Kie Session is declared in the file META-INF/kmodule.xml:

<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
    <kbase name="rules" packages="rules">
        <ksession name="ksession-rules"/>
    </kbase>
</kmodule>

Now last thing in order to run our main class is a maven compiler plugin and the maven exec plugin which is configured to run as main class com.sample.app.Test1

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.1.1</version>
                <executions>
                    <execution>
                        <phase>test</phase>
                        <goals>
                            <goal>java</goal>
                        </goals>
                        <configuration>
                            <mainClass>com.sample.DroolTest</mainClass>

                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>jboss</id>
            <name>jboss</name>
            <url>https://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

You can compile and test your example using:

mvn install test

The expected output is:

Warning! money running out!=============================Today is  Mon Apr 22 17:30:47 CEST 2013
[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------[INFO] Total time: 4.649s
[INFO] Finished at: Mon Apr 22 17:30:47 CEST 2013
[INFO] Final Memory: 15M/109M
[INFO] ------------------------------------------------------------------------

Running the Demo with CDI

It is notwworthy to mention that CDI is now tightly integrated into the KIE API. It can be used to inject versioned KieSession and KieBases. Here is how to rewrite the above example using CDI:

package com.sample;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.kie.api.cdi.KSession;
import org.kie.api.runtime.KieSession;

import com.sample.model.Account;

import javax.inject.Inject;
import java.io.PrintStream;

public class CDIExample {

    @Inject
    @KSession("ksession-rules")
    KieSession kSession;

    public void go(PrintStream out) {
     	Account account = new Account(200);
        account.withdraw(150);
        kSession.insert(account);
        kSession.fireAllRules();
    }

    public static void main(String[] args) {
        Weld w = new Weld();

        WeldContainer wc = w.initialize();
        CDIExample bean = wc.instance().select(CDIExample.class).get();
        bean.go(System.out);

        w.shutdown();
    }

}

In terms of dependencies you have to include the following additonal dependencies in your project:

<properties>
	<runtime.version>6.4.0.Final</runtime.version>
	<cdi.version>1.2</cdi.version>
        <weld.version>2.3.2.Final</weld.version>
</properties>


<dependency>
	<groupId>javax.enterprise</groupId>
    	<artifactId>cdi-api</artifactId>
    	<version>${cdi.version}</version>
</dependency>
<dependency>
    	<groupId>org.jboss.weld.se</groupId>
    	<artifactId>weld-se-core</artifactId>
    	<version>${weld.version}</version>
</dependency>
<dependency>
    	<groupId>org.kie</groupId>
    	<artifactId>kie-ci</artifactId>
    	<version>${runtime.version}</version>
 </dependency>

This project is available on github at Drool Maven project


Advertisement

JBoss CheatSheet for Admins