Search in sources :

Example 21 with AgendaItem

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);
}
Also used : ActivationIterator(org.drools.core.common.ActivationIterator) Iterator(org.drools.core.util.Iterator) ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) AgendaItem(org.drools.core.common.AgendaItem) Test(org.junit.Test)

Example 22 with AgendaItem

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);
}
Also used : ScriptBlock(org.drools.model.functions.ScriptBlock) AgendaItem(org.drools.core.common.AgendaItem) ExecutableStatement(org.mvel2.compiler.ExecutableStatement) Arrays(java.util.Arrays) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) InternalFactHandle(org.drools.core.common.InternalFactHandle) HashMap(java.util.HashMap) RuleContext(org.drools.modelcompiler.RuleContext) LinkedHashMap(java.util.LinkedHashMap) MVELConsequenceBuilder(org.drools.compiler.rule.builder.dialect.mvel.MVELConsequenceBuilder) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KiePackage(org.kie.api.definition.KiePackage) WorkingMemory(org.drools.core.WorkingMemory) Variable(org.drools.model.Variable) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) Consequence(org.drools.core.spi.Consequence) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Stream(java.util.stream.Stream) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Tuple(org.drools.core.spi.Tuple) ScriptBlock(org.drools.model.functions.ScriptBlock) Entry(java.util.Map.Entry) MVEL(org.mvel2.MVEL) EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) Serializable(java.io.Serializable) Variable(org.drools.model.Variable) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) AgendaItem(org.drools.core.common.AgendaItem) LinkedHashMap(java.util.LinkedHashMap) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) KiePackage(org.kie.api.definition.KiePackage) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) ExecutableStatement(org.mvel2.compiler.ExecutableStatement) EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Tuple(org.drools.core.spi.Tuple)

Example 23 with AgendaItem

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();
}
Also used : Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) AgendaItem(org.drools.core.common.AgendaItem) Tuple(org.drools.core.spi.Tuple)

Example 24 with AgendaItem

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);
    }
}
Also used : InternalAgenda(org.drools.core.common.InternalAgenda) RuleAgendaItem(org.drools.core.phreak.RuleAgendaItem) LinkedListEntry(org.drools.core.util.LinkedListEntry) LogicalDependency(org.drools.core.common.LogicalDependency) SimpleLogicalDependency(org.drools.core.beliefsystem.simple.SimpleLogicalDependency) RuleAgendaItem(org.drools.core.phreak.RuleAgendaItem) AgendaItem(org.drools.core.common.AgendaItem)

Example 25 with AgendaItem

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);
}
Also used : RuleAgendaItem(org.drools.core.phreak.RuleAgendaItem) AgendaItem(org.drools.core.common.AgendaItem) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode)

Aggregations

AgendaItem (org.drools.core.common.AgendaItem)27 Test (org.junit.Test)17 ArrayList (java.util.ArrayList)15 List (java.util.List)14 Iterator (org.drools.core.util.Iterator)13 KieSession (org.kie.api.runtime.KieSession)13 KieHelper (org.kie.internal.utils.KieHelper)13 ActivationIterator (org.drools.core.common.ActivationIterator)12 RuleAgendaItem (org.drools.core.phreak.RuleAgendaItem)6 Declaration (org.drools.core.rule.Declaration)6 InternalFactHandle (org.drools.core.common.InternalFactHandle)5 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)5 HashMap (java.util.HashMap)3 DefaultKnowledgeHelper (org.drools.core.base.DefaultKnowledgeHelper)3 AgendaItemImpl (org.drools.core.common.AgendaItemImpl)3 InternalAgenda (org.drools.core.common.InternalAgenda)3 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)3 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)3 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)3 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)3