Friday, April 19, 13
Drools                            in a nutshell                       Everything you always wanted to know                ...
porcelli@redhat.com                  no:sql(br)                                                                         @p...
Drools?                              was born as a rule engine ...                                             evolved as ...
opta                 expert   fusion             guvnor                                   planner                         ...
expert   guvnorFriday, April 19, 13
so...            what?Friday, April 19, 13
Logic and Data Separation                 Speed and Scalability                                 Understandable Rules      ...
rule                       what isFriday, April 19, 13
rule <rule_name>                           <attribute><value>                           when                              ...
rule "Infer Adult"       when           $p : Person( age >= 18 )       then           System.out.println("Adult!");   endF...
patternmatching                       Person( age >= 18 )                                        field name          restri...
rule "Infer Child"            rule "Infer Baby"                   when                          when                      ...
Person(age=10)               rule "Infer Child"            rule "Infer Baby"                   when                       ...
Person(age=22)               rule "Infer Child"            rule "Infer Baby"                   when                       ...
Person(age=61)               rule "Infer Child"            rule "Infer Baby"                   when                       ...
Person(age=1)               rule "Infer Child"            rule "Infer Baby"                   when                        ...
OtherObject()               rule "Infer Child"            rule "Infer Baby"                   when                        ...
decouple logic       rule "Infer Child"                            rule "Infer Adult"           when                      ...
patternmatching                       Person( $age : age )                       Person( age == ( $age + 1 ) )            ...
under the       hoodFriday, April 19, 13
hybrid                       reasoning                       systemFriday, April 19, 13
WTF?Friday, April 19, 13
forward    backward    chainningFriday, April 19, 13
WTF?Friday, April 19, 13
forwardchainning                             data driven/reactionary                 rule "Adults that like cheddar"      ...
backwardchainning                                                                  goal driven                            ...
backwardchainning                       query father( String father, String child )                           ?man( father...
backwardforward                       fewer hypotheses lot’s hypotheses                             query data lot’s data ...
rete        algorithmFriday, April 19, 13
reteoo         rule "Like cheddar"         when             Cheese( $cheddar : name == "cheddar" )              $p : Perso...
reteoo                         rete node                          object type node                         alpha node     ...
reteoo                         rete node                          object type node                         alpha node     ...
reteoo                         rete node                          object type node                         alpha node     ...
reteoo                         rete node                          object type node                         alpha node     ...
so...            how?Friday, April 19, 13
Friday, April 19, 13
codeapi               final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();               // th...
codeapi             final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();             ksession.se...
codeapi              final StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();               ksessi...
please            one sec!Friday, April 19, 13
Friday, April 19, 13
new            paradigm?Friday, April 19, 13
yesnoFriday, April 19, 13
yes   you can construct                             your systems using                             almost only rules!Frida...
pong                         demoFriday, April 19, 13
no  you can adapt your      existing systems    (few lines) to take  advantage of droolsFriday, April 19, 13
public void aprovarPagamento(String apoliceId, String sinistroId,                       "    "    int valor, String cpfApr...
system                             control flow                    control flow                    control flow           ...
public void aprovarPagamento( String apoliceId,                                                     String sinistroId,    ...
rule "Coordenador tentando fraudar"                                                  " when                               ...
system                          control flow            control flow             control flow                             ...
F.A.Q.Friday, April 19, 13
business analyst     write rules?Friday, April 19, 13
yesnoFriday, April 19, 13
no                   they won’t do this:    rule "NOT Like cheddar"    when        Cheese( $cheddar : name == "cheddar" ) ...
yes                             but they can do this:                                         decision tableFriday, April ...
yes                             and this                                        test scenarioFriday, April 19, 13
so...            next?Friday, April 19, 13
droolsv6Friday, April 19, 13
retewilldie                        http://blog.athico.com/2013/01/life-beyond-rete-rip-rete-2013.htmlphreakFriday, April 1...
maven                                           compatible                       project structurekjarFriday, April 19, 13
KieServices ks = KieServices.Factory.get();                       KieContainer kContainer = ks.getKieClasspathContainer();...
public class KProject {                           @Inject @KBase("fol4.test1.KBase1")                           KnowledgeB...
<?xml version="1.0" encoding="UTF-8"?>                                    <kmodule                                        ...
errai gwt                                   cdi best-practices                                   jee java                 ...
database+gitFriday, April 19, 13
shameless self promotion             building world class             web consoles using             uberfire  auditorium ...
that’sall folks!Friday, April 19, 13
questions?Friday, April 19, 13
thanks!                                                     porcelli@redhat.com                                           ...
Upcoming SlideShare
Loading in …5
×

JUDCon São Paulo - Drools in a Nutshell

716 views
601 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
716
On SlideShare
0
From Embeds
0
Number of Embeds
17
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

JUDCon São Paulo - Drools in a Nutshell

  1. 1. Friday, April 19, 13
  2. 2. Drools in a nutshell Everything you always wanted to know but didnt know whom to ask! ;)Friday, April 19, 13
  3. 3. porcelli@redhat.com no:sql(br) @porcellircelli Alexandre Porcelli Program Committee Alexandre Porcelli Program Committee Emerging Languages on the JVM Alexandre Porcelli Core Engineer #guvnordev Alexandre Porcelli #droolsdev Principal Software Engineer #jbpmdev #optaplanner-dev Friday, April 19, 13
  4. 4. Drools? was born as a rule engine ... evolved as business modeling solution ... targets as knowledge representation and reasoning platform!Friday, April 19, 13
  5. 5. opta expert fusion guvnor planner jbpm jbpm jbpm console designerFriday, April 19, 13
  6. 6. expert guvnorFriday, April 19, 13
  7. 7. so... what?Friday, April 19, 13
  8. 8. Logic and Data Separation Speed and Scalability Understandable Rules Centralization of Knowledge Declarative ProgrammingFriday, April 19, 13
  9. 9. rule what isFriday, April 19, 13
  10. 10. rule <rule_name> <attribute><value> when <conditions> then <actions> endFriday, April 19, 13
  11. 11. rule "Infer Adult" when $p : Person( age >= 18 ) then System.out.println("Adult!"); endFriday, April 19, 13
  12. 12. patternmatching Person( age >= 18 ) field name restriction object type constraint patternFriday, April 19, 13
  13. 13. rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  14. 14. Person(age=10) rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  15. 15. Person(age=22) rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  16. 16. Person(age=61) rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  17. 17. Person(age=1) rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  18. 18. OtherObject() rule "Infer Child" rule "Infer Baby" when when Person( age < 18 ) Person( age <= 2 ) then then //code //code end end rule "Infer Adult" rule "Infer Senior" when when Person( age >= 18 ) Person( age >= < 60 ) then then //code //code end endFriday, April 19, 13
  19. 19. decouple logic rule "Infer Child" rule "Infer Adult" when when $p : Person( age < 18 ) $p : Person( age >= 18 ) then then insertLogical( new IsChild( $p ) ) insertLogical( new IsAdult( $p ) ) end end rule "Issue Child Bus Pass" rule "Issue Adult Bus Pass" when when $p : Person( ) $p : Person( ) IsChild( person == $p ) IsAdult( person =$p ) then then insertLogical( new ChildBusPass( $p ) ); insertLogical( new AdultBusPass( $p ) ); end endFriday, April 19, 13
  20. 20. patternmatching Person( $age : age ) Person( age == ( $age + 1 ) ) Person( age > 30 && < 40 || hair in ("black", "brown") ) Person( pets contains $rover ) Person( pets["rover"].type == "dog" ) Person( insurance.valid )Friday, April 19, 13
  21. 21. under the hoodFriday, April 19, 13
  22. 22. hybrid reasoning systemFriday, April 19, 13
  23. 23. WTF?Friday, April 19, 13
  24. 24. forward backward chainningFriday, April 19, 13
  25. 25. WTF?Friday, April 19, 13
  26. 26. forwardchainning data driven/reactionary rule "Adults that like cheddar" when Cheese( $cheddar : name == "cheddar" ) $p : Person( age >= 18, favouriteCheese == $cheddar ) then System.out.println( $p.getName() + " likes cheddar!"); endFriday, April 19, 13
  27. 27. backwardchainning goal driven declare Parent declare Man declare Woman parent : String name : String name : String child : String end end end query man( String name ) Man( name := name ) end query woman( String name ) Woman( name := name ) end query parent( String parent, String child ) Parent( parent := parent, child := child ) endFriday, April 19, 13
  28. 28. backwardchainning query father( String father, String child ) ?man( father; ) ?parent( father, child; ) end query mother( String mother, String child ) ?woman( mother; ) ?parent( mother, child; ) end query son( String son, String parent ) ?man( son; ) ?parent( parent, son; ) end query daughter( String daughter, String parent ) ?woman( daughter; ) ?parent( parent, daughter; ) endFriday, April 19, 13
  29. 29. backwardforward fewer hypotheses lot’s hypotheses query data lot’s data upfrontFriday, April 19, 13
  30. 30. rete algorithmFriday, April 19, 13
  31. 31. reteoo rule "Like cheddar" when Cheese( $cheddar : name == "cheddar" ) $p : Person( favouriteCheese == $cheddar ) then System.out.println( $p.getName() + " likes cheddar" ); end rule "NOT Like cheddar" when Cheese( $cheddar : name == "cheddar" ) $p : Person( favouriteCheese != $cheddar ) then System.out.println( $p.getName() + " not like cheddar" ); endFriday, April 19, 13
  32. 32. reteoo rete node object type node alpha node left input node join node terminalFriday, April 19, 13
  33. 33. reteoo rete node object type node alpha node left input node join node terminalFriday, April 19, 13
  34. 34. reteoo rete node object type node alpha node left input node join node terminalFriday, April 19, 13
  35. 35. reteoo rete node object type node alpha node left input node join node terminalFriday, April 19, 13
  36. 36. so... how?Friday, April 19, 13
  37. 37. Friday, April 19, 13
  38. 38. codeapi final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // this will parse and compile in one step kbuilder.add( ResourceFactory.newClassPathResource("HelloWorld.drl", HelloWorldExample.class), ResourceType.DRL); // Check the builder for errors if ( kbuilder.hasErrors() ) { throw new RuntimeException("Error compiling."); } // get the compiled packages (which are serializable) final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); // add the packages to a KnowledgeBase (deploy the knowledge packages). final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(pkgs);Friday, April 19, 13
  39. 39. codeapi final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.setGlobal( "myGlobalObj", globalObj ); for( Object fact : _facts_ ) { ksession.insert( fact ); } ksession.fireUntilHalt(); ksession.fireAllRules(); SessionEntryPoint entryPoint = ksession.getEntryPoint( "entrypoint_name" ); ksession.dispose(); entryPoint.insert( _fact_ );Friday, April 19, 13
  40. 40. codeapi final StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession(); ksession.execute( _facts_ );Friday, April 19, 13
  41. 41. please one sec!Friday, April 19, 13
  42. 42. Friday, April 19, 13
  43. 43. new paradigm?Friday, April 19, 13
  44. 44. yesnoFriday, April 19, 13
  45. 45. yes you can construct your systems using almost only rules!Friday, April 19, 13
  46. 46. pong demoFriday, April 19, 13
  47. 47. no you can adapt your existing systems (few lines) to take advantage of droolsFriday, April 19, 13
  48. 48. public void aprovarPagamento(String apoliceId, String sinistroId, " " int valor, String cpfAprovador) { " if (!existeReserva(sinistroId)) { " " throw new IllegalStateException( " " " " "não existe reserva para o sinistro."); " } " Pessoa aprovador = pessoaService.buscarPessoa(cpfAprovador); " if (aprovador.getPapeis() " " " .contains(Pessoa.Papeis.COORDENADOR_SEGURADORA) " " " || aprovador.getPapeis().contains( " " " " " Pessoa.Papeis.GERENTE_SEGURADORA) " " " || aprovador.getPapeis().contains( " " " " " Pessoa.Papeis.DIRETOR_SEGURADORA) " " " || aprovador.getPapeis().contains(Pessoa.Papeis.VP_SEGURADORA)) { " " if (valor <= 5000) { " " " pagar(apoliceId, sinistroId, valor); " " } else if (valor > 500000) { " " " if (aprovador.getPapeis().contains(Pessoa.Papeis.VP_SEGURADORA)) { " " " " pagar(apoliceId, sinistroId, valor); " " " } else { " " " " throw new IllegalStateException( " " " " " " "Aprovador não tem alçada para aprovação."); " " " } " " } else if (valor <= 10000) { " " " if (aprovador.getPapeis().contains( " " " " " Pessoa.Papeis.GERENTE_SEGURADORA) " " " " " || aprovador.getPapeis().contains( " " " " " " " Pessoa.Papeis.DIRETOR_SEGURADORA) " " " " " || aprovador.getPapeis().contains( " " " " " " " Pessoa.Papeis.VP_SEGURADORA)) { " " " " pagar(apoliceId, sinistroId, valor); " " " } else { " " " " throw new IllegalStateException( " " " " " " "Aprovador não tem alçada para aprovação."); " " " } " " } else if (valor <= 500000) { " " " if (aprovador.getPapeis().contains( " " " " " Pessoa.Papeis.DIRETOR_SEGURADORA) " " " " " || aprovador.getPapeis().contains( " " " " " " " Pessoa.Papeis.VP_SEGURADORA)) { " " " " pagar(apoliceId, sinistroId, valor); " " " } else { " " " " throw new IllegalStateException( " " " " " " "Aprovador não tem alçada para aprovação."); " " " } " " } else { " " " throw new IllegalStateException("Problemas na aprovação."); " " } " } else { " " throw new IllegalStateException( " " " " "Aprovador não é funcionário da seguradora."); " } }Friday, April 19, 13
  49. 49. system control flow control flow control flow business rules business rules business rules control flow control flow control flow business rules business rules business rules business rules business rules business rules control flow control flow control flow business rules business rules business rulesFriday, April 19, 13
  50. 50. public void aprovarPagamento( String apoliceId, String sinistroId, int valor, String cpfAprovador ) { if ( !existeReserva( sinistroId ) ) { throw new IllegalStateException( "Não existe reserva para o sinistro." ); } final Pessoa aprovador = pessoaService.buscarPessoa( cpfAprovador ); final ValorPagamentoApolice pagamento = new ValorPagamentoApolice( ... ); ksession.execute( asList( aprovador, pagamento ) ); if ( !pagamento.isPago() ) { throw new IllegalArgumentException( "Pagamento nao efetuado." ); } }Friday, April 19, 13
  51. 51. rule "Coordenador tentando fraudar" " when " " p: Pessoa ( papeis contains Pessoa.Papeis.COORDENADOR_SEGURADORA ) " " v: ValorPagamentoApolice( valor > 50000 ) " " f: FinanceiroService( ) " then " System.out.println("O coordenador tentou fazer um pagamento não autorizado"); " " retract( f ); end rule "VP" " when " " m : Pessoa( papeis contains Pessoa.Papeis.VP_SEGURADORA ) " " v: ValorPagamentoApolice( valor > 500000 ) " " f: FinanceiroService( ) " then " executar(f, v); " " retract( f ); end rule "Nenhum funcionario pode aprovar sua apolice" salience 8888 " when " " p : Pessoa( $cpfPessoa: cpf ) " " v: ValorPagamentoApolice( cpfSefurado == $cpfPessoa, valor >= 50000 ) " " f: FinanceiroService( ) " then " System.out.println("O profissional tentou aprovar sua apolice."); " retract( f ); rule "Diretor ou VP" end " when " " m : Pessoa( papeis contains Pessoa.Papeis.DIRETOR_SEGURADORA || " " " " " papeis contains Pessoa.Papeis.VP_SEGURADORA ) " " v: ValorPagamentoApolice( valor > 10000 && <= 500000 ) " " f: FinanceiroService( ) " then " executar(f, v); " " retract( f ); endFriday, April 19, 13
  52. 52. system control flow control flow control flow business rules business rules business rules control flow control flow control flow business rules business rules business rules business rules business rules business rules control flow control flow control flow business rules guvnorFriday, April 19, 13
  53. 53. F.A.Q.Friday, April 19, 13
  54. 54. business analyst write rules?Friday, April 19, 13
  55. 55. yesnoFriday, April 19, 13
  56. 56. no they won’t do this: rule "NOT Like cheddar" when Cheese( $cheddar : name == "cheddar" ) $p : Person( favouriteCheese != $cheddar ) then System.out.println( $p.getName() + " not like cheddar" ); end technical ruleFriday, April 19, 13
  57. 57. yes but they can do this: decision tableFriday, April 19, 13
  58. 58. yes and this test scenarioFriday, April 19, 13
  59. 59. so... next?Friday, April 19, 13
  60. 60. droolsv6Friday, April 19, 13
  61. 61. retewilldie http://blog.athico.com/2013/01/life-beyond-rete-rip-rete-2013.htmlphreakFriday, April 19, 13
  62. 62. maven compatible project structurekjarFriday, April 19, 13
  63. 63. KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); KieSession kSession = kContainer.newKieSession("ksession2"); kSession.setGlobal("out", out); kSession.insert(new Message("Dave", "Hello, HAL. Do you read me, HAL?")); kSession.fireAllRules();newapiFriday, April 19, 13 java code
  64. 64. public class KProject { @Inject @KBase("fol4.test1.KBase1") KnowledgeBase kBase1; public KnowledgeBase getKBase1() { return kBase1; } @Inject @KBase("fol4.test2.KBase2") KnowledgeBase kBase2; public KnowledgeBase getKBase2() { return kBase2; } @Inject @KSession("fol4.test1.KSession1") StatelessKnowledgeSession kBase1kSession1;cdi public StatelessKnowledgeSession getKBase1KSession1() { return kBase1kSession1; } @Inject @KSession("fol4.test1.KSession2") StatefulKnowledgeSession kBase1kSession2; public StatefulKnowledgeSession getKBase1KSession2() { return kBase1kSession2; } } java codeFriday, April 19, 13
  65. 65. <?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> <kbase name="cdiexample"> <ksession name="ksession1"/> </kbase> </kmodule> meta-inf/kmodule.xml <?xml version="1.0" encoding="UTF-8"?> <kmodulecdi xmlns="http://jboss.org/kie/6.0.0/kmodule"> <kbase name="cdiexamplewithinclusion" includes="cdiexample"> <ksession name="ksession2"/> </kbase> </kmodule> inclusion (pom.xml dependency)Friday, April 19, 13
  66. 66. errai gwt cdi best-practices jee java scalability dev tools (ide) (template) html legacyuberfireFriday, April 19, 13
  67. 67. database+gitFriday, April 19, 13
  68. 68. shameless self promotion building world class web consoles using uberfire auditorium 4 saturday, april 20thFriday, April 19, 13
  69. 69. that’sall folks!Friday, April 19, 13
  70. 70. questions?Friday, April 19, 13
  71. 71. thanks! porcelli@redhat.com @porcelli #guvnordev #droolsdev #jbpmdev Alexandre Porcelli #optaplanner-dev Principal Software EngineerFriday, April 19, 13

×