Hello, Rules...

No programming introduction without the famous "HelloWorld" example - I shall make no exception. Whereas I regard it as complete nonsense to use a rule-engine to utter greetings, this simple example shows


You need four things to run a rule-based system (that is an application using a rule-engine):

  1. The rule-engine itself. I take JBoss-Rules here, you find installation instructions on their website.
  2. The rules, located in a file
  3. Your own Java classes to create some facts for the rule-engine to reason about (HelloRules.java, HelloFact.java)
  4. Glue-code to tie those things together. I use my simple RuleEngineWrapper here.

Figure showing the call sequence

hello-rules.drl - Very simple version

    rule "say it alout"
        when hello: HelloFact( );
        then System.out.println( hello.getMessage() );

When the rule engine finds an instance of class HelloFact in working memory, it'll print its message. As working memory might contain several instances of HelloFact, we have to identify our specific one by naming it "hello". In the consequence-part of the rule we can refer to this named instance to call its methods.

Our own Java classes


import ....RuleEngineWrapper; // the glue code to connect to 
public class HelloRules {
     * a declarative way of greeting... using JBoss-Rules
    public static void main(String[] args) {
        RuleEngineWrapper rew = 
            new RuleEngineWrapper("hello-rules.drl");

        HelloFact helloFact = 
            new HelloFact( "hello, rules");

        rew.addFact( helloFact ); // put it into working memory
        rew.addFact( new HelloFact("Allo, bon jour!") ); // another one

To improve our hello-world experience, I added two instances of HelloFact to the working memory.


The HelloFact-class follows the JavaBean conventions and therefore contains getters and setters for all its (public) attributes. I omitted those for brevity.

    public class HelloFact {
        public String   message;

        public HelloFact(String msg) {
            this.message = msg;
        // getter and setter omitted for brevity

The Result

The rule engine finds two instances of HelloFact in working memory, so it schedules two activations of our simple rule, one for every found instance. The output, as you expected:

    Allo, bon jour!
    hello, rules

Remark: It works fine with JBoss-Rules V.3.0.6, but fails with the 4.0.M1 release. I did not yet test it with 4.0.M3 release...

The Glue Code

I used my simple RuleEngineWrapper to glue my own code together with the drl-file and my own classes.