Search in sources :

Example 1 with RuleTerminalNode

use of org.drools.core.reteoo.RuleTerminalNode in project drools by kiegroup.

the class RuleExecutor method fire.

private int fire(InternalWorkingMemory wm, InternalAgenda agenda, AgendaFilter filter, int fireCount, int fireLimit) {
    int localFireCount = 0;
    if (!tupleList.isEmpty()) {
        if (!fireExitedEarly && isDeclarativeAgendaEnabled()) {
            // Network Evaluation can notify meta rules, which should be given a chance to fire first
            RuleAgendaItem nextRule = agenda.peekNextRule();
            if (!isHigherSalience(nextRule)) {
                fireExitedEarly = true;
                return localFireCount;
            }
        }
        RuleTerminalNode rtn = (RuleTerminalNode) pmem.getPathEndNode();
        RuleImpl rule = rtn.getRule();
        Tuple tuple = getNextTuple();
        if (rule.isAllMatches()) {
            fireConsequenceEvent(wm, agenda, (AgendaItem) tuple, DefaultAgenda.ON_BEFORE_ALL_FIRES_CONSEQUENCE_NAME);
        }
        Tuple lastTuple = null;
        for (; tuple != null; lastTuple = tuple, tuple = getNextTuple()) {
            // if the current Rule is no-loop and the origin rule is the same then return
            if (cancelAndContinue(wm, rtn, rule, tuple, filter)) {
                continue;
            }
            AgendaItem item = (AgendaItem) tuple;
            if (agenda.getActivationsFilter() != null && !agenda.getActivationsFilter().accept(item, wm, rtn)) {
                // only relevant for seralization, to not refire Matches already fired
                continue;
            }
            fireActivation(wm, agenda, item);
            localFireCount++;
            if (rtn.getLeftTupleSource() == null) {
                // The activation firing removed this rule from the rule base
                break;
            }
            agenda.flushPropagations();
            // dyanmic salience may have updated it, so get again.
            int salience = ruleAgendaItem.getSalience();
            if (queue != null && !queue.isEmpty() && salience != queue.peek().getSalience()) {
                ruleAgendaItem.dequeue();
                ruleAgendaItem.setSalience(queue.peek().getSalience());
                ruleAgendaItem.getAgendaGroup().add(ruleAgendaItem);
            }
            if (!rule.isAllMatches()) {
                // if firing rule is @All don't give way to other rules
                if (haltRuleFiring(fireCount, fireLimit, localFireCount, agenda)) {
                    // another rule has high priority and is on the agenda, so evaluate it first
                    break;
                }
                if (!wm.isSequential()) {
                    reEvaluateNetwork(agenda);
                }
            }
        }
        if (rule.isAllMatches()) {
            fireConsequenceEvent(wm, agenda, (AgendaItem) lastTuple, DefaultAgenda.ON_AFTER_ALL_FIRES_CONSEQUENCE_NAME);
        }
    }
    removeRuleAgendaItemWhenEmpty(wm);
    fireExitedEarly = false;
    return localFireCount;
}
Also used : RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Tuple(org.drools.core.spi.Tuple) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) AgendaItem(org.drools.core.common.AgendaItem) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode)

Example 2 with RuleTerminalNode

use of org.drools.core.reteoo.RuleTerminalNode in project drools by kiegroup.

the class PhreakActivationIterator method collectAgendaItems.

public static List<AgendaItem> collectAgendaItems(InternalKnowledgeBase kbase, InternalWorkingMemory wm) {
    Set<RuleTerminalNode> nodeSet = new HashSet<RuleTerminalNode>();
    List<RuleTerminalNode> nodeList = populateRuleTerminalNodes(kbase, nodeSet);
    List<AgendaItem> agendaItems = new ArrayList<AgendaItem>();
    for (RuleTerminalNode rtn : nodeList) {
        if (!nodeSet.contains(rtn)) {
            // this node has already been processed
            continue;
        }
        processLeftTuples(rtn.getLeftTupleSource(), agendaItems, nodeSet, wm);
    }
    return agendaItems;
}
Also used : ArrayList(java.util.ArrayList) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) HashSet(java.util.HashSet)

Example 3 with RuleTerminalNode

use of org.drools.core.reteoo.RuleTerminalNode in project drools by kiegroup.

the class IncrementalCompilationTest method testRuleRemoval.

@Test
public void testRuleRemoval() throws Exception {
    String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + "   $m : Message()\n" + "then\n" + "end\n";
    String drl2 = "rule R2 when\n" + "   $m : Message( message == \"Hi Universe\" )\n" + "then\n" + "end\n";
    String drl3 = "rule R3 when\n" + "   $m : Message( message == \"Hello World\" )\n" + "then\n" + "end\n";
    KieServices ks = KieServices.Factory.get();
    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0");
    KieModule km = createAndDeployJar(ks, releaseId1, drl1 + drl2 + drl3);
    // Create a session and fire rules
    KieContainer kc = ks.newKieContainer(km.getReleaseId());
    KiePackage kpkg = kc.getKieBase().getKiePackage("org.drools.compiler");
    assertEquals(3, kpkg.getRules().size());
    Map<String, Rule> rules = rulestoMap(kpkg.getRules());
    assertNotNull(rules.get("R1"));
    assertNotNull(rules.get("R2"));
    assertNotNull(rules.get("R3"));
    RuleTerminalNode rtn1_1 = (RuleTerminalNode) ((KnowledgeBaseImpl) kc.getKieBase()).getReteooBuilder().getTerminalNodes("org.drools.compiler.R1")[0];
    RuleTerminalNode rtn2_1 = (RuleTerminalNode) ((KnowledgeBaseImpl) kc.getKieBase()).getReteooBuilder().getTerminalNodes("org.drools.compiler.R2")[0];
    RuleTerminalNode rtn3_1 = (RuleTerminalNode) ((KnowledgeBaseImpl) kc.getKieBase()).getReteooBuilder().getTerminalNodes("org.drools.compiler.R3")[0];
    // Create a new jar for version 1.1.0
    ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0");
    km = createAndDeployJar(ks, releaseId2, drl1 + drl3);
    // try to update the container to version 1.1.0
    kc.updateToVersion(releaseId2);
    KnowledgeBaseImpl rb_2 = ((KnowledgeBaseImpl) kc.getKieBase());
    RuleTerminalNode rtn1_2 = (RuleTerminalNode) rb_2.getReteooBuilder().getTerminalNodes("org.drools.compiler.R1")[0];
    RuleTerminalNode rtn3_2 = (RuleTerminalNode) rb_2.getReteooBuilder().getTerminalNodes("org.drools.compiler.R3")[0];
    assertNull(rb_2.getReteooBuilder().getTerminalNodes("org.drools.compiler.R2"));
    assertSame(rtn3_1, rtn3_2);
    assertSame(rtn1_1, rtn1_2);
    kpkg = kc.getKieBase().getKiePackage("org.drools.compiler");
    assertEquals(2, kpkg.getRules().size());
    rules = rulestoMap(kpkg.getRules());
    assertNotNull(rules.get("R1"));
    assertNull(rules.get("R2"));
    assertNotNull(rules.get("R3"));
}
Also used : KiePackage(org.kie.api.definition.KiePackage) KieServices(org.kie.api.KieServices) KnowledgeBaseImpl(org.drools.core.impl.KnowledgeBaseImpl) ReleaseId(org.kie.api.builder.ReleaseId) Rule(org.kie.api.definition.rule.Rule) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule) KieModule(org.kie.api.builder.KieModule) KieContainer(org.kie.api.runtime.KieContainer) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) Test(org.junit.Test)

Example 4 with RuleTerminalNode

use of org.drools.core.reteoo.RuleTerminalNode in project drools by kiegroup.

the class MarshallingTest method testScheduledActivation.

@Test
@Ignore("This test is suspicious to say the least...")
public void testScheduledActivation() {
    KnowledgeBaseImpl knowledgeBase = (KnowledgeBaseImpl) KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgePackageImpl impl = new KnowledgePackageImpl("test");
    BuildContext buildContext = new BuildContext(knowledgeBase);
    // simple rule that fires after 10 seconds
    final RuleImpl rule = new RuleImpl("test-rule");
    new RuleTerminalNode(1, new MockTupleSource(2), rule, rule.getLhs(), 0, buildContext);
    final List<String> fired = new ArrayList<String>();
    rule.setConsequence(new Consequence() {

        public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
            fired.add("a");
        }

        public String getName() {
            return "default";
        }
    });
    rule.setTimer(new DurationTimer(10000));
    rule.setPackage("test");
    impl.addRule(rule);
    knowledgeBase.addPackages(Collections.singleton(impl));
    SessionConfiguration config = SessionConfiguration.newInstance();
    config.setClockType(ClockType.PSEUDO_CLOCK);
    KieSession ksession = knowledgeBase.newKieSession(config, KieServices.get().newEnvironment());
    PseudoClockScheduler scheduler = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();
    Marshaller marshaller = MarshallerFactory.newMarshaller(knowledgeBase);
    ksession.insert("cheese");
    assertTrue(fired.isEmpty());
    // marshall, then unmarshall session
    readWrite(knowledgeBase, ksession, config);
    // the activations should fire after 10 seconds
    assertTrue(fired.isEmpty());
    scheduler.advanceTime(12, TimeUnit.SECONDS);
    assertFalse(fired.isEmpty());
}
Also used : Marshaller(org.kie.api.marshalling.Marshaller) WorkingMemory(org.drools.core.WorkingMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) ArrayList(java.util.ArrayList) Consequence(org.drools.core.spi.Consequence) KnowledgeBaseImpl(org.drools.core.impl.KnowledgeBaseImpl) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) IOException(java.io.IOException) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler) DurationTimer(org.drools.core.time.impl.DurationTimer) MockTupleSource(org.drools.core.reteoo.MockTupleSource) BuildContext(org.drools.core.reteoo.builder.BuildContext) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KieSession(org.kie.api.runtime.KieSession) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) SessionConfiguration(org.drools.core.SessionConfiguration) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with RuleTerminalNode

use of org.drools.core.reteoo.RuleTerminalNode in project drools by kiegroup.

the class MarshallingTest method testSingleRuleSingleJoinNodePattern.

@Test
public void testSingleRuleSingleJoinNodePattern() throws Exception {
    String rule = "package org.drools.compiler.test;\n";
    rule += "import org.drools.compiler.Person\n";
    rule += "import org.drools.compiler.Cheese\n";
    rule += "global java.util.List list\n";
    rule += "rule \"Rule 1\"\n";
    rule += "when\n";
    rule += "    $c : Cheese( ) \n";
    rule += "    $p : Person( cheese == $c ) \n";
    rule += "then\n";
    rule += "    list.add( $p );\n";
    rule += "end";
    KieBase kBase = loadKnowledgeBaseFromString(rule);
    // Make sure the rete node map is created correctly
    Map<Integer, BaseNode> nodes = RuleBaseNodes.getNodeMap((InternalKnowledgeBase) kBase);
    assertEquals(5, nodes.size());
    assertEquals("Cheese", ((ClassObjectType) ((ObjectTypeNode) nodes.get(3)).getObjectType()).getClassType().getSimpleName());
    assertEquals("Person", ((ClassObjectType) ((ObjectTypeNode) nodes.get(5)).getObjectType()).getClassType().getSimpleName());
    assertTrue("Should end with JoinNode", nodes.get(6).getClass().getSimpleName().endsWith("JoinNode"));
    assertEquals("Rule 1", ((RuleTerminalNode) nodes.get(7)).getRule().getName());
    KieSession session = kBase.newKieSession();
    List list = new ArrayList();
    session.setGlobal("list", list);
    Cheese stilton = new Cheese("stilton", 25);
    Cheese brie = new Cheese("brie", 49);
    Person bobba = new Person("bobba fet", 32);
    bobba.setCheese(stilton);
    Person vadar = new Person("darth vadar", 32);
    session.insert(stilton);
    session.insert(bobba);
    session.insert(vadar);
    session.insert(brie);
    session = SerializationHelper.getSerialisedStatefulKnowledgeSession(session, kBase, true);
    session.fireAllRules();
    assertEquals(1, ((List) session.getGlobal("list")).size());
    assertEquals(bobba, ((List) session.getGlobal("list")).get(0));
    Person c3po = new Person("c3p0", 32);
    c3po.setCheese(stilton);
    session.insert(c3po);
    session = SerializationHelper.getSerialisedStatefulKnowledgeSession(session, kBase, true);
    session.fireAllRules();
    assertEquals(2, ((List) session.getGlobal("list")).size());
    assertEquals(c3po, ((List) session.getGlobal("list")).get(1));
    Person r2d2 = new Person("r2d2", 32);
    r2d2.setCheese(brie);
    session.insert(r2d2);
    session = SerializationHelper.getSerialisedStatefulKnowledgeSession(session, kBase, true);
    session.fireAllRules();
    assertEquals(3, ((List) session.getGlobal("list")).size());
    assertEquals(r2d2, ((List) session.getGlobal("list")).get(2));
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) KieBase(org.kie.api.KieBase) BaseNode(org.drools.core.common.BaseNode) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) IteratorToList(org.drools.compiler.integrationtests.IteratorToList) Cheese(org.drools.compiler.Cheese) Person(org.drools.compiler.Person) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) Test(org.junit.Test)

Aggregations

RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)69 Test (org.junit.Test)54 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)38 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)30 LeftInputAdapterNode (org.drools.core.reteoo.LeftInputAdapterNode)28 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)23 KieBase (org.kie.api.KieBase)23 SegmentMemory (org.drools.core.reteoo.SegmentMemory)18 JoinNode (org.drools.core.reteoo.JoinNode)16 PathMemory (org.drools.core.reteoo.PathMemory)16 ArrayList (java.util.ArrayList)14 ClassObjectType (org.drools.core.base.ClassObjectType)13 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)13 List (java.util.List)12 LiaNodeMemory (org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory)11 WorkingMemory (org.drools.core.WorkingMemory)10 RightInputAdapterNode (org.drools.core.reteoo.RightInputAdapterNode)9 FactHandle (org.kie.api.runtime.rule.FactHandle)9 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)9 KnowledgeBaseImpl (org.drools.core.impl.KnowledgeBaseImpl)8