0
votes

I was using a proprietary rule engine, and I am now trying to use Drools, i'm pretty new to Drools.

With the previous rule engine, the rule were fired for all instances of existing object even if they were attribute of an other object.

I have a set of rules that are applied to a given type of object O. I add to my session and object O' having O as attribute. But as the rules are not applied to O' they won't be applied to the attribute O of O'.

I will illustrate this with an HEllo word example :

I added to the basic drool Example the following class :

 public static class Email {

        private Message message ;


        public void setMessage(Message message) {
            this.message = message;
        }

        public Message getMessage() {
            return message;
        }
}

Email is O' and Message is O.

My session "works" as follow :

            ...
            Message message = new Message();
            message.setMessage("Hello World");
            message.setStatus(Message.HELLO);
            Email email = new Email();
            email.setMessage(message);
            ksession.insert(email);
            ksession.fireAllRules();
            logger.close();
            ...

and I have a Sample drool file :

rule "Hello World"
    when
        m : Message( status == Message.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

The rule is only applied on Message .

If I launch my session the way it is, no rule will be fired . To have rules fired I need to add the rule :

rule "email"
    when 
        e : Email( message != null)
    then 
        insert(e.getMessage());
end

It works fine, but my question is : is there an easier way to have the rule fired on each instance of an object even if it's an attribute of an other object ?

1

1 Answers

1
votes

Yes you can do something like:

rule "Hello World"
    when
        $email: Email(message.status ==  Message.HELLO, $myMessage: message.message )

    then
        System.out.println( $myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

or you can just insert the message to the working memory using a rule

Rule "insert message"
   when 
      Email ($message: message)
   then
      insert($message);
end

Using this approach then you can write rules only using the Message type.

Cheers