Check if Object does not exists in Working Memory in DRL Drools - Java @ Desk

Sunday, February 9, 2014

Check if Object does not exists in Working Memory in DRL Drools

Check if Object does not exists in Working Memory in DRL Drools

In a Drools rule language, an object when inserted into the working memory, is checked in a DRL file as shown below
When
 $object : Object_Name()
Then
 System.out.println("Object Exists");


What if there arise a case, where it is required to check if the object does not exists in the working memory. If so, insert a new object of that type and then proceed further.

This check can be performed using the not operator in drools in a DRL file.

Refer a below example
DRLNoObject.java - Client File
package com.sample;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;


public class DRLNoObject {
 public static final void main(String[] args) {
        try {
            // load up the knowledge base
            KnowledgeBase kbase = readKnowledgeBase();
            StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
            KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
            ksession.fireAllRules();
            logger.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private static KnowledgeBase readKnowledgeBase() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClassPathResource("DRLNoObject.drl"), ResourceType.DRL);
        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if (errors.size() > 0) {
            for (KnowledgeBuilderError error: errors) {
                System.err.println(error);
            }
            throw new IllegalArgumentException("Could not parse knowledge.");
        }
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
        return kbase;
    }

}


DRLNoObject.drl - DRL File
package com.sample


rule "Rule To Check If Object Does Not Exists"
lock-on-active 
salience 90
    when
  not Pojo()
    then
        System.out.println(drools.getRule().getName());
end







No comments:

Post a Comment