Drools5 Community Training Module 3 Drools Expert DRL Syntax

Mauricio (Salaboy) Salatino
Mauricio (Salaboy) SalatinoPrincipal Software Engineer at LearnK8s
 
                               
Drools5 Community Training
      Sponsored by Plugtree
Module 3: Drools Expert 
     DRL Syntax
   Drools5 Community Training
      version: 1.0-SNAPSHOT
     Release Date: 03/16/2011
Under The Creative Common License
Module 3: Drools Expert 
      DRL Syntax
 Drools5 Community Training Course
  by Mauricio "Salaboy" Salatino and
  Esteban Aliverti is licensed under a
  Creative Commons Attribution 3.0
            Unported License.
Based on a work at salaboy.wordpress.
                  com.
 Permissions beyond the scope of this
   license may be available at http:
       //salaboy.wordpress.com/.
Agenda

● Introduction to Drools Expert
● Drools DRL syntax introduction
    ○ LHS Conditional Elements
    ○ RHS
    ○ Rules attributes
    ○ Queries
● Drools 5.x APIs introduction
Drools Expert Introduction

● Drools Expert is the rule engine core
● Lets us express Business Rules
● It will be in charge of making inferences to get new
  conclusions
Components interaction
Rules Execution Cycle 
Business Rule Structure
package ...
import ...
global ...

rule "My Rule"
    <Attributes>
    when <LHS>
        Song(genre == "Jazz") <CEs>
    then <RHS>
        System.out.println("Hi John!");
end
LHS - Conditional Elements

● Pattern



● e.g.
Song(genre == "Jazz")
$song: Song(genre == "Jazz" || == "Avantgarde")
$song: Song(duration > 360, $genre: genre == "Jazz")
LHS - Conditional Elements

● Field Operators



● e.g.

Song( lyrics matches "AZ-az[drink]" )
Song( authors contains "John Zorn" )
Song( author memberof $greatMusicians )
LHS - Conditional Elements

● AND



  e.g. Person( name == "John" ) AND Pet(type == "cat")
● OR


 e.g. Policewoman (age > 30) OR Fireman(age > 31)
LHS - Conditional Elements

● eval



  e.g. eval( song.isJazz() )
● not


 e.g. not( Song( genre == "Pop") )
LHS - Conditional Elements

● exists



  e.g. exists ( Song(genre == "Jazz"))
● forall


 e.g. forall ( Song()
       Song(genre == "Jazz") )
LHS - Conditional Elements

from CE


 ● e.g.
  $playlist: Playlist()
  Song() from $playlist.songs

  $playlist: Playlist()
  Song(genre == "Jazz") from $playlist.songs
LHS - Conditional Elements

● from


● e.g.
  global HibernateSession hbn;

 $playlist: Playlist()
 Song() from hbn.namedQuery("SongByArtist")
                 .setParameter("artist","John Zorn")
                 .getResultList();
LHS - Conditional Elements

● Collect




● e.g.
  $songs: ArrayList() from collect
       (Song(genre == "Jazz", year > 2000))
LHS - Conditional Elements

● Accumulate
LHS - Conditional Elements
 ● Accumulate CE:
<result pattern> from accumulate( <source pattern>,
                           init( <init code> ),
                           action( <action code> ),
                           reverse( <reverse code> ),
                           result( <result expression>))
 ● e.g.
 $playlist: Playlist()
 $jazzSongs: Number( doubleValue > 100 ) from
       accumulate( Song(playlist == $playlist, genre == "Jazz"),
                   init( double total = 0; ),
                   action( total += 1; ),
                   reverse( total -= 1; ),
                   result( total ))
LHS - Conditional Elements

 ● Accumulate Function Examples
  $playlist: Playlist()
  $total: Number( doubleValue > 100 )
from                         accumulate(
                  $song: Song(
                    playlist == $playlist,
                    genre == "Jazz"),
                 count($song))
LHS - Conditional Elements


● Accumulate out-of-the-box Functions
   ○ average
   ○ min
   ○ max
   ○ count
   ○ sum
LHS - Conditional Elements

● Accumulate custom function
$playlist: Playlist()
 $total: Number( doubleValue > 100 ) from
             accumulate( $song: Song(
                         playlist == $playlist),
                         myCustomFc($song.duration))


● We can plug our custom function here. We just need to
  implement the AccumulateFunction interface.
Nesting CEs
● Drools support nested CEs

  $petshop: PetShop()
  $total: Number( doubleValue > 10 ) from accumulate(
          $pet: Pet(petshop == $petshop,
                type == PetType.Cat)
       from $hbm.getNamedQuery("getPetsFromPetshopId")
          .setParamenter("petshopid",$petshop.getId())
          .list(), count ($pet) )
Right Hand Side
● Set of actions
● MVEL or Java (http://mvel.codehaus.org/)
● We will have a set of methods to modify the working
  memory status
   ○ insert()
   ○ modify() / update ()
   ○ retract()
           rule "Fire ! ! !"
               when
                    Fire()
               then
                    insert(new Alarm());
           end
Rule Attributes
Rule Attributes - no loop

● no-loop

i.e.
  rule "infinite activation loop"
      no-loop true
      when
           $person: Person(age > 21)
      then
           update($person){
               setName("John");
           }
  end
Rule Attributes - salience
 ● salience (higher priority first)
rule "rule with priority"
    salience 10
    when
         $song: Song()
    then
         System.out.println("Rule with higher priority Fired!");
end
rule "rule with less priority"
    salience 5

   when
          $song: Song()
   then
          System.out.println("Rule with lower priority Fired!");
end
Rule Attributes - agenda-group 
rule "Playlist ready"
          agenda-group "Create Playlist"
          when
               Playlist(size == 3)
          then
               //Set the focus to "Play playlist" agenda-group
               kcontext.getKnowledgeRuntime().getAgenda()
               .getAgendaGroup("Play playlist").setFocus();
      end

      rule "Play playlist"
          agenda-group "Play playlist"
          when
               $pl : Playlist()
          then
               $pl.play();
      end
Rule Attributes - lock-on-active

rule "Fill playlist"                rule "Number Songs"
   salience 1                          salience 2
   lock-on-active                      lock-on-active
   agenda-group "Create Playlist"      agenda-group "Create Playlist"
   when                                when
      $pl : Playlist()                    $song : Song()
      $song : Song()                   then
   then                                   modify($song){
      modify($pl){                          setName(
        addSong($song);                        index.getAndIncrement()+
      }                                        "_"+ $song.getName());
end                                       }
                                    end
Queries

Example

 query "Get Persons by Name" (String name)
  Person(name = :name)
end
Drools Expert APIs
KnowledgeBuilder
  KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
// Add our rules
kbuilder.add(new ClassPathResource("rules.drl"), ResourceType.DRL);
//Check for errors during the compilation of the rules
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
   for (KnowledgeBuilderError error : errors) {
         System.err.println(error);
   }
   throw new IllegalArgumentException("Could not parse knowledge.");
 }
KnowledgeBase
  // Create the Knowledge Base
     KnowledgeBase kbase = KnowledgeBaseFactory.
newKnowledgeBase();
  // Add the binary packages (compiled rules) to the Knowledge
Base
     kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
KnowledgeSession
 // Create a StatefulSession using the KnowledgeBase that
 // contains the compiled knowledge
StatefulKnowledgeSession ksession =
                         kbase.newStatefulKnowledgeSession();

// We can add a runtime logger to understand what is going on
// inside the Engine
KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
// Insert a new Fact inside my world
FactHandle myFactHandle = ksession.insert(new Person("Myself"));
// Update a Fact using the FactHandle
ksession.update(myFactHandle, new Person("Salaboy!"));
// Retract/Remove from my world the Fact
ksession.retract(myFactHandle);
Full Picture
Hands on Labs

Projects:
 ● 01 :: Drools Expert Introduction
 ● 02 :: Drools Expert Conditional Elements
 ● 03 :: Drools Expert Rule Attributes
Briefing Up

● Covered Topics:
   ○ Rules Execution Lifecycle
   ○ DRL Syntax
      ■ Conditional Elements in the LHS
      ■ Actions in the RHS
 
              
Questions?
Enjoy! 
Questions and Feedback are always
appreciated!
Stay Tuned!
 
                     
    Contact us at
www.plugtree.com
1 of 39

Recommended

Drools5 Community Training HandsOn 1 Drools DRL Syntax by
Drools5 Community Training HandsOn 1 Drools DRL SyntaxDrools5 Community Training HandsOn 1 Drools DRL Syntax
Drools5 Community Training HandsOn 1 Drools DRL SyntaxMauricio (Salaboy) Salatino
3.5K views17 slides
Invertible-syntax 入門 by
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
2.3K views101 slides
Template Haskell とか by
Template Haskell とかTemplate Haskell とか
Template Haskell とかHiromi Ishii
2.1K views35 slides
Solr @ Etsy - Apache Lucene Eurocon by
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconGiovanni Fernandez-Kincade
1.6K views56 slides
Xlab #1: Advantages of functional programming in Java 8 by
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8XSolve
708 views64 slides
Scala by
ScalaScala
Scalasuraj_atreya
778 views21 slides

More Related Content

What's hot

Meetup slides by
Meetup slidesMeetup slides
Meetup slidessuraj_atreya
561 views27 slides
[131]해커의 관점에서 바라보기 by
[131]해커의 관점에서 바라보기[131]해커의 관점에서 바라보기
[131]해커의 관점에서 바라보기NAVER D2
12.2K views101 slides
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e... by
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
409 views410 slides
Future of HTTP in CakePHP by
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
4.3K views55 slides
はじめてのGroovy by
はじめてのGroovyはじめてのGroovy
はじめてのGroovyTsuyoshi Yamamoto
690 views31 slides
JS OO and Closures by
JS OO and ClosuresJS OO and Closures
JS OO and ClosuresJussi Pohjolainen
692 views19 slides

What's hot(20)

[131]해커의 관점에서 바라보기 by NAVER D2
[131]해커의 관점에서 바라보기[131]해커의 관점에서 바라보기
[131]해커의 관점에서 바라보기
NAVER D212.2K views
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e... by PROIDEA
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
PROIDEA409 views
Future of HTTP in CakePHP by markstory
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
markstory4.3K views
New in cakephp3 by markstory
New in cakephp3New in cakephp3
New in cakephp3
markstory2.1K views
Php 102: Out with the Bad, In with the Good by Jeremy Kendall
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
Jeremy Kendall3.4K views
Lambda Expressions in Java 8 by bryanbibat
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
bryanbibat2.4K views
Leveraging the Power of Graph Databases in PHP by Jeremy Kendall
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHP
Jeremy Kendall890 views
Leveraging the Power of Graph Databases in PHP by Jeremy Kendall
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHP
Jeremy Kendall1.1K views
JavaScript Classes and Inheritance by marcheiligers
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
marcheiligers1.6K views
Algorithm, Review, Sorting by Rowan Merewood
Algorithm, Review, SortingAlgorithm, Review, Sorting
Algorithm, Review, Sorting
Rowan Merewood4.8K views
Intro to Advanced JavaScript by ryanstout
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout599 views
Clojure: Practical functional approach on JVM by sunng87
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
sunng871.7K views
Groovy ネタ NGK 忘年会2009 ライトニングトーク by Tsuyoshi Yamamoto
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Tsuyoshi Yamamoto799 views

Similar to Drools5 Community Training Module 3 Drools Expert DRL Syntax

Clojure入門 by
Clojure入門Clojure入門
Clojure入門Naoyuki Kakuda
5K views52 slides
Spl Not A Bridge Too Far phpNW09 by
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Michelangelo van Dam
2K views57 slides
Metaprogramming in Haskell by
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
4.2K views156 slides
An Elephant of a Different Colour: Hack by
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
2.1K views30 slides
Refactoring to Macros with Clojure by
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
3.5K views51 slides
Python Ireland Nov 2010 Talk: Unit Testing by
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland
603 views28 slides

Similar to Drools5 Community Training Module 3 Drools Expert DRL Syntax(20)

Metaprogramming in Haskell by Hiromi Ishii
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
Hiromi Ishii4.2K views
An Elephant of a Different Colour: Hack by Vic Metcalfe
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
Vic Metcalfe2.1K views
Refactoring to Macros with Clojure by Dmitry Buzdin
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin3.5K views
Python Ireland Nov 2010 Talk: Unit Testing by Python Ireland
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland603 views
JQuery do dia-a-dia Gustavo Dutra by Tchelinux
JQuery do dia-a-dia Gustavo DutraJQuery do dia-a-dia Gustavo Dutra
JQuery do dia-a-dia Gustavo Dutra
Tchelinux616 views
Can't Miss Features of PHP 5.3 and 5.4 by Jeff Carouth
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth3.1K views
The Ring programming language version 1.10 book - Part 94 of 212 by Mahmoud Samir Fayed
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
WordCamp Portland 2018: PHP for WordPress by Alena Holligan
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
Alena Holligan278 views
The Ring programming language version 1.10 book - Part 92 of 212 by Mahmoud Samir Fayed
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212
The History of PHPersistence by Hugo Hamon
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon2.3K views
Groovy puzzlers по русски с Joker 2014 by Baruch Sadogursky
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
Feel of Kotlin (Berlin JUG 16 Apr 2015) by intelliyole
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole1.4K views

More from Mauricio (Salaboy) Salatino

Devoxx UK - Platforms on top of K8s by
Devoxx UK - Platforms on top of K8sDevoxx UK - Platforms on top of K8s
Devoxx UK - Platforms on top of K8sMauricio (Salaboy) Salatino
222 views39 slides
WTF_is_SRE_DeveloperEnabledPlatforms.pdf by
WTF_is_SRE_DeveloperEnabledPlatforms.pdfWTF_is_SRE_DeveloperEnabledPlatforms.pdf
WTF_is_SRE_DeveloperEnabledPlatforms.pdfMauricio (Salaboy) Salatino
124 views29 slides
Lessons Learnt from creating platforms on Kubernetes @ Rejekts by
Lessons Learnt from creating platforms on Kubernetes @ RejektsLessons Learnt from creating platforms on Kubernetes @ Rejekts
Lessons Learnt from creating platforms on Kubernetes @ RejektsMauricio (Salaboy) Salatino
31 views53 slides
Building Developer Experiences for the Cloud .pdf by
Building Developer Experiences for the Cloud .pdfBuilding Developer Experiences for the Cloud .pdf
Building Developer Experiences for the Cloud .pdfMauricio (Salaboy) Salatino
37 views28 slides
The Challenges of building Cloud Native Platforms by
The Challenges of building Cloud Native PlatformsThe Challenges of building Cloud Native Platforms
The Challenges of building Cloud Native PlatformsMauricio (Salaboy) Salatino
698 views31 slides
Functions Working Group Update - August 2022.pdf by
Functions Working Group Update - August 2022.pdfFunctions Working Group Update - August 2022.pdf
Functions Working Group Update - August 2022.pdfMauricio (Salaboy) Salatino
70 views8 slides

More from Mauricio (Salaboy) Salatino(20)

KubeCon NA - 2021 Tools That I Wish Existed 3 Years Ago To Build a SaaS Offering by Mauricio (Salaboy) Salatino
KubeCon NA - 2021 Tools That I Wish Existed 3 Years Ago To Build a SaaS OfferingKubeCon NA - 2021 Tools That I Wish Existed 3 Years Ago To Build a SaaS Offering
KubeCon NA - 2021 Tools That I Wish Existed 3 Years Ago To Build a SaaS Offering

Recently uploaded

PRODUCT PRESENTATION.pptx by
PRODUCT PRESENTATION.pptxPRODUCT PRESENTATION.pptx
PRODUCT PRESENTATION.pptxangelicacueva6
14 views1 slide
Business Analyst Series 2023 - Week 3 Session 5 by
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5DianaGray10
248 views20 slides
Kyo - Functional Scala 2023.pdf by
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfFlavio W. Brasil
368 views92 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
Mini-Track: Challenges to Network Automation Adoption by
Mini-Track: Challenges to Network Automation AdoptionMini-Track: Challenges to Network Automation Adoption
Mini-Track: Challenges to Network Automation AdoptionNetwork Automation Forum
12 views27 slides
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...Jasper Oosterveld
18 views49 slides

Recently uploaded(20)

Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10248 views
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada127 views
Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst478 views
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
SAP Automation Using Bar Code and FIORI.pdf by Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada136 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker37 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive

Drools5 Community Training Module 3 Drools Expert DRL Syntax

  • 1.     Drools5 Community Training Sponsored by Plugtree
  • 2. Module 3: Drools Expert  DRL Syntax Drools5 Community Training version: 1.0-SNAPSHOT Release Date: 03/16/2011 Under The Creative Common License
  • 3. Module 3: Drools Expert  DRL Syntax Drools5 Community Training Course by Mauricio "Salaboy" Salatino and Esteban Aliverti is licensed under a Creative Commons Attribution 3.0 Unported License. Based on a work at salaboy.wordpress. com. Permissions beyond the scope of this license may be available at http: //salaboy.wordpress.com/.
  • 4. Agenda ● Introduction to Drools Expert ● Drools DRL syntax introduction ○ LHS Conditional Elements ○ RHS ○ Rules attributes ○ Queries ● Drools 5.x APIs introduction
  • 5. Drools Expert Introduction ● Drools Expert is the rule engine core ● Lets us express Business Rules ● It will be in charge of making inferences to get new conclusions
  • 8. Business Rule Structure package ... import ... global ... rule "My Rule" <Attributes> when <LHS> Song(genre == "Jazz") <CEs> then <RHS> System.out.println("Hi John!"); end
  • 9. LHS - Conditional Elements ● Pattern ● e.g. Song(genre == "Jazz") $song: Song(genre == "Jazz" || == "Avantgarde") $song: Song(duration > 360, $genre: genre == "Jazz")
  • 10. LHS - Conditional Elements ● Field Operators ● e.g. Song( lyrics matches "AZ-az[drink]" ) Song( authors contains "John Zorn" ) Song( author memberof $greatMusicians )
  • 11. LHS - Conditional Elements ● AND e.g. Person( name == "John" ) AND Pet(type == "cat") ● OR e.g. Policewoman (age > 30) OR Fireman(age > 31)
  • 12. LHS - Conditional Elements ● eval e.g. eval( song.isJazz() ) ● not e.g. not( Song( genre == "Pop") )
  • 13. LHS - Conditional Elements ● exists e.g. exists ( Song(genre == "Jazz")) ● forall e.g. forall ( Song() Song(genre == "Jazz") )
  • 14. LHS - Conditional Elements from CE ● e.g. $playlist: Playlist() Song() from $playlist.songs $playlist: Playlist() Song(genre == "Jazz") from $playlist.songs
  • 15. LHS - Conditional Elements ● from ● e.g. global HibernateSession hbn; $playlist: Playlist() Song() from hbn.namedQuery("SongByArtist") .setParameter("artist","John Zorn") .getResultList();
  • 16. LHS - Conditional Elements ● Collect ● e.g. $songs: ArrayList() from collect (Song(genre == "Jazz", year > 2000))
  • 17. LHS - Conditional Elements ● Accumulate
  • 18. LHS - Conditional Elements ● Accumulate CE: <result pattern> from accumulate( <source pattern>, init( <init code> ), action( <action code> ), reverse( <reverse code> ), result( <result expression>)) ● e.g. $playlist: Playlist() $jazzSongs: Number( doubleValue > 100 ) from accumulate( Song(playlist == $playlist, genre == "Jazz"), init( double total = 0; ), action( total += 1; ), reverse( total -= 1; ), result( total ))
  • 19. LHS - Conditional Elements ● Accumulate Function Examples $playlist: Playlist() $total: Number( doubleValue > 100 ) from accumulate( $song: Song( playlist == $playlist, genre == "Jazz"), count($song))
  • 20. LHS - Conditional Elements ● Accumulate out-of-the-box Functions ○ average ○ min ○ max ○ count ○ sum
  • 21. LHS - Conditional Elements ● Accumulate custom function $playlist: Playlist() $total: Number( doubleValue > 100 ) from accumulate( $song: Song( playlist == $playlist), myCustomFc($song.duration)) ● We can plug our custom function here. We just need to implement the AccumulateFunction interface.
  • 22. Nesting CEs ● Drools support nested CEs $petshop: PetShop() $total: Number( doubleValue > 10 ) from accumulate( $pet: Pet(petshop == $petshop, type == PetType.Cat) from $hbm.getNamedQuery("getPetsFromPetshopId") .setParamenter("petshopid",$petshop.getId()) .list(), count ($pet) )
  • 23. Right Hand Side ● Set of actions ● MVEL or Java (http://mvel.codehaus.org/) ● We will have a set of methods to modify the working memory status ○ insert() ○ modify() / update () ○ retract() rule "Fire ! ! !" when Fire() then insert(new Alarm()); end
  • 25. Rule Attributes - no loop ● no-loop i.e. rule "infinite activation loop" no-loop true when $person: Person(age > 21) then update($person){ setName("John"); } end
  • 26. Rule Attributes - salience ● salience (higher priority first) rule "rule with priority" salience 10 when $song: Song() then System.out.println("Rule with higher priority Fired!"); end rule "rule with less priority" salience 5 when $song: Song() then System.out.println("Rule with lower priority Fired!"); end
  • 27. Rule Attributes - agenda-group  rule "Playlist ready" agenda-group "Create Playlist" when Playlist(size == 3) then //Set the focus to "Play playlist" agenda-group kcontext.getKnowledgeRuntime().getAgenda() .getAgendaGroup("Play playlist").setFocus(); end rule "Play playlist" agenda-group "Play playlist" when $pl : Playlist() then $pl.play(); end
  • 28. Rule Attributes - lock-on-active rule "Fill playlist" rule "Number Songs" salience 1 salience 2 lock-on-active lock-on-active agenda-group "Create Playlist" agenda-group "Create Playlist" when when $pl : Playlist() $song : Song() $song : Song() then then modify($song){ modify($pl){ setName( addSong($song); index.getAndIncrement()+ } "_"+ $song.getName()); end } end
  • 29. Queries Example query "Get Persons by Name" (String name) Person(name = :name) end
  • 31. KnowledgeBuilder KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // Add our rules kbuilder.add(new ClassPathResource("rules.drl"), ResourceType.DRL); //Check for errors during the compilation of the rules KnowledgeBuilderErrors errors = kbuilder.getErrors(); if (errors.size() > 0) { for (KnowledgeBuilderError error : errors) { System.err.println(error); } throw new IllegalArgumentException("Could not parse knowledge."); }
  • 32. KnowledgeBase // Create the Knowledge Base KnowledgeBase kbase = KnowledgeBaseFactory. newKnowledgeBase(); // Add the binary packages (compiled rules) to the Knowledge Base kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  • 33. KnowledgeSession // Create a StatefulSession using the KnowledgeBase that // contains the compiled knowledge StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); // We can add a runtime logger to understand what is going on // inside the Engine KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession); // Insert a new Fact inside my world FactHandle myFactHandle = ksession.insert(new Person("Myself")); // Update a Fact using the FactHandle ksession.update(myFactHandle, new Person("Salaboy!")); // Retract/Remove from my world the Fact ksession.retract(myFactHandle);
  • 35. Hands on Labs Projects: ● 01 :: Drools Expert Introduction ● 02 :: Drools Expert Conditional Elements ● 03 :: Drools Expert Rule Attributes
  • 36. Briefing Up ● Covered Topics: ○ Rules Execution Lifecycle ○ DRL Syntax ■ Conditional Elements in the LHS ■ Actions in the RHS
  • 37.     Questions?
  • 38. Enjoy!  Questions and Feedback are always appreciated! Stay Tuned!
  • 39.     Contact us at www.plugtree.com