Search in sources :

Example 1 with LiveQuery

use of org.kie.api.runtime.rule.LiveQuery in project drools by kiegroup.

the class QueryTest method testOpenQueryNoParams.

@Test
public void testOpenQueryNoParams() throws Exception {
    // RHDM-717
    String str = "";
    str += "package org.drools.mvel.compiler.test  \n";
    str += "import org.drools.mvel.compiler.Cheese \n";
    str += "query cheeses \n";
    str += "    stilton : Cheese(type == 'stilton') \n";
    str += "    cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
    str += "end\n";
    KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
    KieSession ksession = kbase.newKieSession();
    Cheese stilton1 = new Cheese("stilton", 1);
    Cheese cheddar1 = new Cheese("cheddar", 1);
    Cheese stilton2 = new Cheese("stilton", 2);
    Cheese cheddar2 = new Cheese("cheddar", 2);
    Cheese stilton3 = new Cheese("stilton", 3);
    Cheese cheddar3 = new Cheese("cheddar", 3);
    FactHandle s1Fh = ksession.insert(stilton1);
    ksession.insert(stilton2);
    ksession.insert(stilton3);
    ksession.insert(cheddar1);
    ksession.insert(cheddar2);
    FactHandle c3Fh = ksession.insert(cheddar3);
    final List<Object[]> updated = new ArrayList<Object[]>();
    final List<Object[]> removed = new ArrayList<Object[]>();
    final List<Object[]> added = new ArrayList<Object[]>();
    ViewChangedEventListener listener = new ViewChangedEventListener() {

        public void rowUpdated(Row row) {
            Object[] array = new Object[2];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            updated.add(array);
        }

        public void rowDeleted(Row row) {
            Object[] array = new Object[2];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            removed.add(array);
        }

        public void rowInserted(Row row) {
            Object[] array = new Object[2];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            added.add(array);
        }
    };
    // Open the LiveQuery
    LiveQuery query = ksession.openLiveQuery("cheeses", null, listener);
    ksession.fireAllRules();
    // Assert that on opening we have three rows added
    assertEquals(3, added.size());
    assertEquals(0, removed.size());
    assertEquals(0, updated.size());
    // Do an update that causes a match to become untrue, thus triggering a removed
    cheddar3.setPrice(4);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(3, added.size());
    assertEquals(1, removed.size());
    assertEquals(0, updated.size());
    // Now make that partial true again, and thus another added
    cheddar3.setPrice(3);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(1, removed.size());
    assertEquals(0, updated.size());
    // check a standard update
    cheddar3.setOldPrice(0);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(1, removed.size());
    assertEquals(1, updated.size());
    // Check a standard retract
    ksession.retract(s1Fh);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(2, removed.size());
    assertEquals(1, updated.size());
    // Close the query, we should get removed events for each row
    query.close();
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(4, removed.size());
    assertEquals(1, updated.size());
    // Check that updates no longer have any impact.
    ksession.update(c3Fh, cheddar3);
    assertEquals(4, added.size());
    assertEquals(4, removed.size());
    assertEquals(1, updated.size());
}
Also used : ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Cheese(org.drools.mvel.compiler.Cheese) DomainObject(org.drools.mvel.compiler.DomainObject) InsertedObject(org.drools.mvel.compiler.InsertedObject) Row(org.kie.api.runtime.rule.Row) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) LiveQuery(org.kie.api.runtime.rule.LiveQuery) Test(org.junit.Test)

Example 2 with LiveQuery

use of org.kie.api.runtime.rule.LiveQuery in project drools by kiegroup.

the class DroolsEventListTest method testOpenQuery.

@Test
public void testOpenQuery() throws Exception {
    String str = "";
    str += "package org.kie.test  \n";
    str += "import org.drools.compiler.Cheese \n";
    str += "query cheeses(String $type1, String $type2) \n";
    str += "    stilton : Cheese(type == $type1, $price : price) \n";
    str += "    cheddar : Cheese(type == $type2, price == stilton.price) \n";
    str += "end\n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession ksession = createKnowledgeSession(kbase);
    Cheese stilton1 = new Cheese("stilton", 1);
    Cheese cheddar1 = new Cheese("cheddar", 1);
    Cheese stilton2 = new Cheese("stilton", 2);
    Cheese cheddar2 = new Cheese("cheddar", 2);
    Cheese stilton3 = new Cheese("stilton", 3);
    Cheese cheddar3 = new Cheese("cheddar", 3);
    FactHandle s1Fh = ksession.insert(stilton1);
    FactHandle s2Fh = ksession.insert(stilton2);
    FactHandle s3Fh = ksession.insert(stilton3);
    FactHandle c1Fh = ksession.insert(cheddar1);
    FactHandle c2Fh = ksession.insert(cheddar2);
    FactHandle c3Fh = ksession.insert(cheddar3);
    DroolsEventList list = new DroolsEventList();
    // Open the LiveQuery
    LiveQuery query = ksession.openLiveQuery("cheeses", new Object[] { "cheddar", "stilton" }, list);
    SortedList<Row> sorted = new SortedList<Row>(list, new Comparator<Row>() {

        public int compare(Row r1, Row r2) {
            Cheese c1 = (Cheese) r1.get("stilton");
            Cheese c2 = (Cheese) r2.get("stilton");
            return c1.getPrice() - c2.getPrice();
        }
    });
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // alter the price to remove the last row
    stilton3.setPrice(4);
    ksession.update(s3Fh, stilton3);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // alter the price to put the last row back in
    stilton3.setPrice(3);
    ksession.update(s3Fh, stilton3);
    ksession.fireAllRules();
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // alter the price to remove the middle row
    stilton2.setPrice(4);
    ksession.update(s2Fh, stilton2);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // alter the price to add the previous middle rows to the end
    cheddar2.setPrice(4);
    ksession.update(c2Fh, cheddar2);
    ksession.fireAllRules();
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(4, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // Check a standard retract
    ksession.retract(s1Fh);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(3, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(4, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // Close the query, we should get removed events for each row
    query.close();
    assertEquals(0, sorted.size());
}
Also used : KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) FactHandle(org.kie.api.runtime.rule.FactHandle) SortedList(ca.odell.glazedlists.SortedList) KieSession(org.kie.api.runtime.KieSession) Cheese(org.drools.compiler.Cheese) Row(org.kie.api.runtime.rule.Row) LiveQuery(org.kie.api.runtime.rule.LiveQuery) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 3 with LiveQuery

use of org.kie.api.runtime.rule.LiveQuery in project drools by kiegroup.

the class QueryTest method testOpenQuery.

@Test
public void testOpenQuery() throws Exception {
    String str = "";
    str += "package org.drools.compiler.test  \n";
    str += "import org.drools.compiler.Cheese \n";
    str += "query cheeses(String $type1, String $type2) \n";
    str += "    stilton : Cheese(type == $type1, $sprice : price) \n";
    str += "    cheddar : Cheese(type == $type2, $cprice : price == stilton.price) \n";
    str += "end\n";
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
    KieSession ksession = createKieSession(kbase);
    Cheese stilton1 = new Cheese("stilton", 1);
    Cheese cheddar1 = new Cheese("cheddar", 1);
    Cheese stilton2 = new Cheese("stilton", 2);
    Cheese cheddar2 = new Cheese("cheddar", 2);
    Cheese stilton3 = new Cheese("stilton", 3);
    Cheese cheddar3 = new Cheese("cheddar", 3);
    FactHandle s1Fh = ksession.insert(stilton1);
    ksession.insert(stilton2);
    ksession.insert(stilton3);
    ksession.insert(cheddar1);
    ksession.insert(cheddar2);
    FactHandle c3Fh = ksession.insert(cheddar3);
    final List<Object[]> updated = new ArrayList<Object[]>();
    final List<Object[]> removed = new ArrayList<Object[]>();
    final List<Object[]> added = new ArrayList<Object[]>();
    ViewChangedEventListener listener = new ViewChangedEventListener() {

        public void rowUpdated(Row row) {
            Object[] array = new Object[6];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            array[2] = row.get("$sprice");
            array[3] = row.get("$cprice");
            array[4] = row.get("$type1");
            array[5] = row.get("$type2");
            updated.add(array);
        }

        public void rowDeleted(Row row) {
            Object[] array = new Object[6];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            array[2] = row.get("$sprice");
            array[3] = row.get("$cprice");
            array[4] = row.get("$type1");
            array[5] = row.get("$type2");
            removed.add(array);
        }

        public void rowInserted(Row row) {
            Object[] array = new Object[6];
            array[0] = row.get("stilton");
            array[1] = row.get("cheddar");
            array[2] = row.get("$sprice");
            array[3] = row.get("$cprice");
            array[4] = row.get("$type1");
            array[5] = row.get("$type2");
            added.add(array);
        }
    };
    // Open the LiveQuery
    LiveQuery query = ksession.openLiveQuery("cheeses", new Object[] { "stilton", "cheddar" }, listener);
    ksession.fireAllRules();
    // Assert that on opening we have three rows added
    assertEquals(3, added.size());
    assertEquals(0, removed.size());
    assertEquals(0, updated.size());
    // Assert that the identifiers where retrievable
    assertSame(stilton1, added.get(2)[0]);
    assertSame(cheddar1, added.get(2)[1]);
    assertEquals(1, added.get(2)[2]);
    assertEquals(1, added.get(2)[3]);
    assertEquals("stilton", added.get(2)[4]);
    assertEquals("cheddar", added.get(2)[5]);
    // And that we have correct values from those rows
    assertEquals(3, added.get(0)[3]);
    assertEquals(2, added.get(1)[3]);
    assertEquals(1, added.get(2)[3]);
    // Do an update that causes a match to become untrue, thus triggering a removed
    cheddar3.setPrice(4);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(3, added.size());
    assertEquals(1, removed.size());
    assertEquals(0, updated.size());
    assertEquals(4, removed.get(0)[3]);
    // Now make that partial true again, and thus another added
    cheddar3.setPrice(3);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(1, removed.size());
    assertEquals(0, updated.size());
    assertEquals(3, added.get(3)[3]);
    // check a standard update
    cheddar3.setOldPrice(0);
    ksession.update(c3Fh, cheddar3);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(1, removed.size());
    assertEquals(1, updated.size());
    assertEquals(3, updated.get(0)[3]);
    // Check a standard retract
    ksession.retract(s1Fh);
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(2, removed.size());
    assertEquals(1, updated.size());
    assertEquals(1, removed.get(1)[3]);
    // Close the query, we should get removed events for each row
    query.close();
    ksession.fireAllRules();
    assertEquals(4, added.size());
    assertEquals(4, removed.size());
    assertEquals(1, updated.size());
    assertEquals(2, removed.get(3)[3]);
    assertEquals(3, removed.get(2)[3]);
    // Check that updates no longer have any impact.
    ksession.update(c3Fh, cheddar3);
    assertEquals(4, added.size());
    assertEquals(4, removed.size());
    assertEquals(1, updated.size());
}
Also used : ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Cheese(org.drools.compiler.Cheese) DomainObject(org.drools.compiler.DomainObject) InsertedObject(org.drools.compiler.InsertedObject) FlatQueryResultRow(org.drools.core.runtime.rule.impl.FlatQueryResultRow) Row(org.kie.api.runtime.rule.Row) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) LiveQuery(org.kie.api.runtime.rule.LiveQuery) Test(org.junit.Test)

Example 4 with LiveQuery

use of org.kie.api.runtime.rule.LiveQuery in project drools by kiegroup.

the class BackwardChainingTest method testSubNetworksAndQueries.

@Test(timeout = 10000)
public void testSubNetworksAndQueries() {
    final String drl = "" + "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" + "";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
    // Get the accumulate node, so we can test it's memory later
    // now check beta memory was correctly cleared
    final List<ObjectTypeNode> nodes = ((RuleBase) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (final ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == String.class) {
            node = n;
            break;
        }
    }
    assertNotNull(node);
    final BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
    final AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
    final ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
    final FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
    final NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
    final KieSession ksession = kbase.newKieSession();
    try {
        final InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) ksession);
        final AccumulateNode.AccumulateMemory accMemory = (AccumulateNode.AccumulateMemory) wm.getNodeMemory(accNode);
        final BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
        final FromNode.FromMemory fromMemory = (FromNode.FromMemory) wm.getNodeMemory(fromNode);
        final BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
        final List<Map<String, Object>> list = new ArrayList<>();
        ksession.setGlobal("list", list);
        final FactHandle fh = ksession.insert("bread");
        ksession.fireAllRules();
        final List food = new ArrayList();
        // Execute normal query and check no subnetwork tuples are left behind
        QueryResults results = ksession.getQueryResults("look", "kitchen", Variable.v);
        assertEquals(1, results.size());
        for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
            food.addAll((Collection) row.get("food"));
        }
        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();
        final LiveQuery query = ksession.openLiveQuery("look", new Object[] { "kitchen", Variable.v }, new ViewChangedEventListener() {

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

            public void rowDeleted(final Row row) {
            }

            public void rowInserted(final Row row) {
                food.addAll((Collection) row.get("food"));
            }
        });
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, 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", "kitchen", Variable.v);
        assertEquals(1, results.size());
        for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
            food.addAll((Collection) row.get("food"));
        }
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, 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(1, existsMemory.getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, 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(1, existsMemory.getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, 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());
    } finally {
        ksession.dispose();
    }
}
Also used : 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) 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)

Example 5 with LiveQuery

use of org.kie.api.runtime.rule.LiveQuery in project drools by kiegroup.

the class DroolsEventListTest method testOpenQuery.

@Test
public void testOpenQuery() throws Exception {
    String str = "";
    str += "package org.kie.test  \n";
    str += "import " + Cheese.class.getCanonicalName() + "\n";
    str += "query cheeses(String $type1, String $type2) \n";
    str += "    stilton : Cheese(type == $type1, $price : price) \n";
    str += "    cheddar : Cheese(type == $type2, price == stilton.price) \n";
    str += "end\n";
    KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
    KieSession ksession = kbase.newKieSession();
    Cheese stilton1 = new Cheese("stilton", 1);
    Cheese cheddar1 = new Cheese("cheddar", 1);
    Cheese stilton2 = new Cheese("stilton", 2);
    Cheese cheddar2 = new Cheese("cheddar", 2);
    Cheese stilton3 = new Cheese("stilton", 3);
    Cheese cheddar3 = new Cheese("cheddar", 3);
    FactHandle s1Fh = ksession.insert(stilton1);
    FactHandle s2Fh = ksession.insert(stilton2);
    FactHandle s3Fh = ksession.insert(stilton3);
    FactHandle c1Fh = ksession.insert(cheddar1);
    FactHandle c2Fh = ksession.insert(cheddar2);
    FactHandle c3Fh = ksession.insert(cheddar3);
    DroolsEventList list = new DroolsEventList();
    // Open the LiveQuery
    LiveQuery query = ksession.openLiveQuery("cheeses", new Object[] { "cheddar", "stilton" }, list);
    SortedList<Row> sorted = new SortedList<Row>(list, new Comparator<Row>() {

        public int compare(Row r1, Row r2) {
            Cheese c1 = (Cheese) r1.get("stilton");
            Cheese c2 = (Cheese) r2.get("stilton");
            return c1.getPrice() - c2.getPrice();
        }
    });
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // alter the price to remove the last row
    stilton3.setPrice(4);
    ksession.update(s3Fh, stilton3);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // alter the price to put the last row back in
    stilton3.setPrice(3);
    ksession.update(s3Fh, stilton3);
    ksession.fireAllRules();
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(2, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // alter the price to remove the middle row
    stilton2.setPrice(4);
    ksession.update(s2Fh, stilton2);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // alter the price to add the previous middle rows to the end
    cheddar2.setPrice(4);
    ksession.update(c2Fh, cheddar2);
    ksession.fireAllRules();
    assertEquals(3, sorted.size());
    assertEquals(1, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(3, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    assertEquals(4, ((Cheese) sorted.get(2).get("stilton")).getPrice());
    // Check a standard retract
    ksession.retract(s1Fh);
    ksession.fireAllRules();
    assertEquals(2, sorted.size());
    assertEquals(3, ((Cheese) sorted.get(0).get("stilton")).getPrice());
    assertEquals(4, ((Cheese) sorted.get(1).get("stilton")).getPrice());
    // Close the query, we should get removed events for each row
    query.close();
    assertEquals(0, sorted.size());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) KieBase(org.kie.api.KieBase) SortedList(ca.odell.glazedlists.SortedList) Cheese(org.drools.mvel.compiler.Cheese) KieSession(org.kie.api.runtime.KieSession) Row(org.kie.api.runtime.rule.Row) LiveQuery(org.kie.api.runtime.rule.LiveQuery) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)6 KieSession (org.kie.api.runtime.KieSession)6 FactHandle (org.kie.api.runtime.rule.FactHandle)6 LiveQuery (org.kie.api.runtime.rule.LiveQuery)6 Row (org.kie.api.runtime.rule.Row)6 KieBase (org.kie.api.KieBase)5 ArrayList (java.util.ArrayList)4 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 QueryResultsRow (org.kie.api.runtime.rule.QueryResultsRow)4 ViewChangedEventListener (org.kie.api.runtime.rule.ViewChangedEventListener)4 Cheese (org.drools.mvel.compiler.Cheese)3 SortedList (ca.odell.glazedlists.SortedList)2 Cheese (org.drools.compiler.Cheese)2 DomainObject (org.drools.mvel.compiler.DomainObject)2 InsertedObject (org.drools.mvel.compiler.InsertedObject)2 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 DomainObject (org.drools.compiler.DomainObject)1