SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Introducing




by Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Drools Vision
Drools was born as a rule engine, but following the vision of
becoming a single platform for business modelling, it realized
it could achieve this goal only by leveraging 3 complementary
business modelling techniques:

• Business Rule Management (Drools Expert)

• Business Process Management (Drools Flow)

• Complex Event Processing (Drools Fusion)
Drools 5 – Business Logic Integration Platform




 Drools   Drools    Drools    Drools Drools
 Expert    Flow     Fusion    Guvnor Planner


          Business Logic integration System
What a rule-based program is
• A rule-based program is made up of discrete rules, each of
  which applies to some subset of the problem
• It is simpler, because you can concentrate on the rules for one
  situation at a time
• It can be more flexible in the face of fragmentary or poorly
  conditioned inputs
• Used for problems involving control, diagnosis, prediction,
  classification, pattern recognition … in short, all problems
  without clear algorithmic solutions

        Declarative                Imperative
         (What to do)
                      Vs. (How to do it)
When should you use a Rule Engine?
• The problem is beyond any obvious algorithmic solution or
  it isn't fully understood
• The logic changes often
• Domain experts (or business analysts) are readily available,
  but are nontechnical
• You want to isolate the key parts of your business logic,
  especially the really messy parts
How a rule-based system works
Rule's anatomy
                                    Quotes on Rule names are optional
                                    if the rule name has no spaces.
                  rule “<name>”
                       <attribute> <value>
Pattern-matching       when            salience     <int>
against objects in the                 agenda-group <string>
Working Memory              <LHS>      no-loop      <boolean>
                       then            auto-focus   <boolean>
                                       duration     <long>
                            <RHS>      ....

                  end
                                 Code executed when
                                 a match is found
Imperative vs Declarative
 A method must be called directly                         Specific passing
                                                          of arguments
public void helloMark(Person person) {
       if ( person.getName().equals( “mark” ) {
              System.out.println( “Hello Mark” );
       }
}
             Rules can never be called directly
                                                  Specific instances cannot be
                                                  passed but are automatically
rule “Hello Mark”                                 selected with pattern-matching
       when
             Person( name == “mark” )
       then
             System.out.println( “Hello Mark” );
end
What is a pattern

Person( name == “mark” )
              Field Name         Restriction

Object Type            Field Constraint

                    Pattern
Rule's definition
// Java
public class Applicant {          // DRL
    private String name;          declare Applicant
    private int age;
                                      name : String
    private boolean valid;
                                      age : int
    // getter and setter here         valid : boolean
}                                 end


          rule "Is of valid age" when
              $a : Applicant( age >= 18 )
          then
              modify( $a ) { valid = true };
          end
Building
KnowledgeBuilder kbuilder =
        KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(
        ResourceFactory.newClassPathResource("Rules.drl"),
        ResourceType.DRL);
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (kbuilder.hasErrors()) {
    System.err.println(kbuilder.getErrors().toString());
}
KnowledgeBase kbase =
        KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
Executing
StatelessKnowledgeSession ksession =
       kbase.newStatelessKnowledgeSession();
Applicant applicant = new Applicant( "Mr John Smith", 21 );
assertFalse( applicant.isValid() );
ksession.execute( applicant );
assertTrue( applicant.isValid() );
More Pattern Examples
Person( $age : age )
Person( age == ( $age + 1 ) )


Person(age > 30 && < 40 || hair in (“black”, “brown”) )


Person(pets contain $rover )


Person(pets[’rover’].type == “dog”)
Conditional Elements
not Bus( color = “red” )
exists Bus( color = “red” )
forall ( $bus : Bus( color == “red” ) )


$owner : Person( name == “mark” )
           Pet( name == “rover” ) from $owner.pets

                                    Hibernate session
$zipCode : ZipCode()
Person( ) from $hbn.getNamedQuery(“Find People”)
                     .setParameters( [ “zipCode” : $zipCode ] )
                     .list()
 'from' can work
 on any expression
Timers & Calendars
      rule R1                     When the light is on, and has been
          timer 1m30s                on for 1m30s then turn it off
      when
          $l : Light( status == “on” )
      then
         modify( $l ) { status = “off” };

                                             rule R3
        Execute now and after                     calendars "weekday"
 1 hour duration only during weekday
                                                  timer (int:0 1h)
                                             when
rule R2                                            Alarm()
    timer ( cron: 0 0/15 * * * * ) then
when                                               sendEmail( ”Alert!” )
     Alarm()
then                                  Send alert every
    sendEmail( ”Alert!” )            quarter of an hour
Truth Maintenance System (1)
rule "Issue Adult Bus Pass" when
      $p : Person( age >= 18 )
then
                                         Coupled logic
      insert(new AdultBusPass( $p ) );
end


rule "Issue Child Bus Pass" when
                                          What happens
      $p : Person( age < 18 )             when the child
                                          becomes adult?
then
      insert(new ChildBusPass( $p ) );
end
Truth Maintenance System (2)
rule "Who Is Child" when          De-couples the logic
    $p : Person( age < 18 )
then
    logicalInsert( new IsChild( $p ) )
end
                                                 Encapsulate
                                             knowledge providing
rule "Issue Child Bus Pass" when
                                            semantic abstractions
    $p : Person( )                          for this encapsulation
    IsChild( person =$p )
then
    logicalInsert(new ChildBusPass( $p ) );
end
                                         Maintains the truth by
                                         automatically retracting
Drools Eclipse
   DEMO
Complex Event Processing
Event
  A record of state change in the application domain at a
    particular point in time

Complex Event
  An abstraction of other events called its members

Complex Event Processing
  Processing multiple events with the goal of identifying
    the meaningful events within the event cloud
Drools Fusion
• Drools modules for Complex Event Processing
• Understand and handle events as a first class
  platform citizen (actually special type of Fact)
• Select a set of interesting events in a cloud or
  stream of events
• Detect the relevant relationship (patterns)
  among these events
• Take appropriate actions based on the
  patterns detected
Events as Facts in Time
   Temporal
 relationships
between events

rule
    "Sound the alarm"
when
    $f : FireDetected( )
    not( SprinklerActivated( this after[0s,10s] $f ) )
then
    // sound the alarm
end
Workflows as Business Processes
 A workflow is a process that describes the
 order in which a series of steps need to be
        executed, using a flow chart.
Drools Flow (aka jBPM5)
• Allows to model business processes
• Eclipse-based editor to support workflows
  graphical creation
• Pluggable persistence and transaction based
  on JPA / JTA
• Based on BPMN 2.0 specification
• Can be used with Drools to model your
  business logic as combination of processes,
  events and rules
Drools Guvnor
• Centralised repository for Drools Knowledge
  Bases
• Web based GUIs
• ACL for rules and other artifacts
• Version management
• Integrated testing
Drools Planner
• Works on all kinds of planning problems
  – NP-complete
  – Hard & soft constraints
  – Huge search space
• Planning constraints can be weighted and are
  written as declarative score rules
• The planner algorithm is configurable. It searches
  through the solutions within a given amount of
  time and returns the best solution found
Q                                                 A
Mario Fusco                          mario.fusco@gmail.com
Red Hat – Senior Software Engineer     twitter: @mariofusco

Mais conteúdo relacionado

Mais procurados

Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
Srinath Perera
 
2011-03-29 London - drools
2011-03-29 London - drools2011-03-29 London - drools
2011-03-29 London - drools
Geoffrey De Smet
 
JBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic PlatformJBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic Platform
elliando dias
 

Mais procurados (20)

Drools
DroolsDrools
Drools
 
Rule Engine & Drools
Rule Engine & DroolsRule Engine & Drools
Rule Engine & Drools
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
JBoss World 2011 - Drools
JBoss World 2011 - DroolsJBoss World 2011 - Drools
JBoss World 2011 - Drools
 
Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
 
Drools & jBPM Info Sheet
Drools & jBPM Info SheetDrools & jBPM Info Sheet
Drools & jBPM Info Sheet
 
Drools BeJUG 2010
Drools BeJUG 2010Drools BeJUG 2010
Drools BeJUG 2010
 
2011-03-29 London - drools
2011-03-29 London - drools2011-03-29 London - drools
2011-03-29 London - drools
 
Rules Engine - java(Drools) & ruby(ruleby)
Rules Engine - java(Drools) & ruby(ruleby)Rules Engine - java(Drools) & ruby(ruleby)
Rules Engine - java(Drools) & ruby(ruleby)
 
Rules With Drools
Rules With DroolsRules With Drools
Rules With Drools
 
JBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic PlatformJBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic Platform
 
Drools
DroolsDrools
Drools
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
 
Cassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsCassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra Applications
 
LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java Developers
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine
 
Zen of Akka
Zen of AkkaZen of Akka
Zen of Akka
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Fault tolerant microservices - LJC Skills Matter 4thNov2014
Fault tolerant microservices - LJC Skills Matter 4thNov2014Fault tolerant microservices - LJC Skills Matter 4thNov2014
Fault tolerant microservices - LJC Skills Matter 4thNov2014
 

Semelhante a Drools Introduction

10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
martincronje
 
Developing applications with rules, workflow and event processing (it@cork 2010)
Developing applications with rules, workflow and event processing (it@cork 2010)Developing applications with rules, workflow and event processing (it@cork 2010)
Developing applications with rules, workflow and event processing (it@cork 2010)
Geoffrey De Smet
 

Semelhante a Drools Introduction (20)

Stop that!
Stop that!Stop that!
Stop that!
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
Developing applications with rules, workflow and event processing (it@cork 2010)
Developing applications with rules, workflow and event processing (it@cork 2010)Developing applications with rules, workflow and event processing (it@cork 2010)
Developing applications with rules, workflow and event processing (it@cork 2010)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and Techniques
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Hibernate
Hibernate Hibernate
Hibernate
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Beyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel ProcessingBeyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel Processing
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit east
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 

Mais de JBug Italy

JBoss AS7 Overview
JBoss AS7 OverviewJBoss AS7 Overview
JBoss AS7 Overview
JBug Italy
 

Mais de JBug Italy (20)

JBoss Wise: breaking barriers to WS testing
JBoss Wise: breaking barriers to WS testingJBoss Wise: breaking barriers to WS testing
JBoss Wise: breaking barriers to WS testing
 
Camel and JBoss
Camel and JBossCamel and JBoss
Camel and JBoss
 
AS7 and CLI
AS7 and CLIAS7 and CLI
AS7 and CLI
 
Intro jbug milano_26_set2012
Intro jbug milano_26_set2012Intro jbug milano_26_set2012
Intro jbug milano_26_set2012
 
Faster & Greater Messaging System HornetQ zzz
Faster & Greater Messaging System HornetQ zzzFaster & Greater Messaging System HornetQ zzz
Faster & Greater Messaging System HornetQ zzz
 
Infinispan,Lucene,Hibername OGM
Infinispan,Lucene,Hibername OGMInfinispan,Lucene,Hibername OGM
Infinispan,Lucene,Hibername OGM
 
AS7
AS7AS7
AS7
 
JBoss BRMS - The enterprise platform for business logic
JBoss BRMS - The enterprise platform for business logicJBoss BRMS - The enterprise platform for business logic
JBoss BRMS - The enterprise platform for business logic
 
JBoss AS7 Overview
JBoss AS7 OverviewJBoss AS7 Overview
JBoss AS7 Overview
 
Intro JBug Milano - January 2012
Intro JBug Milano - January 2012Intro JBug Milano - January 2012
Intro JBug Milano - January 2012
 
JBoss AS7 Webservices
JBoss AS7 WebservicesJBoss AS7 Webservices
JBoss AS7 Webservices
 
JBoss AS7
JBoss AS7JBoss AS7
JBoss AS7
 
Intro JBug Milano - September 2011
Intro JBug Milano - September 2011Intro JBug Milano - September 2011
Intro JBug Milano - September 2011
 
All the cool stuff of JBoss BRMS
All the cool stuff of JBoss BRMSAll the cool stuff of JBoss BRMS
All the cool stuff of JBoss BRMS
 
Infinispan and Enterprise Data Grid
Infinispan and Enterprise Data GridInfinispan and Enterprise Data Grid
Infinispan and Enterprise Data Grid
 
September 2010 - Arquillian
September 2010 - ArquillianSeptember 2010 - Arquillian
September 2010 - Arquillian
 
September 2010 - Gatein
September 2010 - GateinSeptember 2010 - Gatein
September 2010 - Gatein
 
May 2010 - Infinispan
May 2010 - InfinispanMay 2010 - Infinispan
May 2010 - Infinispan
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
May 2010 - Drools flow
May 2010 - Drools flowMay 2010 - Drools flow
May 2010 - Drools flow
 

Último

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 

Último (20)

2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 

Drools Introduction

  • 1. Introducing by Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco
  • 2. Drools Vision Drools was born as a rule engine, but following the vision of becoming a single platform for business modelling, it realized it could achieve this goal only by leveraging 3 complementary business modelling techniques: • Business Rule Management (Drools Expert) • Business Process Management (Drools Flow) • Complex Event Processing (Drools Fusion)
  • 3. Drools 5 – Business Logic Integration Platform Drools Drools Drools Drools Drools Expert Flow Fusion Guvnor Planner Business Logic integration System
  • 4. What a rule-based program is • A rule-based program is made up of discrete rules, each of which applies to some subset of the problem • It is simpler, because you can concentrate on the rules for one situation at a time • It can be more flexible in the face of fragmentary or poorly conditioned inputs • Used for problems involving control, diagnosis, prediction, classification, pattern recognition … in short, all problems without clear algorithmic solutions Declarative Imperative (What to do) Vs. (How to do it)
  • 5. When should you use a Rule Engine? • The problem is beyond any obvious algorithmic solution or it isn't fully understood • The logic changes often • Domain experts (or business analysts) are readily available, but are nontechnical • You want to isolate the key parts of your business logic, especially the really messy parts
  • 6. How a rule-based system works
  • 7. Rule's anatomy Quotes on Rule names are optional if the rule name has no spaces. rule “<name>” <attribute> <value> Pattern-matching when salience <int> against objects in the agenda-group <string> Working Memory <LHS> no-loop <boolean> then auto-focus <boolean> duration <long> <RHS> .... end Code executed when a match is found
  • 8. Imperative vs Declarative A method must be called directly Specific passing of arguments public void helloMark(Person person) { if ( person.getName().equals( “mark” ) { System.out.println( “Hello Mark” ); } } Rules can never be called directly Specific instances cannot be passed but are automatically rule “Hello Mark” selected with pattern-matching when Person( name == “mark” ) then System.out.println( “Hello Mark” ); end
  • 9. What is a pattern Person( name == “mark” ) Field Name Restriction Object Type Field Constraint Pattern
  • 10. Rule's definition // Java public class Applicant { // DRL private String name; declare Applicant private int age; name : String private boolean valid; age : int // getter and setter here valid : boolean } end rule "Is of valid age" when $a : Applicant( age >= 18 ) then modify( $a ) { valid = true }; end
  • 11. Building KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource("Rules.drl"), ResourceType.DRL); KnowledgeBuilderErrors errors = kbuilder.getErrors(); if (kbuilder.hasErrors()) { System.err.println(kbuilder.getErrors().toString()); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  • 12. Executing StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession(); Applicant applicant = new Applicant( "Mr John Smith", 21 ); assertFalse( applicant.isValid() ); ksession.execute( applicant ); assertTrue( applicant.isValid() );
  • 13. More Pattern Examples Person( $age : age ) Person( age == ( $age + 1 ) ) Person(age > 30 && < 40 || hair in (“black”, “brown”) ) Person(pets contain $rover ) Person(pets[’rover’].type == “dog”)
  • 14. Conditional Elements not Bus( color = “red” ) exists Bus( color = “red” ) forall ( $bus : Bus( color == “red” ) ) $owner : Person( name == “mark” ) Pet( name == “rover” ) from $owner.pets Hibernate session $zipCode : ZipCode() Person( ) from $hbn.getNamedQuery(“Find People”) .setParameters( [ “zipCode” : $zipCode ] ) .list() 'from' can work on any expression
  • 15. Timers & Calendars rule R1 When the light is on, and has been timer 1m30s on for 1m30s then turn it off when $l : Light( status == “on” ) then modify( $l ) { status = “off” }; rule R3 Execute now and after calendars "weekday" 1 hour duration only during weekday timer (int:0 1h) when rule R2 Alarm() timer ( cron: 0 0/15 * * * * ) then when sendEmail( ”Alert!” ) Alarm() then Send alert every sendEmail( ”Alert!” ) quarter of an hour
  • 16. Truth Maintenance System (1) rule "Issue Adult Bus Pass" when $p : Person( age >= 18 ) then Coupled logic insert(new AdultBusPass( $p ) ); end rule "Issue Child Bus Pass" when What happens $p : Person( age < 18 ) when the child becomes adult? then insert(new ChildBusPass( $p ) ); end
  • 17. Truth Maintenance System (2) rule "Who Is Child" when De-couples the logic $p : Person( age < 18 ) then logicalInsert( new IsChild( $p ) ) end Encapsulate knowledge providing rule "Issue Child Bus Pass" when semantic abstractions $p : Person( ) for this encapsulation IsChild( person =$p ) then logicalInsert(new ChildBusPass( $p ) ); end Maintains the truth by automatically retracting
  • 19. Complex Event Processing Event A record of state change in the application domain at a particular point in time Complex Event An abstraction of other events called its members Complex Event Processing Processing multiple events with the goal of identifying the meaningful events within the event cloud
  • 20. Drools Fusion • Drools modules for Complex Event Processing • Understand and handle events as a first class platform citizen (actually special type of Fact) • Select a set of interesting events in a cloud or stream of events • Detect the relevant relationship (patterns) among these events • Take appropriate actions based on the patterns detected
  • 21. Events as Facts in Time Temporal relationships between events rule "Sound the alarm" when $f : FireDetected( ) not( SprinklerActivated( this after[0s,10s] $f ) ) then // sound the alarm end
  • 22. Workflows as Business Processes A workflow is a process that describes the order in which a series of steps need to be executed, using a flow chart.
  • 23. Drools Flow (aka jBPM5) • Allows to model business processes • Eclipse-based editor to support workflows graphical creation • Pluggable persistence and transaction based on JPA / JTA • Based on BPMN 2.0 specification • Can be used with Drools to model your business logic as combination of processes, events and rules
  • 24. Drools Guvnor • Centralised repository for Drools Knowledge Bases • Web based GUIs • ACL for rules and other artifacts • Version management • Integrated testing
  • 25.
  • 26. Drools Planner • Works on all kinds of planning problems – NP-complete – Hard & soft constraints – Huge search space • Planning constraints can be weighted and are written as declarative score rules • The planner algorithm is configurable. It searches through the solutions within a given amount of time and returns the best solution found
  • 27.
  • 28. Q A Mario Fusco mario.fusco@gmail.com Red Hat – Senior Software Engineer twitter: @mariofusco