Kaizar Laxmidhar
Kaizar Laxmidhar

Reputation: 869

Drools rule error "Unexpected global"

I have business rules implemented in Drools, while executing I get java RuntimeException

Unexpected global [myService]
org.drools.common.AbstractWorkingMemory.setGlobal(AbstractWorkingMemory.java:588)

What could be the cause?

Rule:

rule "Tax Rule"
  when
    calculateTax : calculateTax(
        objOne : objOne,
        objTwo : objTwo,
        objThree : objThree
    );

    objFour : objFour();
    System.out.println("debug");

  then
    ...
end

Upvotes: 3

Views: 11189

Answers (5)

Null
Null

Reputation: 41

I find that is the problem of the implement of sessionful session.You can try below code

KieSession kieSession = container.newKieSession();
kieSession.getGlobals().set("total",1);

Upvotes: 0

antonpinchuk
antonpinchuk

Reputation: 453

In many cases this error means your DRL is compiled with errors, so Drools tells you "Unexpected global" because it can't find any global declaration in empty DRL.

DRL compiler does not throw any exception on errors, instead you should check it yourself using:

kieBuilder.getErrors()

Upvotes: 1

laune
laune

Reputation: 31290

This is it, for 5.x; 6.x is somewhat different:

KnowledgeBuilderConfiguration kbConfig =
    KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
//    kbConfig.setOption( sizeAccFunOption );

KnowledgeBuilder kBuilder =
    KnowledgeBuilderFactory.newKnowledgeBuilder( kbConfig );

Resource drl = ResourceFactory.newFileResource( drlPath );

kBuilder.add( drl, ResourceType.DRL );

if( kBuilder.hasErrors() ){
    System.err.println( "### compilation errors ###" );
    KnowledgeBuilderErrors errors = kBuilder.getErrors();
    for( KnowledgeBuilderError err: errors ){
    System.err.println( err.toString() );
    }
    throw new IllegalStateException( "compile errors" );
}

Upvotes: 2

Kaizar Laxmidhar
Kaizar Laxmidhar

Reputation: 869

I found the problem. I had few System.out.println() and one of them was at the place shown below. Removing that solved the problem.

rule "Tax Rule"
  when
    calculateTax : calculateTax(
        objOne : objOne,
        objTwo : objTwo,
        objThree : objThree
    );

    objFour : objFour();
    System.out.println("debug");

  then
    ...
end

Upvotes: 0

laune
laune

Reputation: 31290

To declare and set a global in your DRL, you need to declare it and initialize it:

// DRL file
global Service myService

// Java application
StatefulKnowledgeSession session = ...
session.setGlobal("myService", new Service() );

Failure to declare the global in the DRL file or a mismatch of the global's name and the first argument in the setGlobal call result in the error message as posted.

Upvotes: 12

Related Questions