Add support for parser context in MVEL actions

Resolves #197
pull/200/head
Mahmoud Ben Hassine 6 years ago
parent a4ccab1625
commit 032b5aca5d

@ -26,6 +26,7 @@ package org.jeasy.rules.mvel;
import org.jeasy.rules.api.Action;
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 MVELAction implements Action {
compiledExpression = MVEL.compileExpression(expression);
}
/**
* Create a new {@link MVELAction}.
*
* @param expression the action written in expression language
* @param parserContext the MVEL parser context
*/
public MVELAction(String expression, ParserContext parserContext) {
this.expression = expression;
compiledExpression = MVEL.compileExpression(expression, parserContext);
}
@Override
public void execute(Facts facts) {
try {

@ -29,6 +29,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.rules.ExpectedException;
import org.mvel2.ParserContext;
import static org.assertj.core.api.Assertions.assertThat;
@ -84,4 +85,20 @@ public class MVELActionTest {
// then
// excepted exception
}
@Test
public void testMVELActionWithExpressionAndParserContext() throws Exception {
// given
ParserContext context = new ParserContext();
context.addPackageImport("java.util");
Action printAction = new MVELAction("def random() { System.out.println(\"Random from MVEL = \" + new java.util.Random(123).nextInt(10)); }; random();", context);
Facts facts = new Facts();
// when
printAction.execute(facts);
// then
assertThat(systemOutRule.getLog()).contains("Random from MVEL = 2");
}
}
Loading…
Cancel
Save