FiendFyre
FiendFyre

Reputation: 157

can we access working memory fact of drools rule engine in jbpm6 script task?

is there a way to access working memory fact of drools rule engine in jbpm6 script task?

I have a model class : Application.java Rule : check if salary is > 10000 (part of rule group : salaryCheck )

jbpm flow : start -> salaryCheck(rule task, associated with rule group : salaryCheck) -> updateScore(script task) -> end

updateScore - script rask code:

System.out.println(System.out.println((Application)(kcontext.getKieRuntime().getFactHandles().toArray()[0]));

Error:

java.lang.ClassCastException: org.drools.core.common.DefaultFactHandle cannot be cast to org.model.Application

Updated script task:

import org.model.Application
import org.drools.runtime.rule.QueryResults
import org.drools.runtime.rule.QueryResultsRow

QueryResults results = kcontext.getKieRuntime().getQueryResults( "getObjectsOfApplication" ); 
for ( QueryResultsRow row : results ) {
    Application applicantion = ( Application ) row.get( "$result" ); 
    application.setScore(700);
    System.out.println("Application object :: "+ application);
}

Added Query to rule drl file

query "getObjectsOfApplication"
    $result: Application()
end

Upvotes: 1

Views: 2057

Answers (1)

Esteban Aliverti
Esteban Aliverti

Reputation: 6322

getFactHandles() is definitely not the method you are looking for. The method think you are looking for is getObjects(). Either way, getting the first element of the returned collection without any validation seems dangerous to me. You can't even guarantee that order of the elements in the returned collection will remain the same between different invocations.

A better approach would be to use the version of getObjects() that accepts an ObjectFilter parameter. An even better and more 'declarative' approach would be to define a query in that returns the exact object you are looking for. You can then execute the query using kcontext.getKieRuntime().getQueryResults().

You can get a better understanding on any of these 2 approaches (using an ObjectFilter or a query) in this thread: Retrieving facts of a specific type from working memory


EDIT:

The post I suggested about using a query or an ObjectFilter is Drools 5 code. In Drools 6, the API classes were moved to a different package. These are the imports you should use if you want to invoke a query in your code:

  • org.kie.api.runtime.rule.QueryResults
  • org.kie.api.runtime.rule.QueryResultsRow

These classes are both part of the kie-api project.

Upvotes: 1

Related Questions