javadroolskie-workbenchdrools-kie-server

How can I read facts outside of the KieSession that were inserted inside of the KieSession­ (e.g. rules results)?


During my rules execution, I will be "inserting" new fact object in memory that I will need to read when the rules are done firing. How can I read those facts when outside the Rules Session?

I have tried to insert the fact with an outIdentifier, from outside the session (i.e. before the "fireAllRules()" method). However, because I may not know how many AccountingPeriod fact may get inserted during the rule session, or even if it will get inserted, this method does not seem suitable.

Accounting Period Fact:

package sample.package;

public class AccountingPeriod {

    private LocalDate accountingDate;
    private int personKey;

    public AccountingPeriod(LocalDate accountingDate, int personKey) {
        this.accountingDate = accountingDate;
        this.personKey = personKey;
    }

    public LocalDate getAccountingDate() { return accountingDate; }
    public LocalDate getPersonKey() { return personKey; }
}

Execution Code :

sample.package;
public static void main(String args[]) {
    StatelessKieSession ksession = [initialized KieSession]

    ksession.execute(Arrays.asList(Facts[]));
    [Code here to get the AccountingPeriod fact inserted in the rule session]
}

myRules.drl

rule
    when [some condition]
    then
        insert (new AccountingPeriod(LocalDate.of(year, month, day), 100));
end

Solution

  • I just found a way to get the facts from a stateless KieSession.

    sample.package;
    public static void main(String args[]) {
        StatelessKieSession ksession = [initialized KieSession]
        List<Command> cmds = new ArrayList<>();
    
        cmds.add([all required commands]);
        cmds.add(CommandFactory.newFireAllRules());
        cmds.add(CommandFactory.newGetObjects("facts"));
        ExecutionResults rulesResults = kSession.execute(CommandFactory.newBatchExecution(cmds));
        Collection<Object> results = (Collection<Object>) rulesResults.getValue("facts");
    }
    

    It turns out that by linking a command to an OutIdentifier ("facts", in this case) we can get its return value by using the getValue(outIdentifier) of the KieSession results.