Learn

Sunday, 3 December 2017

How to use Drolls Framework in Java API Development Artificial Intelligence




Using Drolls in API Java Development

We looked at the sample rules file Sample.drl in the last section which is generated automatically when creating a demo project with the Eclipse Drools Workbench. We will use the other generated file DroolsTest.java as an illustrative example in this section. The file DroolsTest.java is almost 100 lines long so I will list it in small fragments followed by an explanation of each code fragment. The first thing to note is that the Java client code is in the same package as the rules file:


package com.sample;

import java.io.InputStreamReader;

import java.io.Reader;

import org.drools.RuleBase;

import org.drools.RuleBaseFactory;

import org.drools.WorkingMemory;

import org.drools.compiler.PackageBuilder;

import org.drools.rule.Package;


This main function is an example showing how to use a rule package defined in a rule source file. We will see the definition of the utility method readRule that opens a rule file and returns an instance of class RuleBase shortly. After creating an instance of RuleBase we create an instance of the Message class and add it to open memory:


public class DroolsTest {

public static final void main(String[] args) {

try {
        RuleBase ruleBase = readRule();
        WorkingMemory workingMemory =
         ruleBase.newStatefulSession();
        Message message = new Message();
        message.setMessage( "Hello World" );
        message.setStatus( Message.HELLO );
        workingMemory.insert( message );
        workingMemory.fireAllRules();
     }

catch (Throwable t) {

t.printStackTrace();

}

}

The main method creates a new rule base and working memory. Working memory is responsible for maintaining the “facts” in the system – in this case facts are Plain Old Java Objects (POJOs) that are maintained in a collection.

An instance of class Message is created and its status is set to the constant value Message: HELLO. We saw in the last section how the first example rule has a condition that allows the rule to “fire” if there is an instance of the class message that has its status attribute set to this value.




No comments:

Post a Comment