From 032b5aca5dfa9c1c7d5baf3ca11ba554457b7208 Mon Sep 17 00:00:00 2001 From: Mahmoud Ben Hassine Date: Thu, 21 Mar 2019 23:19:00 +0100 Subject: [PATCH] Add support for parser context in MVEL actions Resolves #197 --- .../java/org/jeasy/rules/mvel/MVELAction.java | 12 ++++++++++++ .../org/jeasy/rules/mvel/MVELActionTest.java | 17 +++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/easy-rules-mvel/src/main/java/org/jeasy/rules/mvel/MVELAction.java b/easy-rules-mvel/src/main/java/org/jeasy/rules/mvel/MVELAction.java index 153ed54..1f2aa0a 100644 --- a/easy-rules-mvel/src/main/java/org/jeasy/rules/mvel/MVELAction.java +++ b/easy-rules-mvel/src/main/java/org/jeasy/rules/mvel/MVELAction.java @@ -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 { diff --git a/easy-rules-mvel/src/test/java/org/jeasy/rules/mvel/MVELActionTest.java b/easy-rules-mvel/src/test/java/org/jeasy/rules/mvel/MVELActionTest.java index 1ae2c0d..1e65f7b 100644 --- a/easy-rules-mvel/src/test/java/org/jeasy/rules/mvel/MVELActionTest.java +++ b/easy-rules-mvel/src/test/java/org/jeasy/rules/mvel/MVELActionTest.java @@ -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"); + + } } \ No newline at end of file