Add support for parser context in MVEL conditions

Resolves #197
pull/200/head
Mahmoud Ben Hassine 6 years ago
parent 8ea9d81ec4
commit c83ff59da8

@ -26,6 +26,7 @@ package org.jeasy.rules.mvel;
import org.jeasy.rules.api.Condition;
import org.jeasy.rules.api.Facts;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -53,6 +54,17 @@ public class MVELCondition implements Condition {
compiledExpression = MVEL.compileExpression(expression);
}
/**
* Create a new {@link MVELCondition}.
*
* @param expression the condition written in expression language
* @param parserContext the MVEL parser context
*/
public MVELCondition(String expression, ParserContext parserContext) {
this.expression = expression;
compiledExpression = MVEL.compileExpression(expression, parserContext);
}
@Override
public boolean evaluate(Facts facts) {
try {

@ -26,6 +26,7 @@ package org.jeasy.rules.mvel;
import org.jeasy.rules.api.Condition;
import org.jeasy.rules.api.Facts;
import org.junit.Test;
import org.mvel2.ParserContext;
import static org.assertj.core.api.Assertions.assertThat;
@ -57,4 +58,18 @@ public class MVELConditionTest {
// then
assertThat(evaluationResult).isFalse();
}
@Test
public void testMVELConditionWithExpressionAndParserContext() {
// given
ParserContext context = new ParserContext();
context.addPackageImport("java.util");
Condition condition = new MVELCondition("return new java.util.Random(123).nextBoolean();", context);
Facts facts = new Facts();
// when
boolean evaluationResult = condition.evaluate(facts);
// then
assertThat(evaluationResult).isTrue();
}
}
Loading…
Cancel
Save