Exercise 1: Public Training San Francisco 2014

In this opportunity we’ll go over one of the exercises you will be able to see in the Drools and jBPM Public Training. It involves rule execution for a particular case: 
 

We’re going to represent the scenario of a cat trapped on a limb, and all the things needed to provide solutions to the situation. For that, we will need:

  • Pet: with a name, a type and a position
  • Person: will have a pet assigned to him, and can call the pet down
  • Firefighter: Will be able to get the cat down from the tree as a last resort

Once we have a representation, we need to start defining rules to determine different types of situations and act accordingly: Rule “Call Cat when it is in a tree”
When my Cat is on a limb in a tree
  Then I will call my Cat
Rule “Call the Fire Department”
When my Cat is on a limb and it doesn’t come down when I call
  Then call the Fire Department Rule “Firefighter gets the cat down”
When the Firefighter can reach the Cat
  Then the Firefighter follows steps to retrieve the Cat
Each of these rules will have a specific DRL representation, based on the model we defined: rule "Call Cat when it is in a tree"
    when
        $p: Person($pet: pet, petCallCount == 0)
        $cat: Pet(this == $pet,
             position == "on a limb",
             type == PetType.CAT)
    then
        //$cat.getName() + " come down!"
        $p.setPetCallCount($p.getPetCallCount()+1);
        update($p); end rule "Call the fire department"
    when
        $p: Person($pet: pet, petCallCount > 0)
        $cat: Pet(this == $pet,
            position == "on a limb",
            type == PetType.CAT)
    then
        Firefighter firefighter = new Firefighter("Fred");
        insert(firefighter);
end rule "Firefighter gets the cat down"
    when
        $f: Firefighter()
        $p: Person($pet: pet, petCallCount > 0)
        $cat: Pet(this == $pet, position == "on a limb",
            type == PetType.CAT)
    then
        $cat.setPosition("on the street");
        update($cat);
        retract($f);
end
 

And then, some Java code to end up firing said rules:

KieServices kservices = KieServices.Factory.get(); KieSession ksession = kservices.getKieClasspathContainer().newKieSession();
Person person = new Person("John!");
Pet pet = new Pet("mittens", "on a limb",
Pet.PetType.CAT);
person.setPet(pet);
ksession.insert(person);
ksession.fireAllRules();

When we have these components defined, we will take advantage of the course to start modifying it to see how rules interact with each other, by:

  • Creating rules that insert dogs
  • Creating rules that make dogs chase cats that are on the same place as they are
  • Handling a firefighter that doesn’t show up
  • Anything you can think of!

Stay tuned for more info!

Author

Comments are closed.