[slf4j]: Use SLF4J (#114)

Use SLF4J instead of JUL
pull/112/merge
David Belmez Vicente 7 years ago committed by Mahmoud Ben Hassine
parent a342bc26ad
commit a074f93e10

@ -50,6 +50,10 @@
</licenses>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

@ -27,40 +27,42 @@ import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class DefaultRuleListener implements RuleListener {
private static final Logger LOGGER = Logger.getLogger(DefaultRuleListener.class.getName());
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRuleListener.class);
@Override
public boolean beforeEvaluate(Rule rule, Facts facts) {
public boolean beforeEvaluate(final Rule rule, final Facts facts) {
return true;
}
@Override
public void afterEvaluate(Rule rule, Facts facts, boolean evaluationResult) {
String ruleName = rule.getName();
public void afterEvaluate(final Rule rule, final Facts facts, final boolean evaluationResult) {
final String ruleName = rule.getName();
if (evaluationResult) {
LOGGER.log(Level.INFO, "Rule ''{0}'' triggered", ruleName);
LOGGER.info("Rule ''{}'' triggered", ruleName);
} else {
LOGGER.log(Level.INFO, "Rule ''{0}'' has been evaluated to false, it has not been executed", ruleName);
LOGGER.info("Rule ''{}'' has been evaluated to false, it has not been executed", ruleName);
}
}
@Override
public void beforeExecute(Rule rule, Facts facts) {
public void beforeExecute(final Rule rule, final Facts facts) {
}
@Override
public void onSuccess(Rule rule, Facts facts) {
LOGGER.log(Level.INFO, "Rule ''{0}'' performed successfully", rule.getName());
public void onSuccess(final Rule rule, final Facts facts) {
LOGGER.info("Rule ''{}'' performed successfully", rule.getName());
}
@Override
public void onFailure(Rule rule, Facts facts, Exception exception) {
LOGGER.log(Level.SEVERE, String.format("Rule '%s' performed with error", rule.getName()), exception);
public void onFailure(final Rule rule, final Facts facts, final Exception exception) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Rule '" + rule.getName() + "' performed with error", exception);
}
}
}

@ -23,13 +23,17 @@
*/
package org.jeasy.rules.core;
import org.jeasy.rules.api.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default {@link RulesEngine} implementation.
@ -42,7 +46,7 @@ import static java.lang.String.format;
*/
public final class DefaultRulesEngine implements RulesEngine {
private static final Logger LOGGER = Logger.getLogger(RulesEngine.class.getName());
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRuleListener.class);
/**
* The engine parameters
@ -81,9 +85,6 @@ public final class DefaultRulesEngine implements RulesEngine {
this.ruleListeners = new ArrayList<>();
this.ruleListeners.add(new DefaultRuleListener());
this.ruleListeners.addAll(ruleListeners);
if (parameters.isSilentMode()) {
Utils.muteLoggers();
}
}
@Override
@ -99,7 +100,7 @@ public final class DefaultRulesEngine implements RulesEngine {
@Override
public void fire(Rules rules, Facts facts) {
if (rules.isEmpty()) {
LOGGER.warning("No rules registered! Nothing to apply");
LOGGER.warn("No rules registered! Nothing to apply");
return;
}
logEngineParameters();
@ -126,13 +127,13 @@ public final class DefaultRulesEngine implements RulesEngine {
final String name = rule.getName();
final int priority = rule.getPriority();
if (priority > parameters.getPriorityThreshold()) {
LOGGER.log(Level.INFO,
"Rule priority threshold ({0}) exceeded at rule ''{1}'' with priority={2}, next rules will be skipped",
new Object[]{parameters.getPriorityThreshold(), name, priority});
LOGGER.info("Rule priority threshold ({}) exceeded at rule ''{}'' with priority={}, next rules will be skipped",
parameters.getPriorityThreshold(), name, priority);
break;
}
if (!shouldBeEvaluated(rule, facts)) {
LOGGER.log(Level.INFO, "Rule ''{0}'' has been skipped before being evaluated", name);
LOGGER.info("Rule ''{}'' has been skipped before being evaluated",
name);
continue;
}
boolean evaluationResult;
@ -140,7 +141,8 @@ public final class DefaultRulesEngine implements RulesEngine {
evaluationResult = rule.evaluate(facts);
} catch (NoSuchFactException e) {
if (parameters.isSkipOnMissingFact()) {
LOGGER.log(Level.INFO, "Rule ''{0}'' has been skipped due to missing fact ''{1}''", new Object[]{name, e.getMissingFact()});
LOGGER.info("Rule ''{}'' has been skipped due to missing fact ''{}''",
name, e.getMissingFact());
continue;
} else {
throw new RuntimeException(e);
@ -211,29 +213,37 @@ public final class DefaultRulesEngine implements RulesEngine {
}
private void logEngineParameters() {
LOGGER.log(Level.INFO, "Rule priority threshold: {0}", parameters.getPriorityThreshold());
LOGGER.log(Level.INFO, "Skip on first applied rule: {0}", parameters.isSkipOnFirstAppliedRule());
LOGGER.log(Level.INFO, "Skip on first non triggered rule: {0}", parameters.isSkipOnFirstNonTriggeredRule());
LOGGER.log(Level.INFO, "Skip on first failed rule: {0}", parameters.isSkipOnFirstFailedRule());
LOGGER.log(Level.INFO, "Skip on missing fact: {0}", parameters.isSkipOnMissingFact());
LOGGER.info("Rule priority threshold: {}",
parameters.getPriorityThreshold());
LOGGER.info("Skip on first applied rule: {}",
parameters.isSkipOnFirstAppliedRule());
LOGGER.info("Skip on first non triggered rule: {}",
parameters.isSkipOnFirstNonTriggeredRule());
LOGGER.info("Skip on first failed rule: {}",
parameters.isSkipOnFirstFailedRule());
LOGGER.info("Skip on missing fact: {}",
parameters.isSkipOnMissingFact());
}
private void log(Rules rules) {
LOGGER.log(Level.INFO, "Registered rules:");
for (Rule rule : rules) {
LOGGER.log(Level.INFO, format("Rule { name = '%s', description = '%s', priority = '%s'}",
rule.getName(), rule.getDescription(), rule.getPriority()));
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Registered rules:");
for (Rule rule : rules) {
LOGGER.info("Rule { name = '{}', description = '{}', priority = '{}'}",
rule.getName(), rule.getDescription(), rule.getPriority());
}
}
}
private void log(Facts facts) {
LOGGER.log(Level.INFO, "Known facts:");
for (Map.Entry<String, Object> fact : facts) {
LOGGER.log(Level.INFO, format("Fact { %s : %s }",
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Known facts:");
for (Map.Entry<String, Object> fact : facts) {
LOGGER.info("Fact { {} : {} }",
fact.getKey(),
fact.getValue() == null ? "null" : fact.getValue().toString())
);
fact.getValue() == null ? "null" : fact.getValue().toString()
);
}
}
}
}

@ -36,9 +36,9 @@ import java.util.List;
*/
public class RulesEngineBuilder {
private RulesEngineParameters parameters;
private final RulesEngineParameters parameters;
private List<RuleListener> ruleListeners;
private final List<RuleListener> ruleListeners;
/**
* Create a new rules engine builder.
@ -50,7 +50,7 @@ public class RulesEngineBuilder {
}
private RulesEngineBuilder() {
parameters = new RulesEngineParameters(false, false, false, false, RulesEngineParameters.DEFAULT_RULE_PRIORITY_THRESHOLD, false);
parameters = new RulesEngineParameters(false, false, false, false, RulesEngineParameters.DEFAULT_RULE_PRIORITY_THRESHOLD);
ruleListeners = new ArrayList<>();
}
@ -121,13 +121,11 @@ public class RulesEngineBuilder {
}
/**
* Set silent mode to mute all loggers.
*
* @param silentMode to set
* @return the rules engine builder
* @deprecated Silent mode is now log implementation config. Now it uses slf4j facade
* <strong>This will be removed in v3.2</strong>
*/
@Deprecated
public RulesEngineBuilder withSilentMode(final boolean silentMode) {
parameters.setSilentMode(silentMode);
return this;
}

@ -33,7 +33,7 @@ public class RulesEngineParameters {
/**
* Default rule priority threshold.
*/
public static int DEFAULT_RULE_PRIORITY_THRESHOLD = Integer.MAX_VALUE;
public static final int DEFAULT_RULE_PRIORITY_THRESHOLD = Integer.MAX_VALUE;
/**
* Parameter to skip next applicable rules when a rule is applied.
@ -60,11 +60,6 @@ public class RulesEngineParameters {
*/
private int priorityThreshold;
/**
* Parameter to mute loggers.
*/
private boolean silentMode;
/**
* Create a new {@link RulesEngineParameters} with default values.
*/
@ -74,15 +69,24 @@ public class RulesEngineParameters {
/**
* Create a new {@link RulesEngineParameters}
* @deprecated Use {@link RulesEngineParameters#RulesEngineParameters(boolean, boolean, boolean, boolean, int, boolean)} instead.
* @deprecated Use {@link RulesEngineParameters#RulesEngineParameters(boolean, boolean, boolean, boolean, int)} instead.
* <strong>This constructor will be removed in v3.2</strong>
*/
@Deprecated
public RulesEngineParameters(boolean skipOnFirstAppliedRule, boolean skipOnFirstFailedRule, int priorityThreshold, boolean silentMode) {
public RulesEngineParameters(final boolean skipOnFirstAppliedRule, final boolean skipOnFirstFailedRule, final int priorityThreshold, final boolean silentMode) {
this.skipOnFirstAppliedRule = skipOnFirstAppliedRule;
this.skipOnFirstFailedRule = skipOnFirstFailedRule;
this.priorityThreshold = priorityThreshold;
this.silentMode = silentMode;
}
/**
* Create a new {@link RulesEngineParameters}.
* @deprecated Use {@link RulesEngineParameters#RulesEngineParameters(boolean, boolean, boolean, boolean, int)} instead.
* <strong>This constructor will be removed in v3.2</strong>
*/
@Deprecated
public RulesEngineParameters(final boolean skipOnFirstAppliedRule, final boolean skipOnFirstFailedRule, final boolean skipOnFirstNonTriggeredRule, final boolean skipOnMissingFact, final int priorityThreshold, final boolean silentMode) {
this(skipOnFirstAppliedRule, skipOnFirstFailedRule, skipOnFirstNonTriggeredRule, skipOnMissingFact, priorityThreshold);
}
/**
@ -93,38 +97,46 @@ public class RulesEngineParameters {
* @param skipOnFirstNonTriggeredRule parameter to skip next applicable rules on first non triggered rule.
* @param skipOnMissingFact parameter to skip a rule if a declared fact is missing.
* @param priorityThreshold threshold after which rules should be skipped.
* @param silentMode parameter to mute all loggers.
*/
public RulesEngineParameters(boolean skipOnFirstAppliedRule, boolean skipOnFirstFailedRule, boolean skipOnFirstNonTriggeredRule, boolean skipOnMissingFact, int priorityThreshold, boolean silentMode) {
public RulesEngineParameters(final boolean skipOnFirstAppliedRule, final boolean skipOnFirstFailedRule, final boolean skipOnFirstNonTriggeredRule, final boolean skipOnMissingFact, final int priorityThreshold) {
this.skipOnFirstAppliedRule = skipOnFirstAppliedRule;
this.skipOnFirstFailedRule = skipOnFirstFailedRule;
this.skipOnFirstNonTriggeredRule = skipOnFirstNonTriggeredRule;
this.skipOnMissingFact = skipOnMissingFact;
this.priorityThreshold = priorityThreshold;
this.silentMode = silentMode;
}
public int getPriorityThreshold() {
return priorityThreshold;
}
public void setPriorityThreshold(int priorityThreshold) {
this.priorityThreshold = priorityThreshold;
/**
* @deprecated Silent mode is now log implementation config. Now it uses slf4j facade
* <strong>This will be removed in v3.2</strong>
*/
@Deprecated
public boolean isSilentMode() {
return false;
}
public boolean isSilentMode() {
return silentMode;
/**
* @deprecated Silent mode is now log implementation config. Now it uses slf4j facade
* <strong>This will be removed in v3.2</strong>
*/
@Deprecated
public void setSilentMode(final boolean silentMode) {
}
public void setSilentMode(boolean silentMode) {
this.silentMode = silentMode;
public void setPriorityThreshold(final int priorityThreshold) {
this.priorityThreshold = priorityThreshold;
}
public boolean isSkipOnFirstAppliedRule() {
return skipOnFirstAppliedRule;
}
public void setSkipOnFirstAppliedRule(boolean skipOnFirstAppliedRule) {
public void setSkipOnFirstAppliedRule(final boolean skipOnFirstAppliedRule) {
this.skipOnFirstAppliedRule = skipOnFirstAppliedRule;
}
@ -132,7 +144,7 @@ public class RulesEngineParameters {
return skipOnFirstNonTriggeredRule;
}
public void setSkipOnFirstNonTriggeredRule(boolean skipOnFirstNonTriggeredRule) {
public void setSkipOnFirstNonTriggeredRule(final boolean skipOnFirstNonTriggeredRule) {
this.skipOnFirstNonTriggeredRule = skipOnFirstNonTriggeredRule;
}
@ -140,7 +152,7 @@ public class RulesEngineParameters {
return skipOnFirstFailedRule;
}
public void setSkipOnFirstFailedRule(boolean skipOnFirstFailedRule) {
public void setSkipOnFirstFailedRule(final boolean skipOnFirstFailedRule) {
this.skipOnFirstFailedRule = skipOnFirstFailedRule;
}
@ -148,7 +160,7 @@ public class RulesEngineParameters {
return skipOnMissingFact;
}
public void setSkipOnMissingFact(boolean skipOnMissingFact) {
public void setSkipOnMissingFact(final boolean skipOnMissingFact) {
this.skipOnMissingFact = skipOnMissingFact;
}
}

@ -23,55 +23,14 @@
*/
package org.jeasy.rules.core;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import static java.util.Arrays.asList;
final class Utils {
private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());
static {
try {
if (System.getProperty("java.util.logging.config.file") == null &&
System.getProperty("java.util.logging.config.class") == null) {
LogManager.getLogManager().readConfiguration(Utils.class.getResourceAsStream("/logging.properties"));
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to load logging configuration file", e);
}
}
private Utils() {
}
static void muteLoggers() {
Enumeration<String> loggerNames = LogManager.getLogManager().getLoggerNames();
while (loggerNames.hasMoreElements()) {
String loggerName = loggerNames.nextElement();
if (loggerName.startsWith("org.jeasy.rules")) {
muteLogger(loggerName);
}
}
}
private static void muteLogger(final String logger) {
Logger.getLogger(logger).setUseParentHandlers(false);
Handler[] handlers = Logger.getLogger(logger).getHandlers();
for (Handler handler : handlers) {
Logger.getLogger(logger).removeHandler(handler);
}
}
static <A extends Annotation> A findAnnotation(final Class<A> targetAnnotation, final Class<?> annotatedType) {
A foundAnnotation = annotatedType.getAnnotation(targetAnnotation);

@ -1,4 +0,0 @@
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=INFO
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tF %tT.%1$tL %4$s [%2$s] - %5$s %6$s%n

@ -23,22 +23,24 @@
*/
package org.jeasy.rules.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import org.assertj.core.api.Assertions;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Priority;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.RuleListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import org.mockito.InOrder;
import org.mockito.Mock;
/**
* Test class for {@link DefaultRulesEngine}.
@ -56,7 +58,6 @@ public class DefaultRulesEngineTest extends AbstractTest {
public void setup() throws Exception {
super.setup();
when(rule1.getName()).thenReturn("r");
when(rule1.getDescription()).thenReturn("d");
when(rule1.getPriority()).thenReturn(1);
annotatedRule = new AnnotatedRule();
}

@ -23,6 +23,8 @@
*/
package org.jeasy.rules.core;
import static org.assertj.core.api.Assertions.assertThat;
import org.jeasy.rules.api.RuleListener;
import org.jeasy.rules.api.RulesEngine;
import org.junit.Test;
@ -30,8 +32,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class RulesEngineBuilderTest {
@ -64,7 +64,6 @@ public class RulesEngineBuilderTest {
RulesEngine rulesEngine = RulesEngineBuilder.aNewRulesEngine()
.withRuleListener(ruleListener)
.withRulePriorityThreshold(expectedThreshold)
.withSilentMode(true)
.withSkipOnFirstNonTriggeredRule(true)
.withSkipOnFirstAppliedRule(true)
.withSkipOnFirstFailedRule(true)
@ -74,9 +73,8 @@ public class RulesEngineBuilderTest {
assertThat(rulesEngine).isNotNull();
RulesEngineParameters parameters = rulesEngine.getParameters();
assertThat(parameters.getPriorityThreshold()).isEqualTo(expectedThreshold);
assertThat(parameters.isSilentMode()).isTrue();
assertThat(parameters.isSkipOnFirstAppliedRule()).isTrue();
assertThat(parameters.isSkipOnFirstFailedRule()).isTrue();
assertThat(parameters.isSkipOnFirstNonTriggeredRule()).isTrue();
}
}
}

@ -23,18 +23,17 @@
*/
package org.jeasy.rules.tutorials.fizzbuzz;
import static org.jeasy.rules.core.RulesEngineBuilder.aNewRulesEngine;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import static org.jeasy.rules.core.RulesEngineBuilder.aNewRulesEngine;
public class FizzBuzzWithEasyRules {
public static void main(String[] args) {
// create rules engine
RulesEngine fizzBuzzEngine = aNewRulesEngine()
.withSkipOnFirstAppliedRule(true)
.withSilentMode(true)
.build();
// create rules

@ -23,16 +23,20 @@
*/
package org.jeasy.rules.tutorials.web;
import static org.jeasy.rules.core.RulesEngineBuilder.aNewRulesEngine;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import static org.jeasy.rules.core.RulesEngineBuilder.aNewRulesEngine;
@WebFilter("/*")
public class SuspiciousRequestFilter implements Filter {
@ -41,7 +45,7 @@ public class SuspiciousRequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
rulesEngine = aNewRulesEngine().withSilentMode(true).build();
rulesEngine = aNewRulesEngine().build();
rules = new Rules();
rules.register(new SuspiciousRequestRule());
}
@ -58,4 +62,4 @@ public class SuspiciousRequestFilter implements Filter {
public void destroy() {
}
}
}

@ -30,6 +30,7 @@
<junit.version>4.12</junit.version>
<assertj.version>2.6.0</assertj.version>
<mockito.version>2.7.1</mockito.version>
<slf4j-api.version>1.7.25</slf4j-api.version>
<maven-cobertura-plugin.version>2.7</maven-cobertura-plugin.version>
<maven-coveralls-plugin.version>4.3.0</maven-coveralls-plugin.version>
<maven-release-plugin.version>2.5.3</maven-release-plugin.version>
@ -84,6 +85,12 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -187,4 +194,4 @@
</plugins>
</build>
</project>
</project>

Loading…
Cancel
Save