Search code examples
jasper-reportsdrools

Using Drools rules to fill a DTO


I am using Jasper Reports to prepare a PDF file containing data coming from a business application. On the server I prepare a DTO with lots of values depending on business decisions and feed it to a template prepared with iReport. Because with the time these business decisions are increasing in number and complexity, I’m trying to see how to formalize them as rules and entrust them to Drools.

I am fairly new to Drools; I’ve ran a few example from literature and web sources; presently I see the possibility of feeding the empty DTO to the Drools session along with the business objects and let the rule fill it, like in this minimal example:

DTO dto = new DTO();
session.insert(new Purchase(new BigDecimal("30")));
session.insert(dto);
session.fireAllRules()

A rule would look like this:

rule "purchase over 25 dollars"
when
    $p : Purchase ( total > 25 )
    $d : DTO ()
then
    $d.setDiscount(0.15);
end

I must admit all this looks a bit awkward to me. I wonder if there is a cleaner way to prepare the DTO using Drools.

Every Drools-based solution is welcome. NB: Moving the business logic in the iReport template is out of discussion.


Solution

  • What causes your feeling that this isn't "clean" enough? Each new programming paradigm looks somewhat strange to the novice, so drink another cup of strong espresso and get over it.

    The Java code and the rule are basically OK as shown. Purchase is bound to be more complex, and so will be your DTO.

    You could avoid the new and insert of the DTO in your Java code and do it using a rule; in this case (and for other reasons) the DTO should be linked to some specific Purchase:

    rule "create DTO"
    when
      $p: Purchase()
      not DTO( purchase == $p )
    then
      insert new DTO( $p ) );
    end
    

    Linking a DTO to its Purchase is also a good strategy whenver there may be more than one DTO in the Working Memory at the same time. Speaking of which: you should also consider clean-up, i.e., getting the facts out of memory.