Skip to content

Migrating from Easy Rules

This guide is for a project that runs its rules on Easy Rules 4 today and wants to run them on rulii. A rule keeps its shape: a name, a condition and one or more actions. What changes is the annotations, how values reach a rule, how rules are grouped and run, and a handful of situations that Easy Rules handles quietly and rulii does not. Each section says which. The Easy Rules side of every comparison was checked against release 4.1.0.

  1. Build on Java 17 or later. Easy Rules 4 is compiled for Java 8; rulii needs 17.
  2. Replace org.jeasy:easy-rules-core, and easy-rules-support, easy-rules-mvel, easy-rules-spel and easy-rules-jexl where you use them, with org.rulii:rulii.
  3. Rename every rule whose name is not a Java identifier: "discount rule" becomes "DiscountRule".
  4. In rule classes, change @Condition to @Given and @Action to @Then, drop @Fact where the parameter is named after the fact, move the description to @Description, and delete the priority.
  5. Replace RuleBuilder with Rule.builder().
  6. Replace Facts with bindings, and bind every value a rule writes before the run.
  7. Replace Rules and RulesEngine.fire with a RuleSet that lists the rules in the order the priorities gave them. Engine parameters become stop conditions.
  8. Replace composite rules with rule sets, listeners with tracer listeners, and expression-language rules with scripts.
  9. Run your tests with Behaviour That Differs open. An exception inside a rule is no longer logged and passed over, and a rule whose fact is missing now runs, with null in its place.
<dependency>
<groupId>org.rulii</groupId>
<artifactId>rulii</artifactId>
<version>2.3.0</version>
</dependency>

It has no dependencies of its own. The annotation support, the fluent builder and the composite rules that Easy Rules splits between easy-rules-core and easy-rules-support are all in this one artifact; the scripting engines are optional and described in section 8.

rulii matches values to rule parameters by parameter name, and reads the names from the debug information of the compiled class. Maven keeps that information by default. In a build that strips it (-g:none), name the parameters of rule classes with @Param.

A rule class stays a plain class with annotated methods.

Easy Rules:

@Rule(name = "discount rule", description = "Ten percent off orders over 100", priority = 1)
public class DiscountRule {
@Condition
public boolean overThreshold(@Fact("order") Order order) {
return order.getTotal().compareTo(THRESHOLD) > 0;
}
@Action
public void applyDiscount(@Fact("order") Order order, Facts facts) {
order.setDiscount(order.getTotal().multiply(RATE));
facts.put("discounted", true);
}
}

rulii:

@Rule(name = "DiscountRule")
@Description("Ten percent off orders over 100")
public class DiscountRule {
@Given
public boolean overThreshold(Order order) {
return order.getTotal().compareTo(THRESHOLD) > 0;
}
@Then
public void applyDiscount(Order order, Binding<Boolean> discounted) {
order.setDiscount(order.getTotal().multiply(RATE));
discounted.setValue(true);
}
}

The annotations are in org.rulii.annotation.

Easy Rules rulii
@Rule(name = ...) @Rule(name = ...). The name must be a Java identifier ([a-zA-Z$_][a-zA-Z0-9$_]*); a name with a space fails when the rule is built. Without a name, Easy Rules uses the simple class name and rulii uses it with a lower-case first letter (discountRule)
@Rule(description = ...) @Description(...) on the class
@Rule(priority = ...), a @Priority method None; rules run in the order they are listed, see section 5
@Condition @Given
@Action(order = n) @Then(order = n). Give every @Then an order when a rule has more than one; without it their relative order is unspecified
@Fact("order") Order order Order order: the parameter name is the binding name. @Param("order") Order o when the two differ
A parameter of type Facts A parameter Bindings bindings
None @PreCondition, which decides whether the rule runs at all, and @Otherwise, the actions for a false condition

A class that implements org.jeasy.rules.api.Rule or extends BasicRule becomes an annotated class: evaluate is the @Given method and execute the @Then method.

Build a Rule from the class or from an instance you constructed, and run it on its own in a test:

Rule discountRule = Rule.builder().build(new DiscountRule()); // or build(DiscountRule.class)
RuleResult result = discountRule.run(order -> myOrder, discounted -> false);
result.status(); // PASS, FAIL, SKIPPED or ERROR

See Building Rules (Declarative).

Easy Rules:

Rule discountRule = new RuleBuilder()
.name("discount rule")
.description("Ten percent off orders over 100")
.priority(1)
.when(facts -> {
Order order = facts.get("order");
return order.getTotal().compareTo(THRESHOLD) > 0;
})
.then(facts -> {
Order order = facts.get("order");
order.setDiscount(order.getTotal().multiply(RATE));
})
.build();

rulii:

import static org.rulii.model.condition.Conditions.condition;
import static org.rulii.model.action.Actions.action;
Rule discountRule = Rule.builder()
.name("DiscountRule")
.description("Ten percent off orders over 100")
.given(condition((Order order) -> order.getTotal().compareTo(THRESHOLD) > 0))
.then(action((Order order) -> order.setDiscount(order.getTotal().multiply(RATE))))
.build();

The lambda declares the values it needs as typed parameters, so the lookups and casts go. then(...) may be called more than once, as in Easy Rules, and the builder also takes preCondition(...) and otherwise(...). See Building Rules (Functional).

Bindings is the counterpart of Facts: a set of named values the rules read and write. Each binding also has a type.

Easy Rules rulii
facts.put("order", order) bindings.bind("order", order), or order -> myOrder passed to run(...)
facts.get("order") bindings.getValue("order")
put on a name that exists replaces the fact bind on a name that exists throws BindingAlreadyExistsException; change a value with setValue
put rejects a null value null is a legal value: bindings.bind("note", String.class, null)
facts.remove("order") None; a binding is not removed once bound
An action adds a result with facts.put("discounted", true) The action declares Binding<Boolean> discounted and calls setValue(true); the caller binds discounted before the run and reads it afterwards

Two things to plan for:

  • Bind the outputs up front. A rule set runs its rules in a scope of its own, and a binding that an action creates there is gone when the rule set ends. Bind each result before the run, with a starting value, and let the actions set it. An action that declares Binding<Boolean> discounted receives null when nothing is bound under that name.
  • Conditions do not write. A condition receives its arguments as read-only copies, so an Easy Rules condition that also puts a fact has to move that write into an action.

See Bindings and Binding Matching.

Easy Rules:

Rules rules = new Rules();
rules.register(new DiscountRule());
rules.register(new FreeShippingRule());
Facts facts = new Facts();
facts.put("order", myOrder);
RulesEngine engine = new DefaultRulesEngine();
engine.fire(rules, facts);

rulii:

RuleSet<RuleSetExecutionStatus> rules = RuleSet.<RuleSetExecutionStatus>builder()
.with("OrderRules")
.rule(Rule.builder().build(new DiscountRule()))
.rule(Rule.builder().build(new FreeShippingRule()))
.build();
RuleSetExecutionStatus status = rules.run(order -> myOrder, discounted -> false);

A RuleSet holds the rules and runs them; there is no separate engine object.

Order. Easy Rules sorts registered rules by priority and then by name. A rule set runs its rules in the order they were added, so list them in the order the priorities produced. Rules that shared a priority ran in name order.

Engine parameters become a stop condition on the rule set, from org.rulii.ruleset.RuleSetConditions:

RulesEngineParameters rulii
skipOnFirstAppliedRule(true) .stopCondition(stopWhenOnePasses())
skipOnFirstNonTriggeredRule(true) .stopCondition(stopWhenOneFails())
skipOnFirstFailedRule(true) Nothing to set; an exception in a rule always ends the run, see section 9
priorityThreshold(n) None; leave the rules above the threshold out of the rule set

The result. fire returns nothing. run returns a RuleSetExecutionStatus with one RuleResult per rule that ran: getPassed(), getFailed() and getSkipped() list them by outcome. A rule set can return a value of your own instead through a result extractor.

Checking without firing. engine.check(rules, facts) evaluates the conditions and runs no actions. The counterpart is isTrue on a rule:

RuleContext context = RuleContext.builder().build(bindings);
boolean applies = discountRule.isTrue(context); // the condition only; no action runs

In application code, run rules and rule sets through a RuleFlow, which declares the inputs, runs the steps in order and decides what happens on an exception. See RuleSets for pre-conditions, initializers, finalizers and result extractors.

The three composite rules in easy-rules-support become rule sets.

Easy Rules rulii
UnitRuleGroup: all rules apply, or none A rule set with .preCondition(allMustPass())
ActivationRuleGroup: the first rule that applies fires, the rest are ignored A rule set with .stopCondition(stopWhenOnePasses()), rules listed in priority order
ConditionalRuleGroup: the rule with the highest priority decides whether the others are considered A rule set whose pre-condition is that rule’s condition
import static org.rulii.ruleset.RuleSetConditions.*;
// UnitRuleGroup
RuleSet<?> allOrNothing = RuleSet.builder()
.with("LoyaltyRewards")
.preCondition(allMustPass())
.rule(isPremium).rule(isVerified).rule(hasOptedIn)
.build();
// ActivationRuleGroup
RuleSet<?> firstMatch = RuleSet.builder()
.with("DiscountTiers")
.stopCondition(stopWhenOnePasses())
.rule(platinum).rule(gold).rule(silver)
.build();
// ConditionalRuleGroup
RuleSet<?> gated = RuleSet.builder()
.with("WeekendOffers")
.preCondition(isWeekend.getCondition())
.rule(isWeekend).rule(freeShipping).rule(doublePoints)
.build();

Two differences to know:

  • When conditions are evaluated. An Easy Rules group evaluates the conditions of its members first and runs the actions afterwards. A rule set evaluates each rule’s condition immediately before that rule’s actions, so a rule sees what the rules before it changed. With allMustPass() the conditions are evaluated once as the gate, without any action, and again as each rule runs.
  • A rule set is not a rule. A composite rule could be registered among other rules. A rule set contains rules only; to run a group between other rules, make them steps of a RuleFlow: .run(ruleA).run(group).run(ruleB).

Listeners are registered on a Tracer, and the tracer is given to the RuleContext the rules run in.

Tracer tracer = Tracer.builder().build();
tracer.addListener(new RuleListener() {
@Override
public void onRuleEnd(Rule rule, RuleResult result) {
log.info("{} -> {}", rule.getName(), result.status());
}
});
RuleContext context = RuleContext.builder()
.with(bindings)
.traceUsing(tracer)
.build();
rules.run(context);
Easy Rules rulii
RuleListener.beforeEvaluate returning false to skip a rule A pre-condition on the rule (@PreCondition or .preCondition(...)); the result is SKIPPED. Listeners observe and cannot veto
RuleListener.beforeEvaluate as a notification RuleListener.onRuleStart(rule)
afterEvaluate(rule, facts, result) onGiven(rule, condition, result)
beforeExecute(rule, facts) onThen(rule, action), once for each action; onOtherwise(rule, action) for a false condition
onSuccess(rule, facts) onRuleEnd(rule, result), with the status in the result
onEvaluationError, onFailure onRuleError(rule, exception)
RulesEngineListener.beforeEvaluate(rules, facts) RuleSetListener.onRuleSetStart(ruleSet, scope)
RulesEngineListener.afterExecute(rules, facts) RuleSetListener.onRuleSetEnd(ruleSet, scope, status)

RuleListener is in org.rulii.rule and RuleSetListener in org.rulii.ruleset. The callbacks receive the rule, its condition or action and the result, not the bindings. See Rule Tracing & Debugging.

MVELRule, SpELRule and JexlRule become rules whose condition and actions are built from a Script.

Easy Rules:

Rule adultRule = new MVELRule()
.name("adult rule")
.when("person.age > 18")
.then("person.setAdult(true);");

rulii:

Rule adultRule = Rule.builder()
.name("AdultRule")
.given(Condition.builder().build(
Script.builder().with("js", "ctx.person.age > 18").build()))
.then(Action.builder().build(
Script.builder().with("js", "ctx.person.adult = true").build()))
.build();
  • Facts are not top-level variables. Easy Rules hands each fact to the expression under its own name. rulii hands the script one object, ctx, that holds the bindings: person.age becomes ctx.person.age.
  • Languages. rulii ships engines for JavaScript (js, GraalJS), Java expressions (java, Janino) and Jakarta Expression Language (jakarta-el), each active when its library is on the classpath, and runs any other language that has a JSR-223 engine on the classpath under that engine’s name. There is no MVEL engine of rulii’s own.
  • SpEL comes with rulii-spring as the language el, and the bindings are the variable #ctx: #ctx.person.age > 18. See SpEL Scripting.

Rule files. MVELRuleFactory, SpELRuleFactory and JexlRuleFactory read rules from YAML or JSON. rulii core does not read rule files. With rulii-spring, rules, rule sets and flows can be declared in XML with scripted conditions and actions; see XML Rule Definitions. Without Spring, read your own format and build each rule with Rule.builder() and Script, as above.

See Scripting Support.

Easy Rules logs most problems and carries on. rulii reports an exception to the caller, and runs a rule whose value is missing instead of passing over it. Expect these when the tests first run:

Situation Easy Rules rulii
The order of the rules Priority, then name The order they were added to the rule set
A rule name Any string A Java identifier
A condition is false Nothing happens The result is FAIL, and the rule’s @Otherwise actions run if it has any. FAIL is an outcome, not an error
A condition names a fact that is not there A warning is logged and the condition counts as false The condition runs, and the parameter receives a default: null for an object, 0 or false for a primitive
A fact has the wrong type for the parameter A warning is logged and the condition counts as false The value is converted to the parameter’s type where a converter exists; otherwise UnrulyException
A condition throws The error is logged and the condition counts as false UnrulyException, and the run ends
An action throws The error is logged, onFailure is called and the next rule runs UnrulyException, and the run ends
A null value Rejected by Facts.put Allowed
Binding a name twice The second value replaces the first BindingAlreadyExistsException

Keeping a rule’s failure from ending the run. Where the old behaviour was wanted, say so in a flow. A handler on the step catches the exception and the flow continues with the next step:

RuleFlow<RuleContext> flow = RuleFlow.builder()
.name("OrderFlow")
.run(discountRule, spec -> spec.onException(Exception.class,
handler -> handler.execute(action((Exception ex) -> log.warn("DiscountRule failed", ex)))))
.run(freeShippingRule)
.build();
flow.run(order -> myOrder, discounted -> false);

Missing values. A rule that stayed quiet when a fact was absent now runs with null in its place. A condition that uses the value without testing it throws a NullPointerException, which reaches the caller inside an UnrulyException; a condition that never touches it may pass where it used not to fire. Decide what each rule should do:

  • Test for null in the condition, or in a pre-condition so that the rule is SKIPPED.
  • Declare the parameter as Optional<Order> order; it arrives empty when nothing is bound.
  • Give it a default with @Param(defaultValue = "5") int count. The text is converted to the parameter’s type.

InferenceRulesEngine has no counterpart. It fires the rules whose conditions hold, then selects again, until no condition holds. rulii runs each rule once, in the order given, and that is by design. Rules that rely on being fired repeatedly until the facts settle do not migrate as they are; the loop has to be written out, in the calling code or as explicit steps.

The reason to migrate is what sits on top of the same idea: a result for every rule (PASS, FAIL, SKIPPED, ERROR) instead of a log line; pre-conditions and @Otherwise on the rule itself; typed bindings matched by parameter name; rule sets with pre-conditions, stop conditions and result extractors; rule flows with inputs, branching, iteration, exception handling and async steps; built-in validation rules and a Jakarta Bean Validation provider that run on the same engine; Spring integration; and rulii-explorer, which shows the rules, rule sets and flows of a running application.