Drools Support In Spring Boot 2

Spring Drools

You will see an example on drools support in Spring Boot 2. You might have seen in past example on how to integrate drools in Spring application. I had used Spring Boot version 1.5.9 but here it will support Spring Boot 2.1.5 to 2.7.2 versions. I will not explain about drools in this post and if you want to know on drools then you can check my previous example how to integrate drools in Spring application.

Prerequisites

Java 1.8+, Gradle 5.4.1 – 6.7.1, Maven 3.8.2 – 3.8.5, Drools 7.22.0 – 7.73.0

Project Setup

Create a gradle or maven based project in your favorite IDE or tool.

If you are using maven based project, then you can use the following pom.xml file:

<?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.roytuts</groupId>
	<artifactId>drools-support-spring-boot-2</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>12</maven.compiler.source>
		<maven.compiler.target>12</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.2</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.kie</groupId>
			<artifactId>kie-spring</artifactId>
			<version>7.73.0.Final</version>
		</dependency>

		<dependency>
			<groupId>org.drools</groupId>
			<artifactId>drools-compiler</artifactId>
			<version>7.73.0.Final</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Update the content of the default generated build.gradle script to include the required dependencies.

buildscript {
	ext {
		springBootVersion = '2.1.5.RELEASE' to 2.7.2
	}
	
    repositories {
    	maven {
    		url 'https://plugins.gradle.org/m2/'
    	}
    }
    
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	implementation("org.kie:kie-spring:7.22.0.Final") to 7.50.0.Final
	implementation("org.drools:drools-compiler:7.22.0.Final") to 7.51.0.t20210303
}

Drools Configuration

I want to use Java based configurations so create below java class to create all the required configurations. I will put all rule files under src/main/resources/rules directory.

I have defined few beans for our Spring and Drools integration.

I have created KieFileSystem bean that finds all the rule files put under the classpath file system. These rule files define the rules, which would be applied on the object fields for validation.

I have defined KieContainer bean which is used to create different components, such as, KieSession that is required to create before fire rules on the drools file.

@Configuration
public class SpringDroolsConfig {

	private static final String RULES_PATH = "rules/";

	@Bean
	public KieFileSystem kieFileSystem() throws IOException {
		KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();

		for (Resource file : getRuleFiles()) {
			kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
		}

		return kieFileSystem;
	}

	private Resource[] getRuleFiles() throws IOException {
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
	}

	@Bean
	public KieContainer kieContainer() throws IOException {
		final KieRepository kieRepository = getKieServices().getRepository();

		kieRepository.addKieModule(new KieModule() {
			public ReleaseId getReleaseId() {
				return kieRepository.getDefaultReleaseId();
			}
		});

		KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem()).buildAll();

		Results results = kieBuilder.getResults();
		
		if (results.hasMessages(Message.Level.ERROR)) {
			System.out.println(results.getMessages());
			throw new IllegalStateException("### errors ###");
		}

		return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
	}

	private KieServices getKieServices() {
		return KieServices.Factory.get();
	}

}

Custom Exception

I will create custom exception class to throw exception when validation fails. I will create NumberFormatException class to throw number format exception for non-integer value.

public class NumberFormatException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	public NumberFormatException(String msg) {
		super(msg);
	}
}

VO Class

I will create VO (Value Object) class to use on REST controller.

I will apply validation on code using drools.

public class AreaPin {
	private int code;
	public AreaPin(int code) {
		this.code = code;
	}
	public int getCode() {
		return code;
	}
}

Rule Validation File

Create a file called PinCodeValidation.drl to perform validation on pin code. I will check whether the pin code is 6 digits integer value or not.

The rule validation file must be put into src/main/resources/rules folder as I mentioned earlier. You may put into other location and accordingly you have to change the configuration.

You find AreaPin in when clause is the object and field code is accessed directly by its property name in the AreaPin class.

package com.roytuts.spring.drools.rules

import com.roytuts.spring.drools.vo.AreaPin;
import com.roytuts.spring.drools.exception.NumberFormatException;

rule "PinCodeValidation"
	when
		AreaPin(code != 0 && code not matches "^[0-9]{6}$")
	then
		throw new NumberFormatException("Invalid Area Pin Code. Must be a valid 6 digits number.");
end

REST Controller

The Spring REST controller that handles end users requests/responses is given below.

I want to search the area name for a given pin code using REST service. So before I search into the Map whether the area name will be returned or not, I perform validation on pin code and rule is fired using drools.

Notice how I autowire KieContainer and create KieSession and fire the rule on AreaPin object.

If pin code validation fails then you will see exception in the console as well as on the web page or REST client.

If pin code validation passes then area name will be returned if found or Area not found message will be returned as a default value from the Map.

@RestController
public class AreaRestController {

	@Autowired
	private KieContainer kieContainer;

	@GetMapping("/area/name/{pinCode}")
	public ResponseEntity<String> getAreaByPinCode(@PathVariable int pinCode) {
		KieSession kieSession = kieContainer.newKieSession();
		kieSession.insert(new AreaPin(pinCode)); // which object to validate
		kieSession.fireAllRules(); // fire all rules defined into drool file (drl)
		kieSession.dispose();
		
		return new ResponseEntity<String>(getAreaByCode(pinCode), HttpStatus.OK);
	}

	private String getAreaByCode(int pin) {
		final Map<Integer, String> areaMap = new HashMap<>();
		areaMap.put(700001, "BBD Bag");
		areaMap.put(700010, "Beliaghata");
		areaMap.put(700105, "Nabapally");
		areaMap.put(700098, "Sukanta Nagar");
		
		return areaMap.getOrDefault(pin, "Area not found");
	}

}

Spring Boot Main Class

A class with main method and @SpringBootApplication is enough to start the Spring Boot application.

@SpringBootApplication
public class SpringBoot2Drools {

	public static void main(String[] args) {
		SpringApplication.run(SpringBoot2Drools.class, args);
	}

}

Testing Spring Drools Integration

Run the above main class to deploy into Tomcat server and start the application.

Once the application deployed, it starts on port number 8080 as it is a default port of Tomcat. You may also override this port number in application.properties or application.yml file using key server.port.

If you hit the URL http://localhost:8080/area/name/700098, you will get below output on the browser:

spring boot drools

If you hit the URL http://localhost:8080/area/name/98 in the browser, you will see below exception in the console:

[Request processing failed; nested exception is Exception executing consequence for rule "PinCodeValidation" in com.roytuts.spring.drools.rules: com.roytuts.spring.drools.exception.NumberFormatException: Invalid Area Pin Code. Must be a valid 6 digits number.] with root cause

com.roytuts.spring.drools.exception.NumberFormatException: Invalid Area Pin Code. Must be a valid 6 digits number.

That’s all about how to use drools in Spring framework.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *