Skip to content
Ryan Brush edited this page Oct 4, 2013 · 1 revision

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

  • Java Beans are treated as first-class facts in Clara.
  • Clara offers a simple Java API

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

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

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:

for (QueryResult result: memory.query("clara.examples.java.shopping/get-promotions")) {
    System.out.println("Query result: " + result.getResult("?promotion"));
}

The full source code for this example is here.

##Resources

Clone this wiki locally