Donnerstag, 23. Mai 2013

Drools Part 3 - The Power of rules

Currently I am quite happy. This was easier as expected. When I first took a look at the JBoss Drools Website I just got the impression, that this could be something cool, but I did not get the point where to start? But as I said this is not the first time I am using Drools. So I have been there and after some internet research I found multiple examples to get some small examples running.

Enough gibberish let's start to check out other things about rules. So what I did not like about the previous rule and test was that we have to set the limit value in the test as well as in the rule. Normally such a value should be configurable, so it has to be set. Therefore, we can use global variables in Drools. Taking a look at the documentation at http://docs.jboss.org/drools/release/5.5.0.Final/drools-expert-docs/html/ch04.html#d0e4569 you get the idea behind global variabless and also some possibilities to misuse them :-). 

   global Double ALERTVALUE

   rule "Critical value" 
      
      when
         $v : SensorValue ( value > ALERTVALUE)
      then
         System.err.println("Critical sensor value");

   end

No we can inject the value of alertValue into the rule, by using the setGlobal method of our session.

   ksession.setGlobal("ALERTVALUE", 50.0);

When testing this rule, I also tried double and int as data types, as for example suggested by Jeremy, other books and some blogs. For me it did not work. I do not know why, but I got a parsing exception (unknown class).

Another thing is that we can bind variables:

   rule "Critical value"       

      when         
         SensorValue ($id : sensorId)           
         $v : SensorValue ( value >50.0 )      
      then          
         System.err.println("Critical sensor value in " + $id);  

   end

As you can see, it is possible to bind the sensor id to the variable §id and use it in the consequence. This rule shows another interesting thing about rules. When firing rules, the number of fired rules is returned as result of the method call. When using this rule, I got 10000 fired rules, but I only inserted 100 sensor values. The reason for this behavior is the cross product which is the result of the join. So instead of writing rules this way, the size of the cross product should be minimized.

   global Double alertValue
   
   rule "Critical value"      

      when         
         $v : SensorValue ( value > alertValue, $id : sensorId ) 
      then         
         System.err.println("Critical sensor value in " + $id);   

   end

Another possibility is to use the getter of the bound object.

   System.err.println("Critical sensor value in " + 
      $v.getSensorId());

Well, there is so much more about rules and their configuration. I will extend this post in the future, but there are other things to explore, for example decision tables.

Keine Kommentare:

Kommentar veröffentlichen