Java Usage

Clara offers first-class integration with Java in two ways:

  • Java Beans are treated as first-class facts
  • A simple Java API makes Clara easy to use

Rules can be loaded very simply by using the clara.rules.RuleLoader.

static final WorkingMemory emptyMemory =
  RuleLoader.loadRules("clara.examples.java");

The returned WorkingMemory is an immutable object, and any changes like adding facts or fire rules creates a new WorkingMemory, just as the direct Clojure use does.

Don’t fear: internally, the new WorkingMemory shares most of its state with the previous version, so this is efficient!

Because the working memory is immutable, it’s safe to load your ruleset and save an instance of your WorkingMemory as a static object. Rather than re-created a working memory every time (which can be relatively expensive), we can simply hold onto an “empty” working memory, and reuse it any time we want to start with a blank slate for a new set of facts.

We can then use our working memory. Here we insert some facts – JavaBeans for a Customer and an Order object:

// Create some facts to add to the working memory.
List facts = Arrays.asList(new Customer("Tim", true), new Order(250));

// Insert some facts and fire the rules.
WorkingMemory memory = emptyMemory.insert(facts).fireRules();

Finally, we run a query against our working memory and print the results. The name of the query is simply the namespace/query-name, and the getResult method on each result returns the value of the specified field in the query:

List<QueryResult> results = memory.query("clara.examples.java/get-promotions"))

for (QueryResult result: results) {
    System.out.println("Query result: " +
                        result.getResult("?promotion"));
}

The full source code for this example is here.