3

I'm writing a RESTful service to calculate some values according some rules.

For example:

There is a JSON like this:

{ "amount": 100,
  "destination":"A"
}

This data is a request body, post to my controller:

@RequestMapping(value = "/orders", method= RequestMethod.POST)
public void getOrderRequest(@RequestBody Order order){

// use Drools to calculate and return the result

}

Here is the entity class:

public class Order{
    private Integer amount;
    private String destination;
    private Float price;
    // getters and setters
}

I use Drools to calculate the price(fake code):

package rules
import entity.Order
rule "rule1"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(amount <= 50 && destination=="A") 
    then
        $s.setPrice(1000);
        update($s);

rule "rule2"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(amount > 50 && destination=="A") 
    then
        $s.setPrice(2000);
        update($s);

This works fine.All rules can be changed and worked without restarting my REST service.

Here is a scenario , a new field added to the order JSON:

{ "amount": 100,
  "destination":"A",
  "customer":"Trump"
}

Add a new rule: If the customer is Trump, then double the price:

rule "rule3"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(customer == "Trump") 
    then
        $s.setPrice(price * 2);
        update($s);

But I have to add a new variable to my Order class and restart my service.

I wonder that is there any way to make it happen without restarting my REST service ?

Or can I just handle JSON data dynamically with other BRMSs ?

epicGeek
  • 72
  • 2
  • 10

1 Answers1

5

Use Map to carry all the Order details:

public class Order{
    private Map<String, Object> fields;
    // getters and setters
}

If you manage to add values from JSON into Map then you can write your rule like this:

rule "rule3"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(fields["customer"] == "Trump") 
    then
        $s.setPrice(price * 2);
        update($s);
Master Drools
  • 728
  • 6
  • 18