Search code examples
javadroolsrule-engine

drools, rules directly in java


Is there any way to use drools by implementing rules condition directly and fully in java, like it's possible in

https://github.com/j-easy/easy-rules (look in section "declarative way" and section "programmatic way")

something like that:

@Rule(name = "weather rule", description = "if it rains then take an umbrella" )
public class WeatherRule {

@Condition
public boolean itRains(@Fact("rain") boolean rain) {
    return rain;
}

@Action
public void takeAnUmbrella() {
    System.out.println("It rains, take an umbrella!");
}
}

or maybe

Rule weatherRule = new RuleBuilder()
    .name("weather rule")
    .description("if it rains then take an umbrella")
    .when(facts -> facts.get("rain").equals(true))
    .then(facts -> System.out.println("It rains, take an umbrella!"))
    .build();

Solution

  • Recently a new feature was added that enables users to represent rules in a Java model [1]. You could use this feature to build rules in plain Java. There is a test class that you could check to see some examples. See here [2]. You have the option to choose from PatternDSL or FlowDSL (what suits you better).

    To get a KieBase with the Java rules, you could do this (as stated in the linked doc.):

    Model model = new ModelImpl().addRule( rule );
    KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
    

    [1] https://docs.jboss.org/drools/release/7.15.0.Final/drools-docs/html_single/index.html#executable-model-con_kie-apis
    [2] https://github.com/kiegroup/drools/blob/3826ee0c95fe139041880f52f3e00309b7907871/drools-model/drools-canonical-model/src/test/java/org/drools/model/FlowDSLTest.java#L21