Search in sources :

Example 11 with RightInputAdapterNode

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

the class CollectBuilder method build.

/**
 * @inheritDoc
 */
public void build(final BuildContext context, final BuildUtils utils, final RuleConditionElement rce) {
    boolean existSubNetwort = false;
    final Collect collect = (Collect) rce;
    context.pushRuleComponent(collect);
    final List<BetaNodeFieldConstraint> resultBetaConstraints = context.getBetaconstraints();
    final List<AlphaNodeFieldConstraint> resultAlphaConstraints = context.getAlphaConstraints();
    final Pattern sourcePattern = collect.getSourcePattern();
    // get builder for the pattern
    final ReteooComponentBuilder builder = utils.getBuilderFor(sourcePattern);
    // save tuple source and pattern offset for later if needed
    final LeftTupleSource tupleSource = context.getTupleSource();
    final int currentPatternIndex = context.getCurrentPatternOffset();
    // builds the source pattern
    builder.build(context, utils, sourcePattern);
    // if object source is null, then we need to adapt tuple source into a subnetwork
    if (context.getObjectSource() == null) {
        RightInputAdapterNode riaNode = context.getComponentFactory().getNodeFactoryService().buildRightInputNode(context.getNextId(), context.getTupleSource(), tupleSource, context);
        // attach right input adapter node to convert tuple source into an object source
        context.setObjectSource(utils.attachNode(context, riaNode));
        // restore tuple source from before the start of the sub network
        context.setTupleSource(tupleSource);
        // create a tuple start equals constraint and set it in the context
        final TupleStartEqualsConstraint constraint = TupleStartEqualsConstraint.getInstance();
        final List<BetaNodeFieldConstraint> betaConstraints = new ArrayList<BetaNodeFieldConstraint>();
        betaConstraints.add(constraint);
        context.setBetaconstraints(betaConstraints);
        existSubNetwort = true;
    }
    BetaConstraints binder = utils.createBetaNodeConstraint(context, context.getBetaconstraints(), false);
    // indexing for the results should be always disabled
    BetaConstraints resultBinder = utils.createBetaNodeConstraint(context, resultBetaConstraints, true);
    CollectAccumulator accumulator = new CollectAccumulator(collect, existSubNetwort);
    Accumulate accumulate = new SingleAccumulate(sourcePattern, sourcePattern.getRequiredDeclarations(), accumulator);
    AccumulateNode accNode = context.getComponentFactory().getNodeFactoryService().buildAccumulateNode(context.getNextId(), context.getTupleSource(), context.getObjectSource(), resultAlphaConstraints.toArray(new AlphaNodeFieldConstraint[resultAlphaConstraints.size()]), // source binder
    binder, resultBinder, accumulate, existSubNetwort, context);
    context.setTupleSource(utils.attachNode(context, accNode));
    // source pattern was bound, so nulling context
    context.setObjectSource(null);
    context.setCurrentPatternOffset(currentPatternIndex);
    context.popRuleComponent();
}
Also used : Pattern(org.drools.core.rule.Pattern) BetaConstraints(org.drools.core.common.BetaConstraints) Collect(org.drools.core.rule.Collect) AccumulateNode(org.drools.core.reteoo.AccumulateNode) ArrayList(java.util.ArrayList) TupleStartEqualsConstraint(org.drools.core.common.TupleStartEqualsConstraint) BetaNodeFieldConstraint(org.drools.core.spi.BetaNodeFieldConstraint) SingleAccumulate(org.drools.core.rule.SingleAccumulate) BetaNodeFieldConstraint(org.drools.core.spi.BetaNodeFieldConstraint) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) TupleStartEqualsConstraint(org.drools.core.common.TupleStartEqualsConstraint) SingleAccumulate(org.drools.core.rule.SingleAccumulate) Accumulate(org.drools.core.rule.Accumulate) LeftTupleSource(org.drools.core.reteoo.LeftTupleSource) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) CollectAccumulator(org.drools.core.base.accumulators.CollectAccumulator) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode)

Example 12 with RightInputAdapterNode

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

the class RightInputAdapterNodeVisitor method doVisit.

@Override
protected void doVisit(NetworkNode node, Stack<NetworkNode> nodeStack, StatefulKnowledgeSessionInfo info) {
    RightInputAdapterNode an = (RightInputAdapterNode) node;
    DefaultNodeInfo ni = info.getNodeInfo(node);
    BetaNode betaNode = (BetaNode) an.getObjectSinkPropagator().getSinks()[0];
    Memory childMemory = info.getSession().getNodeMemory(betaNode);
    BetaMemory bm;
    if (betaNode.getType() == NodeTypeEnums.AccumulateNode) {
        bm = ((AccumulateMemory) childMemory).getBetaMemory();
    } else {
        bm = (BetaMemory) childMemory;
    }
    ni.setMemoryEnabled(true);
    ni.setTupleMemorySize(bm.getRightTupleMemory().size());
    ni.setCreatedFactHandles(bm.getRightTupleMemory().size());
}
Also used : BetaNode(org.drools.core.reteoo.BetaNode) Memory(org.drools.core.common.Memory) BetaMemory(org.drools.core.reteoo.BetaMemory) AccumulateMemory(org.drools.core.reteoo.AccumulateNode.AccumulateMemory) BetaMemory(org.drools.core.reteoo.BetaMemory) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode)

Example 13 with RightInputAdapterNode

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

the class AccumulateTest method testAccumulateWithSameSubnetwork.

// (timeout = 10000)
@Test
public void testAccumulateWithSameSubnetwork() throws Exception {
    String rule = "package org.drools.compiler.test;\n" + "import org.drools.compiler.Cheese;\n" + "import org.drools.compiler.Person;\n" + "global java.util.List list; \n" + "rule r1 salience 100 \n" + "    when\n" + "        $person      : Person( name == 'Alice', $likes : likes )\n" + "        $total       : Number() from accumulate( $p : Person(likes != $likes, $l : likes) and $c : Cheese( type == $l ),\n" + "                                                min($c.getPrice()) )\n" + "    then\n" + "        list.add( 'r1' + ':' + $total);\n" + "end\n" + "rule r2 \n" + "    when\n" + "        $person      : Person( name == 'Alice', $likes : likes )\n" + "        $total       : Number() from accumulate( $p : Person(likes != $likes, $l : likes) and $c : Cheese( type == $l ),\n" + "                                                max($c.getPrice()) )\n" + "    then\n" + "        list.add( 'r2' + ':' + $total);\n" + "end\n" + "";
    // read in the source
    KieBase kbase = loadKnowledgeBaseFromString(rule);
    KieSession wm = createKnowledgeSession(kbase);
    List list = new ArrayList();
    wm.setGlobal("list", list);
    // Check the network formation, to ensure the RiaNode is shared.
    ObjectTypeNode cheeseOtn = LinkingTest.getObjectTypeNode(kbase, Cheese.class);
    ObjectSink[] oSinks = cheeseOtn.getObjectSinkPropagator().getSinks();
    assertEquals(1, oSinks.length);
    JoinNode cheeseJoin = (JoinNode) oSinks[0];
    LeftTupleSink[] ltSinks = cheeseJoin.getSinkPropagator().getSinks();
    assertEquals(1, ltSinks.length);
    RightInputAdapterNode rian = (RightInputAdapterNode) ltSinks[0];
    // RiaNode is shared, if this has two outputs
    assertEquals(2, rian.getObjectSinkPropagator().size());
    wm.insert(new Cheese("stilton", 10));
    wm.insert(new Person("Alice", "brie"));
    wm.insert(new Person("Bob", "stilton"));
    wm.fireAllRules();
    assertEquals(2, list.size());
    assertEquals("r1:10", list.get(0));
    assertEquals("r2:10", list.get(1));
}
Also used : JoinNode(org.drools.core.reteoo.JoinNode) ArrayList(java.util.ArrayList) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) LeftTupleSink(org.drools.core.reteoo.LeftTupleSink) Cheese(org.drools.compiler.Cheese) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) ObjectSink(org.drools.core.reteoo.ObjectSink) Person(org.drools.compiler.Person) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) Test(org.junit.Test)

Example 14 with RightInputAdapterNode

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

the class LinkingTest method testNestedSubNetworkMasks.

@Test
public void testNestedSubNetworkMasks() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "import " + F.class.getCanonicalName() + "\n";
    str += "import " + G.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";
    str += "rule rule1 when \n";
    str += "   A() \n";
    str += "   B() \n";
    str += "   exists( C() and D() and exists( E() and F() ) ) \n";
    str += "   G() \n";
    str += "then \n";
    str += "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ObjectTypeNode node = getObjectTypeNode(kbase, A.class);
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) node.getObjectSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getSinks()[0];
    ExistsNode exists1n = (ExistsNode) bNode.getSinkPropagator().getSinks()[1];
    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[0];
    JoinNode dNode = (JoinNode) cNode.getSinkPropagator().getSinks()[0];
    ExistsNode exists2n = (ExistsNode) dNode.getSinkPropagator().getSinks()[1];
    JoinNode eNode = (JoinNode) dNode.getSinkPropagator().getSinks()[0];
    JoinNode fNode = (JoinNode) eNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode2 = (RightInputAdapterNode) fNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode1 = (RightInputAdapterNode) exists2n.getSinkPropagator().getSinks()[0];
    JoinNode gNode = (JoinNode) exists1n.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = (RuleTerminalNode) gNode.getSinkPropagator().getSinks()[0];
    wm.insert(new A());
    wm.insert(new B());
    wm.insert(new C());
    wm.insert(new D());
    wm.insert(new G());
    wm.flushPropagations();
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    BetaMemory bMem = (BetaMemory) wm.getNodeMemory(bNode);
    BetaMemory exists1Mem = (BetaMemory) wm.getNodeMemory(exists1n);
    BetaMemory cMem = (BetaMemory) wm.getNodeMemory(cNode);
    BetaMemory dMem = (BetaMemory) wm.getNodeMemory(dNode);
    BetaMemory exists2Mem = (BetaMemory) wm.getNodeMemory(exists2n);
    BetaMemory eMem = (BetaMemory) wm.getNodeMemory(eNode);
    BetaMemory fMem = (BetaMemory) wm.getNodeMemory(fNode);
    BetaMemory gMem = (BetaMemory) wm.getNodeMemory(gNode);
    RightInputAdapterNode.RiaNodeMemory riaMem1 = (RightInputAdapterNode.RiaNodeMemory) wm.getNodeMemory(riaNode1);
    RightInputAdapterNode.RiaNodeMemory riaMem2 = (RightInputAdapterNode.RiaNodeMemory) wm.getNodeMemory(riaNode2);
    PathMemory rs = (PathMemory) wm.getNodeMemory(rtn);
    // E and F are not inserted yet, so rule is unlinked
    assertFalse(rs.isRuleLinked());
    // ---
    // assert a and b in same segment
    assertSame(liaMem.getSegmentMemory(), bMem.getSegmentMemory());
    // exists1 and b not in same segment
    assertNotSame(bMem.getSegmentMemory(), exists1Mem.getSegmentMemory());
    // exists1 and b are in same segment
    assertSame(exists1Mem.getSegmentMemory(), gMem.getSegmentMemory());
    // check segment masks
    assertEquals(2, rs.getSegmentMemories().length);
    assertEquals(3, rs.getAllLinkedMaskTest());
    assertEquals(1, rs.getLinkedSegmentMask());
    assertEquals(3, liaMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(1, liaMem.getNodePosMaskBit());
    assertEquals(2, bMem.getNodePosMaskBit());
    assertEquals(3, exists1Mem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(1, exists1Mem.getNodePosMaskBit());
    assertEquals(2, gMem.getNodePosMaskBit());
    // assert c, d are in the same segment, and that this is the only segment in ria1 memory
    assertSame(dMem.getSegmentMemory(), cMem.getSegmentMemory());
    // assert d and exists are not in the same segment
    assertNotSame(exists2Mem.getSegmentMemory(), dMem.getSegmentMemory());
    assertEquals(3, riaMem1.getRiaPathMemory().getSegmentMemories().length);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem1.getRiaPathMemory().getSegmentMemories()[0]);
    assertEquals(dMem.getSegmentMemory(), riaMem1.getRiaPathMemory().getSegmentMemories()[1]);
    assertEquals(1, dMem.getSegmentMemory().getPathMemories().size());
    assertSame(riaMem1.getRiaPathMemory(), cMem.getSegmentMemory().getPathMemories().get(0));
    assertEquals(3, cMem.getSegmentMemory().getAllLinkedMaskTest());
    // E and F is not yet inserted, so bit is not set
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(1, cMem.getNodePosMaskBit());
    assertEquals(2, dMem.getNodePosMaskBit());
    assertEquals(0, exists2Mem.getNodePosMaskBit());
    // insert to lazy initialize exists2Mem segment
    FactHandle fhE1 = wm.insert(new E());
    FactHandle fhF1 = wm.insert(new F());
    wm.flushPropagations();
    assertEquals(1, exists2Mem.getNodePosMaskBit());
    // only cares that the segment for c, E and exists1 are set, ignores the outer first segment
    assertEquals(6, riaMem1.getRiaPathMemory().getAllLinkedMaskTest());
    // E and F are inerted, so 6
    assertEquals(6, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    wm.delete(fhE1);
    wm.delete(fhF1);
    wm.flushPropagations();
    // E deleted
    assertEquals(2, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    // assert e, f are in the same segment, and that this is the only segment in ria2 memory
    // subnetworks are recursively created, so segment already exists
    assertNotNull(null, eMem.getSegmentMemory());
    assertSame(fMem.getSegmentMemory(), eMem.getSegmentMemory());
    assertEquals(3, riaMem2.getRiaPathMemory().getSegmentMemories().length);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem2.getRiaPathMemory().getSegmentMemories()[0]);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem2.getRiaPathMemory().getSegmentMemories()[1]);
    assertEquals(fMem.getSegmentMemory(), riaMem2.getRiaPathMemory().getSegmentMemories()[2]);
    assertSame(riaMem2.getRiaPathMemory(), eMem.getSegmentMemory().getPathMemories().get(0));
    assertEquals(3, eMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(0, eMem.getSegmentMemory().getLinkedNodeMask());
    // only cares that the segment for e and f set, ignores the outer two segment
    assertEquals(4, riaMem2.getRiaPathMemory().getAllLinkedMaskTest());
    // E and F is not yet inserted, so bit is not set
    assertEquals(0, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
    fhE1 = wm.insert(new E());
    wm.insert(new F());
    wm.flushPropagations();
    // E and F are now inserted yet, so rule is linked
    assertTrue(rs.isRuleLinked());
    assertEquals(3, rs.getAllLinkedMaskTest());
    assertEquals(3, rs.getLinkedSegmentMask());
    // retest bits
    assertEquals(3, cMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(6, riaMem1.getRiaPathMemory().getAllLinkedMaskTest());
    assertEquals(6, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    assertEquals(3, eMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(3, eMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(4, riaMem2.getRiaPathMemory().getAllLinkedMaskTest());
    assertEquals(4, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
    wm.delete(fhE1);
    wm.flushPropagations();
    // retest bits
    assertFalse(rs.isRuleLinked());
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(2, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    assertEquals(2, eMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(0, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) JoinNode(org.drools.core.reteoo.JoinNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) BetaMemory(org.drools.core.reteoo.BetaMemory) ExistsNode(org.drools.core.reteoo.ExistsNode) LiaNodeMemory(org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) PathMemory(org.drools.core.reteoo.PathMemory) Test(org.junit.Test)

Example 15 with RightInputAdapterNode

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

the class BackwardChainingTest method testSubNetworksAndQueries.

@Test(timeout = 10000)
public void testSubNetworksAndQueries() throws Exception {
    String str = "" + "package org.drools.compiler.test  \n" + "import java.util.List\n" + "import java.util.ArrayList\n" + "import java.util.Map\n" + "import java.util.HashMap\n" + "global List list\n" + "dialect \"mvel\"\n" + "\n" + "declare Location\n" + "    thing : String \n" + "    location : String \n" + "end" + "\n" + "declare Edible\n" + "   thing : String\n" + "end" + "\n" + "query whereFood( String x, String y ) \n" + "    Location(x, y;) Edible(x;) \n" + "end\n" + "\n" + "query look(String place, List food ) \n" + "    $s : String() // just here to give a OTN lookup point\n" + "    food := List() from accumulate( whereFood(thing, place;) ," + "                                    collectList( thing ) )\n" + "    exists( whereFood(thing, place;) )\n" + "    not( whereFood(thing, place;) and\n " + "         String( this == $s ) from thing )\n" + "end\n" + "\n" + "rule init when\n" + "then\n" + "        \n" + "        insert( new Location(\"apple\", \"kitchen\") );\n" + "        insert( new Location(\"crackers\", \"kitchen\") );\n" + "        insert( new Location(\"broccoli\", \"kitchen\") );\n" + "        insert( new Location(\"computer\", \"office\") );\n" + "        insert( new Edible(\"apple\") );\n" + "        insert( new Edible(\"crackers\") );\n" + "end\n" + "";
    logger.debug(str);
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
    // Get the accumulate node, so we can test it's memory later
    // now check beta memory was correctly cleared
    List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == String.class) {
            node = n;
            break;
        }
    }
    BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
    AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
    ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
    FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
    NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
    KieSession ksession = createKnowledgeSession(kbase);
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) ksession);
    AccumulateMemory accMemory = (AccumulateMemory) wm.getNodeMemory(accNode);
    BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
    FromMemory fromMemory = (FromMemory) wm.getNodeMemory(fromNode);
    BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    ksession.setGlobal("list", list);
    FactHandle fh = ksession.insert("bread");
    ksession.fireAllRules();
    final List food = new ArrayList();
    QueryResults results = null;
    // Execute normal query and check no subnetwork tuples are left behind
    results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
    assertEquals(1, results.size());
    for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
        food.addAll((Collection) row.get("food"));
        logger.debug(row.get("food").toString());
    }
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(0, existsMemory.getRightTupleMemory().size());
    assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    // Now execute an open query and ensure the memory is left populated
    food.clear();
    final List foodUpdated = new ArrayList();
    LiveQuery query = ksession.openLiveQuery("look", new Object[] { "kitchen", Variable.v }, new ViewChangedEventListener() {

        public void rowUpdated(Row row) {
            foodUpdated.addAll((Collection) row.get("food"));
        }

        public void rowDeleted(Row row) {
        }

        public void rowInserted(Row row) {
            food.addAll((Collection) row.get("food"));
        }
    });
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    food.clear();
    // Now try again, make sure it only delete's it's own tuples
    results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
    assertEquals(1, results.size());
    for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
        food.addAll((Collection) row.get("food"));
        logger.debug(row.get("food").toString());
    }
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    food.clear();
    // do an update and check it's  still memory size 2
    // however this time the food should be empty, as 'crackers' now blocks the not.
    ksession.update(fh, "crackers");
    ksession.fireAllRules();
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(1, notMemory.getRightTupleMemory().size());
    assertEquals(0, foodUpdated.size());
    // do an update and check it's  still memory size 2
    // this time
    ksession.update(fh, "oranges");
    ksession.fireAllRules();
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    // Close the open
    query.close();
    assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(0, existsMemory.getRightTupleMemory().size());
    assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
}
Also used : AccumulateMemory(org.drools.core.reteoo.AccumulateNode.AccumulateMemory) NotNode(org.drools.core.reteoo.NotNode) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) AccumulateNode(org.drools.core.reteoo.AccumulateNode) QueryElementNode(org.drools.core.reteoo.QueryElementNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ArrayList(java.util.ArrayList) FromNode(org.drools.core.reteoo.FromNode) ExistsNode(org.drools.core.reteoo.ExistsNode) LiveQuery(org.kie.api.runtime.rule.LiveQuery) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) BetaNode(org.drools.core.reteoo.BetaNode) BetaMemory(org.drools.core.reteoo.BetaMemory) QueryResults(org.kie.api.runtime.rule.QueryResults) FromMemory(org.drools.core.reteoo.FromNode.FromMemory) ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) Collection(java.util.Collection) Row(org.kie.api.runtime.rule.Row) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

RightInputAdapterNode (org.drools.core.reteoo.RightInputAdapterNode)22 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)10 BetaMemory (org.drools.core.reteoo.BetaMemory)10 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)10 Test (org.junit.Test)10 LeftInputAdapterNode (org.drools.core.reteoo.LeftInputAdapterNode)8 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)8 BetaNode (org.drools.core.reteoo.BetaNode)7 JoinNode (org.drools.core.reteoo.JoinNode)7 LeftTupleSource (org.drools.core.reteoo.LeftTupleSource)7 LiaNodeMemory (org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory)6 PathMemory (org.drools.core.reteoo.PathMemory)6 KieBase (org.kie.api.KieBase)6 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)5 AccumulateMemory (org.drools.core.reteoo.AccumulateNode.AccumulateMemory)5 ExistsNode (org.drools.core.reteoo.ExistsNode)5 ObjectSink (org.drools.core.reteoo.ObjectSink)5 SegmentMemory (org.drools.core.reteoo.SegmentMemory)5 ArrayList (java.util.ArrayList)4 Memory (org.drools.core.common.Memory)4