Skip to content

Commit

Permalink
Merge branch 'inference-rules-engine'
Browse files Browse the repository at this point in the history
  • Loading branch information
fmbenhassine committed Dec 11, 2017
2 parents 36544be + 5cee7c6 commit 42251de
Show file tree
Hide file tree
Showing 9 changed files with 405 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public Map<Rule, Boolean> check(Rules rules, Facts facts) {
return result;
}

private void apply(Rules rules, Facts facts) {
void apply(Rules rules, Facts facts) {
LOGGER.info("Rules evaluation started");
for (Rule rule : rules) {
final String name = rule.getName();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* The MIT License
*
* Copyright (c) 2017, Mahmoud Ben Hassine ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.rules.core;

import org.jeasy.rules.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
* Inference {@link RulesEngine} implementation.
*
* Rules are selected based on given facts and fired according to their natural order which is priority by default.
*
* The engine continuously select and fire rules until no more rules are applicable.
*
* @author Mahmoud Ben Hassine ([email protected])
*/
public final class InferenceRulesEngine implements RulesEngine {

private static final Logger LOGGER = LoggerFactory.getLogger(InferenceRulesEngine.class);

private RulesEngineParameters parameters;
private List<RuleListener> ruleListeners;
private DefaultRulesEngine delegate;

/**
* Create a new inference rules engine with default parameters.
*/
public InferenceRulesEngine() {
this(new RulesEngineParameters());
}

/**
* Create a new inference rules engine.
* @param parameters of the engine
*/
public InferenceRulesEngine(RulesEngineParameters parameters) {
this(parameters, new ArrayList<RuleListener>());
}

/**
* Create a new inference rules engine.
* @param parameters of the engine
* @param ruleListeners to apply for each rule
*/
public InferenceRulesEngine(RulesEngineParameters parameters, List<RuleListener> ruleListeners) {
this.parameters = parameters;
this.ruleListeners = ruleListeners;
delegate = new DefaultRulesEngine(parameters, ruleListeners);
}

@Override
public RulesEngineParameters getParameters() {
return parameters;
}

@Override
public List<RuleListener> getRuleListeners() {
return ruleListeners;
}

@Override
public void fire(Rules rules, Facts facts) {
Set<Rule> selectedRules;
do {
LOGGER.info("Selecting candidate rules based on the following {}", facts);
selectedRules = selectCandidates(rules, facts);
if(!selectedRules.isEmpty()) {
delegate.apply(new Rules(selectedRules), facts);
} else {
LOGGER.info("No candidate rules found for {}", facts);
}
} while (!selectedRules.isEmpty());
}

private Set<Rule> selectCandidates(Rules rules, Facts facts) {
Set<Rule> candidates = new TreeSet<>();
for (Rule rule : rules) {
if (rule.evaluate(facts)) {
candidates.add(rule);
}
}
return candidates;
}

@Override
public Map<Rule, Boolean> check(Rules rules, Facts facts) {
return delegate.check(rules, facts);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,13 @@
package org.jeasy.rules.core;

/**
* Parameters of the rules engine.
*
* Parameters of a rules engine.
*
* <ul>
* <li>When parameters are used with a {@link DefaultRulesEngine}, they are applied on all registered rules.</li>
* <li>When parameters are used with a {@link InferenceRulesEngine}, they are applied on candidate rules in each iteration.</li>
* </ul>
*
* @author Mahmoud Ben Hassine ([email protected])
*/
public class RulesEngineParameters {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
* The MIT License
*
* Copyright (c) 2017, Mahmoud Ben Hassine ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.rules.core;

import org.jeasy.rules.annotation.*;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class InferenceRulesEngineTest {

@Test
public void testCandidateSelection() throws Exception {
// Given
Facts facts = new Facts();
facts.put("foo", true);
DummyRule dummyRule = new DummyRule();
AnotherDummyRule anotherDummyRule = new AnotherDummyRule();
Rules rules = new Rules(dummyRule, anotherDummyRule);
RulesEngine rulesEngine = new InferenceRulesEngine();

// When
rulesEngine.fire(rules, facts);

// Then
assertThat(dummyRule.isExecuted()).isTrue();
assertThat(anotherDummyRule.isExecuted()).isFalse();
}

@Test
public void testCandidateOrdering() throws Exception {
// Given
Facts facts = new Facts();
facts.put("foo", true);
facts.put("bar", true);
DummyRule dummyRule = new DummyRule();
AnotherDummyRule anotherDummyRule = new AnotherDummyRule();
Rules rules = new Rules(dummyRule, anotherDummyRule);
RulesEngine rulesEngine = new InferenceRulesEngine();

// When
rulesEngine.fire(rules, facts);

// Then
assertThat(dummyRule.isExecuted()).isTrue();
assertThat(anotherDummyRule.isExecuted()).isTrue();
assertThat(dummyRule.getTimestamp()).isLessThanOrEqualTo(anotherDummyRule.getTimestamp());
}

@Rule
class DummyRule {

private boolean isExecuted;
private long timestamp;

@Condition
public boolean when(@Fact("foo") boolean foo) {
return foo;
}

@Action
public void then(Facts facts) {
isExecuted = true;
timestamp = System.currentTimeMillis();
facts.remove("foo");
}

@Priority
public int priority() {
return 1;
}

public boolean isExecuted() {
return isExecuted;
}

public long getTimestamp() {
return timestamp;
}
}

@Rule
class AnotherDummyRule {

private boolean isExecuted;
private long timestamp;

@Condition
public boolean when(@Fact("bar") boolean bar) {
return bar;
}

@Action
public void then(Facts facts) {
isExecuted = true;
timestamp = System.currentTimeMillis();
facts.remove("bar");
}

@Priority
public int priority() {
return 2;
}

public boolean isExecuted() {
return isExecuted;
}

public long getTimestamp() {
return timestamp;
}
}

}
52 changes: 52 additions & 0 deletions easy-rules-tutorials/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<tomcat7-maven-plugin.version>2.2</tomcat7-maven-plugin.version>
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>

<scm>
Expand Down Expand Up @@ -63,6 +64,13 @@
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
Expand Down Expand Up @@ -141,6 +149,50 @@
</plugins>
</build>
</profile>
<profile>
<id>runWeatherTutorial</id>
<build>
<defaultGoal>exec:java</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven-exec-plugin.version}</version>
<configuration>
<mainClass>org.jeasy.rules.tutorials.weather.Launcher</mainClass>
<systemProperties>
<systemProperty>
<key>java.util.logging.SimpleFormatter.format</key>
<value>[%1$tc] %4$s: %5$s%n</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>runAircoTutorial</id>
<build>
<defaultGoal>exec:java</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven-exec-plugin.version}</version>
<configuration>
<mainClass>org.jeasy.rules.tutorials.airco.Launcher</mainClass>
<systemProperties>
<systemProperty>
<key>java.util.logging.SimpleFormatter.format</key>
<value>[%1$tc] %4$s: %5$s%n</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>runShopTutorial</id>
<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.jeasy.rules.tutorials.airco;

import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;

@Rule(name = "air conditioning rule", description = "if it is hot, decrease temperature" )
public class AirConditioningRule {

@Condition
public boolean isItHot(@Fact("temperature") int temperature) {
return temperature > 25;
}

@Action
public void coolAir(Facts facts) {
System.out.println("It is hot! cooling air..");
Integer temperature = (Integer) facts.get("temperature");
facts.put("temperature", temperature - 1);
}

}
Loading

0 comments on commit 42251de

Please sign in to comment.