Simple Rule Engine Updated
Simple Rule Engine Updated
Join the DZone community and get the full member experience.Join For Free
Download the blueprint that can take a company of any maturity level all the way up to enterprise-scale continuous delivery using a combination of Automic Release Automation, Automic’s 20+ years of business automation experience, and the proven tools and practices the company is already leveraging.
First off, the Maven dependencies. The following dependency is for the basic rule engine which is compatible with Java 6.
<dependency> <groupId>ch.maxant</groupId> <artifactId>rules</artifactId> <version>2.1.0</version> </dependency>
If you want to use lambdas from Java 8, then you need to also add a dependency as follows:
<dependency> <groupId>ch.maxant</groupId> <artifactId>rules-java8</artifactId> <version>2.1.0</version> </dependency>
This allows you to write code like that found on lines 15 and 20.
Rule rule1 =newRule("R1", "input.p1.name == \"ant\" && input.p2.name == \"clare\"", "outcome1", 0, "ch.maxant.produits", "Règle spéciale pour famille Kutschera"); Rule rule2 =newRule("R2","true","outcome2",1, "ch.maxant.produits","Régle par défault"); List<Rule> rules =Arrays.asList(rule1, rule2); //to use a lambda, construct a SamAction and pass it a lambda. IAction<MyInput,BigDecimal> action1 = newSamAction<MyInput,BigDecimal>( "outcome1", i ->newBigDecimal("100.0") ); IAction<MyInput,BigDecimal> action2 = newSamAction<MyInput,BigDecimal>( "outcome2", i ->newBigDecimal("101.0") ); List<IAction<MyInput,BigDecimal>> actions = Arrays.asList(action1, action2); Engine e =newEngine(rules,true); MyInput input =newMyInput(); Person p1 =newPerson("ant"); Person p2 =newPerson("clare"); input.setP1(p1); input.setP2(p2); BigDecimal price = e.executeBestAction(input, actions); assertEquals(newBigDecimal("101.0"), price);
If you want to pass a Stream to the
Engine rather than a
Collection, then use the sub-class found in the second library, for example:
Stream<Rule> streamOfRules = getStreamOfRules(); //to pass in a stream, we need to use a different Engine Java8Engine e =newJava8Engine(streamOfRules,true); //use this engine as you would the normal Engine
See the tests on GitHub for more details. In theory, you can pass in a parallel stream - I haven't tried it but would be interested to hear about your successes / failures.
Finally, if you are using Scala, there is still support for that too, in the
ScalaEngine which can be found in the following dependency. See the tests onGitHub for more details.
<dependency> <groupId>ch.maxant</groupId> <artifactId>rules-scala</artifactId> <version>2.1.0</version> </dependency>
Published at DZone with permission of Ant Kutschera , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.