SlideShare a Scribd company logo
eBusiness Technologies (ebTech) Introduction to Drools Adrian Giurca, eBusiness Technologies, Craiova, March 2009 Dr. Adrian Giurca Brandenburg University of Technology Cottbus, Germany
Repetition Embedding rules in large applications is a difficult task Many controversies and open questions when we want to use libraries to connect AI Languages to Java Applications Hard difficulties to share data between libraries and the main application ( Prolog facts versus Java classes ) Logic can be difficult to be employed in rule modeling Fortunately we have Drools an open source Java-based rule engine In addition, Drools employs a Java-based syntax for rules Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Developing Rule-based applications Vocabulary constraints: The rule-based part of the application is based on the existent domain vocabulary of your application Therefore you have to  design rules considering this vocabulary Is a standalone rule-based application? Then is just a server-side component You can add a basic JSP layer or a Java client Is an Enterprise application (JEE5)? Then the rule engine should be integrated at the business layer Is a Web Service application? Then the rule engine should be controlled by the WS EJB Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Drools Vocabulary is basically POJO package org.btu.it.userv.vocabulary; class YoungDriver extends Driver { // properties  //default constructor public YoungDriver(){ } //setters and getters for the properties }  Adrian Giurca, eBusiness Technologies, Craiova, March 2009 POJO – Plain Old Java Object (search on Google)
Rules are grouped in rulesets Rulesets in Drools are captured by means of  packages. A  package  is a placeholder for  rules ,  imports ,  globals ,  functions : Imports  make vocabulary classes accessible to rules Globals  are global variables. They are used to make application objects available to the rules. They must be understand as constants in the reasoning process.  Functions  are static Java functions usually designed to be available in rules action part. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Sample ruleset (package) package org.btu.it.userv.driverPremium #list any import classes here. import org.btu.it.userv.vocabulary.YoungDriver; import java.io.IOException; // ... #declare any global variables here global java.io.BufferedWriter out; global org.btu.it.userv.utils.Output writer; // Rules #write any global function here function void writeLog(String text,  BufferedWriter out)throws IOException{ // function code comes here } # or imports such as import function org.btu.it.userv.utils.Logger.writeLog Adrian Giurca, eBusiness Technologies, Craiova, March 2009 Ruleset name Vocabulary Global variables Global functions
Drools Rule structure A rule specifies that  when  a particular set of conditions occur - specified in the Left Hand Side (LHS),  then do this  - specified as a list of actions in the Right Hand Side (RHS). A rule  must have a unique name , in the scope of the rule package.  Attributes are optional. The rule LHS follows the  when  keyword. The RHS follows the  then  keyword (ideally on a newline). The rule is terminated by the  end  keyword.  Rules cannot be nested. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Rules condition part (LHS) Rule conditions part is a  logical formula  built by using  conjunction  ( , ),  disjunction  ( || ), and  negation  ( not ) on conditional elements There are two main conditional elements i.e.  pattern  and  eval The  pattern  condition is the most important one.  Basic  and  advanced  pattern conditions are provided Essentially  eval  is a Boolean expression evaluator. This can refer to variables that were bound in the rule LHS, and functions in the rule package.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Actions (the RHS) The action part part should contain a list of actions to be executed.  Any valid Java code is allowed.  However, is bad practice to use imperative or conditional code in the RHS of a rule; as a rule should be atomic in nature - "when this, then do this", not "when this, maybe do this".  The RHS part of a rule  should also be kept small , thus keeping it  declarative  and  readable .  The main purpose of the RHS is to insert, retract or modify facts from the working memory.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Standard Actions in RHS update(object, handle);  will tell the engine that an object has changed and rules may need to be reconsidered. insert(new Something());  will place a new object of your creation in working memory. insertLogical(new Something());  similar to  insert , but the object will be automatically retracted when there are no more facts to support the truth of the currently firing rule. retract(handle);  removes an object from working memory. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Slide No. 11 This is Slide No. 11 (half time) and we don't know yet how to use rules in a large application?! To do : Download  Drools Use it. Make running an  example from their library Adrian Giurca, eBusiness Technologies, Craiova, March 2009
The basic pattern patternBinding  is a variable bound to a Java object instance of  patternType  bean. patternBinding  is bound sequentially to each instance of the class  patternType  for which the  constraints  holds. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $driver:Driver(age < 25) The  $driver  variable is bound sequentially to all  Driver  objects from the working memory for which the  age  value is less than  25 , something like:   X  driver( X ) && age( X ) < 25
Constraints (1) Are used in a pattern definition Logically they are conditions referring to different properties of the pattern class type Can be combined in complex constraints by using logical connectors Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $driver:Driver(age < 25) age < 25  is a (field) constraint
Constraints (2) Constraints can be more complex: Adrian Giurca, eBusiness Technologies, Craiova, March 2009 constraintGroup  corresponds to a conjunction of constraints fieldConstraint  represents constraints on the class properties. There are three types of restrictions: Single Value Restriction, Compound Value Restriction and Multi Restriction. inlineEvalConstraint  can use any valid dialect expression as long as it is evaluated to a primitive Boolean
Field constraints (1) A field corresponds to a getter for a property on the bean object. If your model objects follow the java bean pattern, then fields are exposed using  getXXX()  or  isXXX() . You can access fields by using the bean-name convention (so  getType()  can be accessed as  type )  For example,  YoungDriver(maritalStatus == MaritalStatus.MARRIED) uses the  getMaritalStatus()  method on the  YoungDriver  instance.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Field constraints (2) You can restrict a field by using a large number of constructs based on various operators. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 fieldBinding is a variable bound to the value of the fieldName property i.e.  YoungDriver($age:age < 25)   where  $age  is the  fieldBinding ,  age  is the  fieldName  and  <25  is the  restriction
The  eval  pattern and  inlineEvalConstraint   eval  and  inlineEvalConstraint  have similar model. Evaluates a specific expression to a Boolean Over use of  eval  reduces the declaratives of your rules and can result in a poor performing engine.  While 'evals' can be used anywhere the best practice is to add it as the last conditional element in the LHS of a rule.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: eval(isApprovedByManager($client, $vip)) supposing isApprovedByManager()  be a Boolean function.
Advanced patterns -  from allows users to specify a source for patterns to reason over.  This allows the engine to reason over data not in the Working Memory.  This allows integration with other application components and frameworks. One common example is the integration with data retrieved on-demand from databases using hibernate named queries.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $item : OrderItem( value > 100 ) from $order.items   $item   is bounded sequentially to all   OrderItem   objects with   value   greater than   100   from the list   $order.items
More complex  from : using  collect allows rules to reason over collection of objects collected from the given source or from the working memory.   Adrian Giurca, eBusiness Technologies, Craiova, March 2009 $drivers : ArrayList()  from  collect(  Driver( gender == 'F', noOfAccidents > 0 )  from $town.getDrivers() )
More complex  from:  using  accumulate Is a form of  collect Allows a rule to iterate over a collection of objects, executing custom actions for each of the elements, and at the end return a result object.  Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Accumulate example $total : Number( doubleValue > 100 )  from  accumulate(  OrderItem( order == $order, $value : value ),  init( double total = 0; ),  action( total += $value; ),  reverse( total -= $value; ),  result( total )  )  Adrian Giurca, eBusiness Technologies, Craiova, March 2009
Do you like rule-based applications? Attend the next lecture  Tomorrow at 4PM in the same room Adrian Giurca, eBusiness Technologies, Craiova, March 2009

More Related Content

Introduction to Drools

  • 1. eBusiness Technologies (ebTech) Introduction to Drools Adrian Giurca, eBusiness Technologies, Craiova, March 2009 Dr. Adrian Giurca Brandenburg University of Technology Cottbus, Germany
  • 2. Repetition Embedding rules in large applications is a difficult task Many controversies and open questions when we want to use libraries to connect AI Languages to Java Applications Hard difficulties to share data between libraries and the main application ( Prolog facts versus Java classes ) Logic can be difficult to be employed in rule modeling Fortunately we have Drools an open source Java-based rule engine In addition, Drools employs a Java-based syntax for rules Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 3. Developing Rule-based applications Vocabulary constraints: The rule-based part of the application is based on the existent domain vocabulary of your application Therefore you have to design rules considering this vocabulary Is a standalone rule-based application? Then is just a server-side component You can add a basic JSP layer or a Java client Is an Enterprise application (JEE5)? Then the rule engine should be integrated at the business layer Is a Web Service application? Then the rule engine should be controlled by the WS EJB Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 4. Drools Vocabulary is basically POJO package org.btu.it.userv.vocabulary; class YoungDriver extends Driver { // properties //default constructor public YoungDriver(){ } //setters and getters for the properties } Adrian Giurca, eBusiness Technologies, Craiova, March 2009 POJO – Plain Old Java Object (search on Google)
  • 5. Rules are grouped in rulesets Rulesets in Drools are captured by means of packages. A package is a placeholder for rules , imports , globals , functions : Imports make vocabulary classes accessible to rules Globals are global variables. They are used to make application objects available to the rules. They must be understand as constants in the reasoning process. Functions are static Java functions usually designed to be available in rules action part. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 6. Sample ruleset (package) package org.btu.it.userv.driverPremium #list any import classes here. import org.btu.it.userv.vocabulary.YoungDriver; import java.io.IOException; // ... #declare any global variables here global java.io.BufferedWriter out; global org.btu.it.userv.utils.Output writer; // Rules #write any global function here function void writeLog(String text, BufferedWriter out)throws IOException{ // function code comes here } # or imports such as import function org.btu.it.userv.utils.Logger.writeLog Adrian Giurca, eBusiness Technologies, Craiova, March 2009 Ruleset name Vocabulary Global variables Global functions
  • 7. Drools Rule structure A rule specifies that when a particular set of conditions occur - specified in the Left Hand Side (LHS), then do this - specified as a list of actions in the Right Hand Side (RHS). A rule must have a unique name , in the scope of the rule package. Attributes are optional. The rule LHS follows the when keyword. The RHS follows the then keyword (ideally on a newline). The rule is terminated by the end keyword. Rules cannot be nested. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 8. Rules condition part (LHS) Rule conditions part is a logical formula built by using conjunction ( , ), disjunction ( || ), and negation ( not ) on conditional elements There are two main conditional elements i.e. pattern and eval The pattern condition is the most important one. Basic and advanced pattern conditions are provided Essentially eval is a Boolean expression evaluator. This can refer to variables that were bound in the rule LHS, and functions in the rule package. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 9. Actions (the RHS) The action part part should contain a list of actions to be executed. Any valid Java code is allowed. However, is bad practice to use imperative or conditional code in the RHS of a rule; as a rule should be atomic in nature - &quot;when this, then do this&quot;, not &quot;when this, maybe do this&quot;. The RHS part of a rule should also be kept small , thus keeping it declarative and readable . The main purpose of the RHS is to insert, retract or modify facts from the working memory. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 10. Standard Actions in RHS update(object, handle); will tell the engine that an object has changed and rules may need to be reconsidered. insert(new Something()); will place a new object of your creation in working memory. insertLogical(new Something()); similar to insert , but the object will be automatically retracted when there are no more facts to support the truth of the currently firing rule. retract(handle); removes an object from working memory. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 11. Slide No. 11 This is Slide No. 11 (half time) and we don't know yet how to use rules in a large application?! To do : Download Drools Use it. Make running an example from their library Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 12. The basic pattern patternBinding is a variable bound to a Java object instance of patternType bean. patternBinding is bound sequentially to each instance of the class patternType for which the constraints holds. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $driver:Driver(age < 25) The $driver variable is bound sequentially to all Driver objects from the working memory for which the age value is less than 25 , something like:  X driver( X ) && age( X ) < 25
  • 13. Constraints (1) Are used in a pattern definition Logically they are conditions referring to different properties of the pattern class type Can be combined in complex constraints by using logical connectors Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $driver:Driver(age < 25) age < 25 is a (field) constraint
  • 14. Constraints (2) Constraints can be more complex: Adrian Giurca, eBusiness Technologies, Craiova, March 2009 constraintGroup corresponds to a conjunction of constraints fieldConstraint represents constraints on the class properties. There are three types of restrictions: Single Value Restriction, Compound Value Restriction and Multi Restriction. inlineEvalConstraint can use any valid dialect expression as long as it is evaluated to a primitive Boolean
  • 15. Field constraints (1) A field corresponds to a getter for a property on the bean object. If your model objects follow the java bean pattern, then fields are exposed using getXXX() or isXXX() . You can access fields by using the bean-name convention (so getType() can be accessed as type ) For example, YoungDriver(maritalStatus == MaritalStatus.MARRIED) uses the getMaritalStatus() method on the YoungDriver instance. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 16. Field constraints (2) You can restrict a field by using a large number of constructs based on various operators. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 fieldBinding is a variable bound to the value of the fieldName property i.e. YoungDriver($age:age < 25) where $age is the fieldBinding , age is the fieldName and <25 is the restriction
  • 17. The eval pattern and inlineEvalConstraint eval and inlineEvalConstraint have similar model. Evaluates a specific expression to a Boolean Over use of eval reduces the declaratives of your rules and can result in a poor performing engine. While 'evals' can be used anywhere the best practice is to add it as the last conditional element in the LHS of a rule. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: eval(isApprovedByManager($client, $vip)) supposing isApprovedByManager() be a Boolean function.
  • 18. Advanced patterns - from allows users to specify a source for patterns to reason over. This allows the engine to reason over data not in the Working Memory. This allows integration with other application components and frameworks. One common example is the integration with data retrieved on-demand from databases using hibernate named queries. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 For example: $item : OrderItem( value > 100 ) from $order.items $item is bounded sequentially to all OrderItem objects with value greater than 100 from the list $order.items
  • 19. More complex from : using collect allows rules to reason over collection of objects collected from the given source or from the working memory. Adrian Giurca, eBusiness Technologies, Craiova, March 2009 $drivers : ArrayList() from collect( Driver( gender == 'F', noOfAccidents > 0 ) from $town.getDrivers() )
  • 20. More complex from: using accumulate Is a form of collect Allows a rule to iterate over a collection of objects, executing custom actions for each of the elements, and at the end return a result object. Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 21. Accumulate example $total : Number( doubleValue > 100 ) from accumulate( OrderItem( order == $order, $value : value ), init( double total = 0; ), action( total += $value; ), reverse( total -= $value; ), result( total ) ) Adrian Giurca, eBusiness Technologies, Craiova, March 2009
  • 22. Do you like rule-based applications? Attend the next lecture Tomorrow at 4PM in the same room Adrian Giurca, eBusiness Technologies, Craiova, March 2009