use of org.drools.mvel.expr.MVELConsequence in project drools by kiegroup.
the class MVELConsequenceBuilder method build.
public void build(final RuleBuildContext context, String consequenceName) {
// pushing consequence LHS into the stack for variable resolution
context.getDeclarationResolver().pushOnBuildStack(context.getRule().getLhs());
try {
MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
final RuleDescr ruleDescr = context.getRuleDescr();
String text = (RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName)) ? (String) ruleDescr.getConsequence() : (String) ruleDescr.getNamedConsequences().get(consequenceName);
text = processMacros(text);
text = rewriteModify(text);
Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
AnalysisResult analysis = dialect.analyzeBlock(context, text, new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context, Collections.EMPTY_MAP, KnowledgeHelper.class), null, "drools", KnowledgeHelper.class);
if (analysis == null) {
// something bad happened, issue already logged in errors
return;
}
text = rewriteUpdates(context, analysis, text);
final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
final Declaration[] declarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
String[] declrStr = new String[declarations.length];
int j = 0;
for (String str : usedIdentifiers.getDeclrClasses().keySet()) {
declrStr[j] = str;
declarations[j++] = decls.get(str);
}
Arrays.sort(declarations, SortDeclarations.instance);
for (int i = 0; i < declrStr.length; i++) {
declrStr[i] = declarations[i].getIdentifier();
}
context.getRule().setRequiredDeclarationsForConsequence(consequenceName, declrStr);
MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, declarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.CONSEQUENCE);
MVELConsequence expr = new MVELConsequence(unit, dialect.getId(), consequenceName);
if (RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName)) {
context.getRule().setConsequence(expr);
} else {
context.getRule().addNamedConsequence(consequenceName, expr);
}
MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
data.addCompileable(context.getRule(), expr);
expr.compile(data, context.getRule());
} catch (final Exception e) {
copyErrorLocation(e, context.getRuleDescr());
context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Unable to build expression for 'consequence': " + e.getMessage() + " '" + context.getRuleDescr().getConsequence() + "'"));
}
}
use of org.drools.mvel.expr.MVELConsequence in project drools by kiegroup.
the class MVELConsequenceBuilderTest method testImperativeCodeError.
@Test
public void testImperativeCodeError() throws Exception {
InternalKnowledgePackage pkg = CoreComponentFactory.get().createKnowledgePackage("pkg1");
final RuleDescr ruleDescr = new RuleDescr("rule 1");
ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");
Properties properties = new Properties();
properties.setProperty("drools.dialect.default", "mvel");
KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);
KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());
final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjeectType);
final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);
final Declaration declaration = new Declaration("cheese", extractor, pattern);
final Map<String, Declaration> map = new HashMap<String, Declaration>();
map.put("cheese", declaration);
declarationResolver.setDeclarations(map);
context.setDeclarationResolver(declarationResolver);
final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
final Cheese cheddar = new Cheese("cheddar", 10);
final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
kbHelper.setActivation(item);
try {
((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
context.getRule().getConsequence().evaluate(kbHelper, ksession);
fail("should throw an exception, as 'if' is not allowed");
} catch (Exception e) {
}
assertEquals(10, cheddar.getPrice());
}
use of org.drools.mvel.expr.MVELConsequence in project drools by kiegroup.
the class MVELDebugTest method testDebug.
@Test
public void testDebug() throws Exception {
String rule = "package com.sample; dialect \"mvel\" rule myRule when then\n System.out.println( \"test\" ); end";
KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
DrlParser parser = new DrlParser(LanguageLevelOption.DRL5);
PackageDescr packageDescr = parser.parse(null, rule);
RuleDescr ruleDescr = packageDescr.getRules().get(0);
builder = new KnowledgeBuilderImpl();
builder.addPackage(packageDescr);
InternalKnowledgePackage pkg = builder.getPackage("com.sample");
MVELConsequence consequence = (MVELConsequence) pkg.getRule("myRule").getConsequence();
String ruleName = ruleDescr.getNamespace() + "." + ruleDescr.getClassName();
System.out.println(ruleName);
assertEquals("com.sample.Rule_myRule", ruleName);
}
use of org.drools.mvel.expr.MVELConsequence in project drools by kiegroup.
the class MVELConsequenceBuilderTest method testSimpleExpression.
@Test
public void testSimpleExpression() throws Exception {
PackageDescr pkgDescr = new PackageDescr("pkg1");
KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl();
pkgBuilder.addPackage(pkgDescr);
InternalKnowledgePackage pkg = pkgBuilder.getPackageRegistry("pkg1").getPackage();
final RuleDescr ruleDescr = new RuleDescr("rule 1");
ruleDescr.setNamespace("pkg1");
ruleDescr.setConsequence("modify (cheese) {price = 5 };\nretract (cheese)");
DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");
final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjeectType, "cheese");
final GroupElement subrule = new GroupElement(GroupElement.AND);
subrule.addChild(pattern);
final Map<String, Declaration> map = new HashMap<String, Declaration>();
map.put("cheese", pattern.getDeclaration());
declarationResolver.setDeclarations(map);
context.setDeclarationResolver(declarationResolver);
final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
PropagationContextFactory pctxFactory = RuntimeComponentFactory.get().getPropagationContextFactory();
kBase.addPackage(pkg);
StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
BuildContext buildContext = new BuildContext(kBase, Collections.emptyList());
MockTupleSource source = new MockTupleSource(1, buildContext);
source.setObjectCount(1);
RuleTerminalNode rtn = new RuleTerminalNode(0, source, context.getRule(), subrule, 0, buildContext);
final Cheese cheddar = new Cheese("cheddar", 10);
final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
final LeftTupleImpl tuple = new LeftTupleImpl(f0, rtn, true);
f0.removeLeftTuple(tuple);
final AgendaItem item = new AgendaItemImpl(0, tuple, 10, pctxFactory.createPropagationContext(1, PropagationContext.Type.DELETION, null, null, null), rtn, null);
final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
kbHelper.setActivation(item);
((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
context.getRule().getConsequence().evaluate(kbHelper, ksession);
assertEquals(5, cheddar.getPrice());
}
use of org.drools.mvel.expr.MVELConsequence in project drools by kiegroup.
the class MVELConsequenceBuilderTest method testMVELDebugSymbols.
@Test
public void testMVELDebugSymbols() throws DroolsParserException {
MVELDebugHandler.setDebugMode(true);
try {
final DrlParser parser = new DrlParser(LanguageLevelOption.DRL5);
final PackageDescr pkgDescr = parser.parse(new InputStreamReader(getClass().getResourceAsStream("mvel_rule.drl")));
// just checking there is no parsing errors
assertFalse(parser.getErrors().toString(), parser.hasErrors());
InternalKnowledgePackage pkg = CoreComponentFactory.get().createKnowledgePackage("org.drools");
final RuleDescr ruleDescr = pkgDescr.getRules().get(0);
final KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
Dialect dialect = dialectRegistry.getDialect("mvel");
RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, dialect);
RuleBuilder.build(context);
assertTrue(context.getErrors().toString(), context.getErrors().isEmpty());
final RuleImpl rule = context.getRule();
MVELConsequence mvelCons = (MVELConsequence) rule.getConsequence();
mvelCons.compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
String s = DebugTools.decompile(mvelCons.getCompExpr());
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(4, count);
} finally {
MVELDebugHandler.setDebugMode(false);
}
}
Aggregations