use of org.drools.core.common.AgendaItem in project drools by kiegroup.
the class ActivationIteratorTest method testLianPlusEvalnWithSharing.
@Test
public void testLianPlusEvalnWithSharing() {
// Rule 0 single LiaNode
// Rule 1 and 2 are shared
// Rule 3 shares the LIANode with 1 and 2
// Rule 4 Shares the eval with 3
String str = "package org.kie.test \n" + "\n" + "rule rule0 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + "then\n" + "end\n" + "rule rule1 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + " eval( Integer.parseInt( $s ) <= 2 ) \n" + "then\n" + "end\n" + "rule rule2 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + " eval( Integer.parseInt( $s ) <= 2 ) \n" + "then\n" + "end\n" + "rule rule3 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + " eval( Integer.parseInt( $s ) > 2 ) \n" + "then\n" + "end\n" + "rule rule4 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + " eval( Integer.parseInt( $s ) > 2 ) \n" + " eval( Integer.parseInt( $s ) > 3 ) \n" + "then\n" + "end\n" + "rule rule5 @Propagation(EAGER) when\n" + " $s : String( this != 'xx' )\n" + " eval( Integer.parseInt( $s ) > 2 ) \n" + " eval( Integer.parseInt( $s ) > 3 ) \n" + "then\n" + "end\n" + "rule rule6 @Propagation(EAGER) when\n" + " java.util.Map()\n" + "then\n" + "end\n" + "\n";
KieSession ksession = new KieHelper().addContent(str, ResourceType.DRL).build().newKieSession();
for (int i = 0; i < 5; i++) {
ksession.insert(new String("" + i));
}
evaluateEagerList(ksession);
Iterator it = ActivationIterator.iterator(ksession);
List list = new ArrayList();
for (AgendaItem act = (AgendaItem) it.next(); act != null; act = (AgendaItem) it.next()) {
list.add(act.getRule().getName() + ":" + act.getDeclarationValue("$s") + ":" + act.isQueued());
}
assertContains(new String[] { "rule0:0:true", "rule0:1:true", "rule0:2:true", "rule0:3:true", "rule0:4:true", "rule1:0:true", "rule1:1:true", "rule1:2:true", "rule2:0:true", "rule2:1:true", "rule2:2:true", "rule3:3:true", "rule3:4:true", "rule4:4:true", "rule5:4:true" }, list);
ksession.fireAllRules();
it = ActivationIterator.iterator(ksession);
list = new ArrayList();
for (AgendaItem act = (AgendaItem) it.next(); act != null; act = (AgendaItem) it.next()) {
list.add(act.getRule().getName() + ":" + act.getDeclarationValue("$s") + ":" + act.isQueued());
}
assertContains(new String[] { "rule0:0:false", "rule0:1:false", "rule0:2:false", "rule0:3:false", "rule0:4:false", "rule1:0:false", "rule1:1:false", "rule1:2:false", "rule2:0:false", "rule2:1:false", "rule2:2:false", "rule3:3:false", "rule3:4:false", "rule4:4:false", "rule5:4:false" }, list);
}
use of org.drools.core.common.AgendaItem in project drools by kiegroup.
the class MVELConsequence method evaluate.
@Override
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
// same as lambda consequence...
Tuple tuple = knowledgeHelper.getTuple();
Declaration[] declarations = ((RuleTerminalNode) knowledgeHelper.getMatch().getTuple().getTupleSink()).getRequiredDeclarations();
Variable[] vars = consequence.getVariables();
// ...but the facts are association of Variable and its value, preserving order.
Map<Variable, Object> facts = new LinkedHashMap<>();
int declrCounter = 0;
for (Variable var : vars) {
if (var.isFact()) {
Declaration declaration = declarations[declrCounter++];
InternalFactHandle fh = tuple.get(declaration);
facts.put(var, declaration.getValue((InternalWorkingMemory) workingMemory, fh.getObject()));
} else {
facts.put(var, workingMemory.getGlobal(var.getName()));
}
}
ScriptBlock scriptBlock = null;
try {
scriptBlock = (ScriptBlock) consequence.getBlock();
} catch (ClassCastException e) {
throw new RuntimeException("I tried to access a ScriptBlock but it was not. So something is thinking is a MVEL consequence but did not set the MVEL script textual representation", e);
}
String originalRHS = scriptBlock.getScript();
String name = context.getRule().getPackageName() + "." + context.getRule().getName();
String expression = MVELConsequenceBuilder.processMacros(originalRHS);
String[] globalIdentifiers = new String[] {};
String[] default_inputIdentifiers = new String[] { "this", "drools", "kcontext", "rule" };
String[] inputIdentifiers = Stream.concat(Arrays.asList(default_inputIdentifiers).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getName())).collect(Collectors.toList()).toArray(new String[] {});
String[] default_inputTypes = new String[] { "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.kie.api.definition.rule.Rule" };
String[] inputTypes = Stream.concat(Arrays.asList(default_inputTypes).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getType().getName())).collect(Collectors.toList()).toArray(new String[] {});
// ^^ please notice about inputTypes, it is to use the Class.getName(), because is later used by the Classloader internally in MVEL to load the class,
// do NOT replace with getCanonicalName() otherwise inner classes will not be loaded correctly.
int languageLevel = 4;
boolean strictMode = true;
boolean readLocalsFromTuple = false;
EvaluatorWrapper[] operators = new EvaluatorWrapper[] {};
Declaration[] previousDeclarations = new Declaration[] {};
Declaration[] localDeclarations = new Declaration[] {};
String[] otherIdentifiers = new String[] {};
MVELCompilationUnit cu = new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, strictMode, readLocalsFromTuple);
// TODO unfortunately the MVELDialectRuntimeData would be the one of compile time
// the one from runtime is not helpful, in fact the dialect registry for runtime is empty:
// MVELDialectRuntimeData runtimeData = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
MVELDialectRuntimeData runtimeData = new MVELDialectRuntimeData();
// this classloader will be used by the CompilationUnit to load the imports.
runtimeData.onAdd(null, Thread.currentThread().getContextClassLoader());
runtimeData.addPackageImport(context.getPkg().getName());
runtimeData.addPackageImport("java.lang");
// therefore we assume for the ScriptBlock all available KBPackages are the default available and imported for the scope of the Script itself.
for (KiePackage kp : context.getKnowledgePackages()) {
if (!kp.getName().equals(context.getPkg().getName())) {
runtimeData.addPackageImport(kp.getName());
}
}
// sometimes here it was passed as a 2nd argument a String?? similar to `rule R in file file.drl`
Serializable cuResult = cu.getCompiledExpression(runtimeData);
ExecutableStatement compiledExpression = (ExecutableStatement) cuResult;
// TODO the part above up to the ExecutableStatement compiledExpression should be cached.
Map<String, Object> mvelContext = new HashMap<>();
mvelContext.put("this", knowledgeHelper);
mvelContext.put("drools", knowledgeHelper);
mvelContext.put("kcontext", knowledgeHelper);
mvelContext.put("rule", knowledgeHelper.getRule());
for (Entry<Variable, Object> kv : facts.entrySet()) {
mvelContext.put(kv.getKey().getName(), kv.getValue());
}
CachingMapVariableResolverFactory cachingFactory = new CachingMapVariableResolverFactory(mvelContext);
VariableResolverFactory factory = cu.getFactory(knowledgeHelper, ((AgendaItem) knowledgeHelper.getMatch()).getTerminalNode().getRequiredDeclarations(), knowledgeHelper.getRule(), knowledgeHelper.getTuple(), null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver());
cachingFactory.setNextFactory(factory);
MVEL.executeExpression(compiledExpression, knowledgeHelper, cachingFactory);
}
use of org.drools.core.common.AgendaItem in project drools by kiegroup.
the class WorkingMemoryLogger method extractDeclarations.
/**
* Creates a string representation of the declarations of an activation.
* This is a list of name-value-pairs for each of the declarations in the
* tuple of the activation. The name is the identifier (=name) of the
* declaration, and the value is a toString of the value of the
* parameter, followed by the id of the fact between parentheses.
*
* @param match The match from which the declarations should be extracted
* @return A String represetation of the declarations of the activation.
*/
private String extractDeclarations(Match match) {
final StringBuilder result = new StringBuilder();
List<String> declarations = match.getDeclarationIds();
Map<String, Declaration> declsMap = ((AgendaItem) match).getTerminalNode().getSubRule().getOuterDeclarations();
for (int i = 0; i < declarations.size(); i++) {
String declaration = declarations.get(i);
Declaration decl = declsMap.get(declaration);
InternalFactHandle handle = ((Tuple) match).get(decl);
if (!handle.isValid()) {
continue;
}
Object value = decl.getValue(null, handle.getObject());
result.append(declaration);
result.append("=");
if (value == null) {
// this should never occur
result.append("null");
} else {
result.append(value);
}
if (i < declarations.size() - 1) {
result.append("; ");
}
}
return result.toString();
}
use of org.drools.core.common.AgendaItem in project drools by kiegroup.
the class DefaultKnowledgeHelper method unblockAllMatches.
public void unblockAllMatches(Match act) {
AgendaItem targetMatch = (AgendaItem) act;
boolean wasBlocked = (targetMatch.getBlockers() != null && !targetMatch.getBlockers().isEmpty());
for (LinkedListEntry entry = (LinkedListEntry) targetMatch.getBlockers().getFirst(); entry != null; ) {
LinkedListEntry tmp = (LinkedListEntry) entry.getNext();
LogicalDependency dep = (LogicalDependency) entry.getObject();
((AgendaItem) dep.getJustifier()).removeBlocked(dep);
entry = tmp;
}
if (wasBlocked) {
RuleAgendaItem ruleAgendaItem = targetMatch.getRuleAgendaItem();
InternalAgenda agenda = workingMemory.getAgenda();
agenda.stageLeftTuple(ruleAgendaItem, targetMatch);
}
}
use of org.drools.core.common.AgendaItem in project drools by kiegroup.
the class DefaultKnowledgeHelper method cancelMatch.
public void cancelMatch(Match act) {
AgendaItem match = (AgendaItem) act;
((RuleTerminalNode) match.getTerminalNode()).cancelMatch(match, workingMemory);
}
Aggregations