Skip to content

Getting Started

Clayton Long edited this page Sep 30, 2017 · 9 revisions

This small example shows you how to create a RuleBook with Rules that execute actions based on conditions. It also shows how facts can be chained across rules and how a result can be derived from the execution of a RuleBook.

Add the RuleBook Core dependency

For Maven

Add the dependency

<dependency>
  <groupId>com.deliveredtechnologies</groupId>
  <artifactId>rulebook-core</artifactId>
  <version>0.10</version>
</dependency>

For Gradle

Add the dependency

compile 'com.deliveredtechnologies:rulebook-core:0.10'

Write a RuleBook using the RuleBook Java DSL

import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder;

public class PetMessage {
  /* 
   * arg[0]    the number of pets
   * arg[1]    the number of kids
   */
  public static void main(String args[]) {
    NameValueReferableMap factMap = new FactMap();
    factMap.setValue("number of pets", Integer.valueOf(args[0]));
    factMap.setValue("number of kids", Integer.valueOf(args[1]));

    RuleBook<String> petRuleBook = RuleBookBuilder.create().withResultType(String.class)
      .withDefaultResult("You're probably lonely. You could use a pet!")
      .addRule(rule -> rule
        .when(facts -> facts.IntVal("number of pets") == 0)
        .then(facts -> facts.setValue("pet owner", false)))
      .addRule(rule -> rule
        .when(facts -> facts.IntVal("number of kids") > 0)
        .then(facts -> facts.setValue("parent", true)))
      .addRule(rule -> rule.withFactType(Boolean.class)
        .when(facts -> facts.getValue("parent") && !facts.getValue("pet owner"))
        .then((facts, result) -> result.setValue("You should get a pet. Every kid should have a pet."))
        .stop())
      .addRule(rule -> rule.withFactType(Boolean.class)
        .when(facts -> facts.getValue("pet owner"))
        .then((facts, result) -> result.setValue("You're a pet owner. That's awesome!")))
      .build();

    petRuleBook.run(factMap);
    petRuleBook.getResult().ifPresent(System.out::println);
  }
}
Clone this wiki locally