Always
Always

Reputation: 23

Get expression value from drools

I want to get expression value from drools.The drl like this.

global java.util.Map $globalVar;
global java.lang.Object $result;

import java.util.Map;

function myFunc(Map map){
    return "hello";
}

rule "onlyone"
when
    $factMap: Map($tmpResult:(myFunc($globalVar)), eval(true))
then
    $result = $tmpResult;
end

When the rule get exception,like this

Caused by: org.mvel2.PropertyAccessException: [unable to resolve method: java.util.Map.$globalVar() [argslength=0]]

The global variable $globarVar has no relation with the fact.

It is likely drools can't recognize the global variable.Is there any grammar error in my drl?

Upvotes: 0

Views: 659

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15180

Your syntax is so wrong I can't even figure out what you're trying to do.

Functions are very simple, they're just like methods in Java. They even look like methods in Java -- yours is missing a return type.

function String myFunc(Map map) {
  return "hello";
}

function String greeting(String name) {
  return "Hello, " + name + ". How are you?"
}

You can invoke them in your rules as you would any other function, either on the left hand side ("when") or on the right hand side ("then").

rule "Apply Greeting and Send Memo"
when
  $memo: Memo( $recipient: recipient, sent == false )
  $greeting: String() from greeting($recipient)
then
  MemoSender.send($greeting, $memo);
  modify( $memo ) {
    setSent(true)
  };
end

rule "Apply Greeting and Send Memo - v2"
when
  $memo: Memo( $recipient: recipient, sent == false )
then
  String $greeting = greeting($recipient);
  MemoSender.send( $greeting, $memo );
  modify( $memo ) {
    setSent(true)
  }
end

The bits with the globals in your question are red herrings. Yes, they're not working and throwing errors, but the syntax is so wrong that I'm not sure how it was supposed to work in the first place.

One way you might interact with a global in a function would possibly be something like ...

global Float taxRate; // passed in as a global because it's an external constant value
global Float freeShippingThreshold;

function float calculateTotal(float subtotal) {
  // some math here that references taxRate
  return calculatedTotal
}

rule "Apply free shipping"
when
  Cart( $subtotal: subtotal )
  Float( this >= freeShippingThreshold) from calculateTotal($subtotal)
then
  // you get free shipping
end

Upvotes: 1

Related Questions