Java Code Examples for org.kie.api.runtime.KieSession#delete()

The following examples show how to use org.kie.api.runtime.KieSession#delete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SegmentMemoryPrototypeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void checkKieSession(KieSession ksession) {
    final List<String> events = new ArrayList<String>();

    ksession.setGlobal("events", events);

    // phase 1
    Room room1 = new Room("Room 1");
    ksession.insert(room1);
    FactHandle fireFact1 = ksession.insert(new Fire(room1));
    ksession.fireAllRules();
    assertEquals(1, events.size());

    // phase 2
    Sprinkler sprinkler1 = new Sprinkler(room1);
    ksession.insert(sprinkler1);
    ksession.fireAllRules();
    assertEquals(2, events.size());

    // phase 3
    ksession.delete(fireFact1);
    ksession.fireAllRules();
    assertEquals(5, events.size());
}
 
Example 2
Source File: JTMSTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimeJustificationWithEqualityMode() {
    String droolsSource =
            "package org.drools.tms.test; \n" +
            "declare Bar end \n" +
            "" +
            "declare Holder x : Bar end \n" +
            "" +
            "" +
            "rule Init \n" +
            "when \n" +
            "then \n" +
            "   insert( new Holder( new Bar() ) ); \n" +
            "end \n" +

            "rule Justify \n" +
            "when \n" +
            " $s : Integer() \n" +
            " $h : Holder( $b : x ) \n" +
            "then \n" +
            " insertLogical( $b ); \n" +
            "end \n" +

            "rule React \n" +
            "when \n" +
            " $b : Bar(  ) \n" +
            "then \n" +
            " System.out.println( $b );  \n" +
            "end \n" ;

    KieSession session = getSessionFromString( droolsSource );

    FactHandle handle1 = session.insert( 10 );
    FactHandle handle2 = session.insert( 20 );

    assertEquals( 4, session.fireAllRules() );

    session.delete( handle1 );
    assertEquals( 0, session.fireAllRules() );
}
 
Example 3
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
//@Disabled("in Java 8, the byte[] generated by serialization are not the same and requires investigation")
public void testLogicalInsertionsWithModify() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsWithUpdate.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final Person p = new Person( "person" );
        p.setAge( 2 );
        FactHandle h = ksession.insert( p );
        assertEquals(1, ksession.getObjects().size());

        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, false);
        assertEquals(2, ksession.getObjects().size());

        Collection l = ksession.getObjects( new ClassObjectFilter( CheeseEqual.class ) );
        assertEquals(1, l.size());
        assertEquals(2, ((CheeseEqual) l.iterator().next()).getPrice());

        h = getFactHandle( h, ksession );
        ksession.delete( h );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, false);
        assertEquals(0, ksession.getObjects().size());

        TruthMaintenanceSystem tms =  ((NamedEntryPoint)ksession.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId()) ).getTruthMaintenanceSystem();

        final java.lang.reflect.Field field = tms.getClass().getDeclaredField( "equalityKeyMap" );
        field.setAccessible( true );
        final ObjectHashMap m = (ObjectHashMap) field.get( tms );
        field.setAccessible( false );
        assertEquals(0, m.size(), "assertMap should be empty");
    } finally {
        ksession.dispose();
    }
}
 
Example 4
Source File: MarshallerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedMarshallerTest
public void testSubnetwork(Environment env) throws Exception {
    final String str =
            "rule R1 when\n" +
                    "    String()\n" +
                    "    Long()\n" +
                    "    not( Long() and Integer() )\n" +
                    "then end\n";

    KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL)
            .build(EqualityBehaviorOption.EQUALITY);
    KieSession ksession = null;

    try {
        ksession = kbase.newKieSession(null, env);

        ksession.insert("Luca");
        ksession.insert(2L);
        ksession.insert(10);

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);

        assertEquals(0, ksession.fireAllRules());

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);

        ksession.delete(ksession.getFactHandle(10));

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);

        assertEquals(1, ksession.fireAllRules());
    } finally {
        if (ksession != null) {
            ksession.dispose();
        }
    }
}
 
Example 5
Source File: BasicConcurrentInsertionsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Callable<Boolean> getTask(
        final int objectCount,
        final KieSession ksession,
        final boolean disposeSession,
        final boolean updateFacts) {
    return () -> {
        try {
            for (int j = 0; j < 10; j++) {
                FactHandle[] facts = new FactHandle[objectCount];
                for (int i = 0; i < objectCount; i++) {
                    facts[i] = ksession.insert(new Bean(i));
                }
                if (updateFacts) {
                    for (int i = 0; i < objectCount; i++) {
                        ksession.update(facts[i], new Bean(-i));
                    }
                }
                for (FactHandle fact : facts) {
                    ksession.delete(fact);
                }
                ksession.fireAllRules();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (disposeSession) {
                ksession.dispose();
            }
        }
    };
}
 
Example 6
Source File: RuleRuntimeEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventModel() throws Exception {
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_EventModel.drl"));
    final KieSession wm = createKnowledgeSession(kbase);

    final RuleRuntimeEventListener wmel = mock(RuleRuntimeEventListener.class);
    wm.addEventListener(wmel);

    final Cheese stilton = new Cheese("stilton", 15);

    final FactHandle stiltonHandle = wm.insert(stilton);

    final ArgumentCaptor<ObjectInsertedEvent> oic = ArgumentCaptor.forClass(org.kie.api.event.rule.ObjectInsertedEvent.class);
    verify(wmel).objectInserted(oic.capture());
    assertSame(stiltonHandle, oic.getValue().getFactHandle());

    wm.update(stiltonHandle, stilton);
    final ArgumentCaptor<org.kie.api.event.rule.ObjectUpdatedEvent> ouc = ArgumentCaptor.forClass(org.kie.api.event.rule.ObjectUpdatedEvent.class);
    verify(wmel).objectUpdated(ouc.capture());
    assertSame(stiltonHandle, ouc.getValue().getFactHandle());

    wm.delete(stiltonHandle);
    final ArgumentCaptor<ObjectDeletedEvent> orc = ArgumentCaptor.forClass(ObjectDeletedEvent.class);
    verify(wmel).objectDeleted(orc.capture());
    assertSame(stiltonHandle, orc.getValue().getFactHandle());

}
 
Example 7
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithBreakingBranch() throws Exception {
    // DROOLS-1068
    String drl =
            "global java.util.List list;\n" +
            "rule R when\n" +
            "  Integer()\n" +
            "  if (true) break[branch]\n" +
            "  not Integer()\n" +
            "then\n" +
            "  list.add(\"main\");\n" +
            "then[branch]\n" +
            "  list.add(\"branch\");\n" +
            "end\n";

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build()
                                         .newKieSession();

    List<String> list = new ArrayList<String>();
    ksession.setGlobal( "list", list );

    FactHandle fh = ksession.insert(1);
    ksession.fireAllRules();
    ksession.delete(fh);
    ksession.fireAllRules();

    assertEquals( 1, list.size() );
    assertEquals( "branch", list.get( 0 ) );
}
 
Example 8
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryInSubnetwork() {
    // DROOLS-1386
    String str = "query myquery(Integer $i)\n" +
                 "   $i := Integer()\n" +
                 "end\n" +
                 "\n" +
                 "rule R when\n" +
                 "   String()\n" +
                 "   accumulate (myquery($i;);\n" +
                 "      $result_count : count(1)\n" +
                 "   )\n" +
                 "   eval($result_count > 0)\n" +
                 "then\n" +
                 "end\n\n";

    KieSession ksession = new KieHelper().addContent( str, ResourceType.DRL ).build().newKieSession();

    FactHandle iFH = ksession.insert( 1 );
    FactHandle sFH = ksession.insert( "" );

    ksession.fireAllRules();

    ksession.update( iFH, 1 );
    ksession.delete( sFH );

    ksession.fireAllRules();
}
 
Example 9
Source File: MemoryLeakTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStagedLeftTupleLeak() throws Exception {
    // BZ-1058874
    String str =
            "rule R1 when\n" +
            "    String( this == \"this\" )\n" +
            "    String( this == \"that\" )\n" +
            "then\n" +
            "end\n";

    KieBase kbase = new KieHelper().addContent( str, ResourceType.DRL ).build();
    KieSession ksession = kbase.newKieSession();
    ksession.fireAllRules();

    for ( int i = 0; i < 10; i++ ) {
        FactHandle fh = ksession.insert( "this" );
        ksession.fireAllRules();
        ksession.delete( fh );
        ksession.fireAllRules();
    }

    Rete rete = ( (KnowledgeBaseImpl) kbase ).getRete();
    LeftInputAdapterNode liaNode = null;
    for ( ObjectTypeNode otn : rete.getObjectTypeNodes() ) {
        if ( String.class == otn.getObjectType().getValueType().getClassType() ) {
            AlphaNode alphaNode = (AlphaNode) otn.getObjectSinkPropagator().getSinks()[0];
            liaNode = (LeftInputAdapterNode) alphaNode.getObjectSinkPropagator().getSinks()[0];
            break;
        }
    }

    assertNotNull( liaNode );
    InternalWorkingMemory wm = (InternalWorkingMemory) ksession;
    LeftInputAdapterNode.LiaNodeMemory memory = (LeftInputAdapterNode.LiaNodeMemory) wm.getNodeMemory( liaNode );
    TupleSets<LeftTuple> stagedLeftTuples = memory.getSegmentMemory().getStagedLeftTuples();
    assertNull( stagedLeftTuples.getDeleteFirst() );
    assertNull( stagedLeftTuples.getInsertFirst() );
}
 
Example 10
Source File: DeleteObjectCommand.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Void execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
    EntryPoint ep = ksession.getEntryPoint( entryPoint );
    if ( ep != null ) {
        FactHandle handle = ksession.getEntryPoint( entryPoint ).getFactHandle( object );
        ksession.delete( handle );
    }
    return null;
}
 
Example 11
Source File: RuleExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnDeleteMatchConsequence() throws Exception {
    String str =
            "import " + Person.class.getCanonicalName() + ";\n" +
            "rule R1 when\n" +
            "    $p : Person( age > 30 )\n" +
            "then\n" +
            "    $p.setStatus(\"in\");\n" +
            "then[$onDeleteMatch$]\n" +
            "    $p.setStatus(\"out\");\n" +
            "end\n";

    KieSession ksession = new KieHelper()
            .addContent(str, ResourceType.DRL)
            .build()
            .newKieSession();

    Person mario = new Person("Mario", 40);
    FactHandle fact = ksession.insert(mario);
    ksession.fireAllRules();

    assertEquals("in", mario.getStatus());

    ksession.delete(fact);
    ksession.fireAllRules();

    assertEquals("out", mario.getStatus());
}
 
Example 12
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMvelInsertWithNamedConsequence() {
    // DROOLS-726
    String drl2 =
            "package org.drools.compiler\n" +
            "global java.util.concurrent.atomic.AtomicInteger counter\n" +
            "declare Output\n" +
            "    feedback: String\n" +
            "end\n" +
            "rule \"Move to next\" dialect \"mvel\"\n" +
            "   when\n" +
            "          $i: Integer()\n" +
            "          if ($i == 1) break[nextStep1]\n" +
            "   then\n" +
            "           insert(new Output(\"defualt\"));\n" +
            "   then[nextStep1]\n" +
            "           insert(new Output(\"step 1\"));\n" +
            "end\n" +
            "\n" +
            "rule \"Produce output\"\n" +
            "    when\n" +
            "        $output: Output()\n" +
            "    then\n" +
            "        System.out.println($output);\n" +
            "        retract($output);" +
            "        counter.incrementAndGet();\n" +
            "end\n";

    KieSession kSession = new KieHelper().addContent(drl2, ResourceType.DRL)
                                         .build()
                                         .newKieSession();

    AtomicInteger counter = new AtomicInteger(0);
    kSession.setGlobal("counter", counter);

    FactHandle messageHandle = kSession.insert(1);
    kSession.fireAllRules();

    kSession.delete(messageHandle);
    kSession.insert(2);
    kSession.fireAllRules();

    assertEquals(2, counter.get());
}
 
Example 13
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testFiredRuleDoNotRefireAfterUnblock() {
    // BZ-1038076
    String drl =
            "package org.drools.compiler.integrationtests\n" +
            "\n" +
            "import org.kie.api.runtime.rule.Match\n" +
            "import java.util.List\n" +
            "\n" +
            "global List list\n" +
            "\n" +
            "rule startAgenda\n" +
            "salience 100\n" +
            "when\n" +
            "    String( this == 'startAgenda' )\n" +
            "then\n" +
            "    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup(\"agenda\").setFocus();\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n" +
            "\n" +
            "rule sales @department('sales')\n" +
            "agenda-group \"agenda\"\n" +
            "when\n" +
            "    $s : String( this == 'fireRules' )\n" +
            "then\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n" +
            "\n" +
            "rule salesBlocker salience 10\n" +
            "when\n" +
            "    $s : String( this == 'fireBlockerRule' )\n" +
            "    $i : Match( department == 'sales' )\n" +
            "then\n" +
            "    kcontext.blockMatch( $i );\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n";

    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
                                    .setDefault(true)
                                    .setDeclarativeAgenda(DeclarativeAgendaOption.ENABLED);
    baseModel.newKieSessionModel("defaultKSession")
             .setDefault(true);

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write("src/main/resources/block_rule.drl", drl);
    KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll();
    assertEquals( 0, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() );

    KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();

    List<String> list = new DebugList<String>();

    ksession.setGlobal("list", list);

    // first run
    ksession.insert("startAgenda");
    ksession.insert("fireRules");
    FactHandle fireBlockerRule = ksession.insert("fireBlockerRule");
    ksession.fireAllRules();
    String[] expected = { "startAgenda", "sales", "salesBlocker" };

    assertEquals(expected.length, list.size());
    for (int i = 0; i < list.size(); i++) {
        assertEquals(expected[i], list.get(i));
    }

    // second run
    ksession.delete(fireBlockerRule);
    list.clear();
    ksession.fireAllRules();
    assertEquals(0, list.size());

    ksession.dispose();
    list.clear();
}
 
Example 14
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogicalWithStatedShadowThenDeleteLogicalThenDeleteStated() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

            "global java.util.List list; \n" +

            "rule Justify \n" +
            "when \n" +
            "    String( this == 'go1' ) " +
            "then \n" +
            "    insertLogical( 'f1' ); \n" +
            "end \n" +


            "rule StillHere \n" +
            "when \n" +
            "    String( this in ('go2', 'go3', 'go4') ) " +
            "    s : String( this == 'f1' ) " +
            "then \n" +
            "    list.add( s ); \n" +
            "end \n" +
            ""
            ;

    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption( EqualityBehaviorOption.IDENTITY );
    KieBase kbase = loadKnowledgeBaseFromString( kieConf, droolsSource );
    KieSession session = kbase.newKieSession();
    try {
        List list = new ArrayList();
        session.setGlobal("list", list);

        session.insert( "go1" );
        session.fireAllRules();

        TruthMaintenanceSystem tms = ((StatefulKnowledgeSessionImpl)session).getTruthMaintenanceSystem();
        InternalFactHandle jfh1 = tms.get( "f1" ).getLogicalFactHandle();
        assertEquals(EqualityKey.JUSTIFIED, jfh1.getEqualityKey().getStatus());

        InternalFactHandle fh1 = (InternalFactHandle) session.insert( "f1" );

        session.insert("go2");
        session.fireAllRules();

        assertEquals(EqualityKey.STATED, fh1.getEqualityKey().getStatus());
        assertEquals(1, fh1.getEqualityKey().getBeliefSet().size());
        assertSame( fh1.getEqualityKey(), jfh1.getEqualityKey() );
        assertNotSame( fh1, jfh1 );

        // Make sure f1 only occurs once
        assertEquals(1, list.size());
        assertEquals("f1", list.get(0 ));

        list.clear();
        tms.delete( jfh1 );
        session.insert("go3");
        session.fireAllRules();

        assertNull(fh1.getEqualityKey().getBeliefSet());

        // Make sure f1 only occurs once
        assertEquals(1, list.size());
        assertEquals("f1", list.get(0 ));

        list.clear();
        session.delete( fh1 );
        session.insert("go4");
        session.fireAllRules();

        assertEquals(0, list.size());
    } finally {
        session.dispose();
    }
}
 
Example 15
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testStatedShadowLogicalThenLogicalOnly() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

            "global java.util.List list; \n" +

            "rule Justify \n" +
            "when \n" +
            "    String( this == 'go1' ) " +
            "then \n" +
            "    insertLogical( 'f1' ); \n" +
            "end \n" +


            "rule StillHere \n" +
            "when \n" +
            "    String( this == 'go2' ) " +
            "    s : String( this == 'f1' ) " +
            "then \n" +
            "    list.add( s ); \n" +
            "end \n" +
            ""
            ;

    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption( EqualityBehaviorOption.IDENTITY );
    KieBase kbase = loadKnowledgeBaseFromString( kieConf, droolsSource );
    KieSession session = kbase.newKieSession();
    try {
        List list = new ArrayList();
        session.setGlobal("list", list);

        InternalFactHandle fh1 = (InternalFactHandle) session.insert( "f1" );
        InternalFactHandle fh2 = (InternalFactHandle) session.insert( "f2" );


        FactHandle g1 = session.insert( "go1" );
        session.fireAllRules();

        // This removes the stated position, but it should still be logical now and exist
        session.delete( fh1, FactHandle.State.STATED );
        session.insert( "go2" );
        session.fireAllRules();

        // fh1 is invalid and no longer in the WM. However it's now reverted to it's Justified version and will
        // still be there
        assertFalse(fh1.isValid());

        // Make sure f1 is still there, but logical only now
        assertEquals(1, list.size());
        assertEquals("f1", list.get(0));
        InternalFactHandle jfh1 = ((StatefulKnowledgeSessionImpl)session).getTruthMaintenanceSystem().get( "f1" ).getLogicalFactHandle();
        assertEquals(EqualityKey.JUSTIFIED, jfh1.getEqualityKey().getStatus());

        assertSame(jfh1, session.getFactHandle("f1") );
    } finally {
        session.dispose();
    }
}
 
Example 16
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
//@Disabled("in Java 8, the byte[] generated by serialization are not the same and requires investigation")
public void testLogicalInsertionsNot() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsNot.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final Person a = new Person( "a" );
        final Cheese cheese = new Cheese( "brie",
                                          1 );
        ksession.setGlobal( "cheese",
                            cheese );

        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        Collection list = ksession.getObjects();
        assertEquals(1, list.size(), "i was not asserted by not a => i.");
        assertEquals(cheese, list.iterator().next(), "i was not asserted by not a => i.");

        FactHandle h = ksession.insert( a );

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        // no need to fire rules, assertion alone removes justification for i,
        // so it should be deleted.
        // workingMemory.fireAllRules();
        ksession.fireAllRules();
        list = ksession.getObjects();

        assertEquals(1, list.size(), "a was not asserted or i not deleted.");
        assertEquals(a, list.iterator().next(), "a was asserted.");
        assertFalse(list.contains(cheese ), "i was not rectracted.");

        // no rules should fire, but nevertheless...
        // workingMemory.fireAllRules();
        assertEquals(0,
                                ((InternalAgenda)((StatefulKnowledgeSessionImpl) ksession).getAgenda()).agendaSize(),
                                "agenda should be empty.");

        h = getFactHandle( h, ksession );
        ksession.delete( h );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        list = ksession.getObjects();
        assertEquals(1, list.size(), "i was not asserted by not a => i.");
        assertEquals(cheese, list.iterator().next(), "i was not asserted by not a => i.");
    } finally {
        ksession.dispose();
    }
}
 
Example 17
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled("Currently cannot support updates")
//@Disabled("in Java 8, the byte[] generated by serialization are not the same and requires investigation")
public void testLogicalInsertionsUpdateEqual() throws Exception {
    // calling update on a justified FH, states it
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsUpdateEqual.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final Person p = new Person( "person" );
        p.setAge( 2 );
        FactHandle h = ksession.insert( p );
        assertEquals(1, ksession.getObjects().size());

        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        assertEquals(2, ksession.getObjects().size());
        Collection l = ksession.getObjects( new ClassObjectFilter( CheeseEqual.class ) );
        assertEquals(1, l.size());
        assertEquals(3, ((CheeseEqual) l.iterator().next()).getPrice());

        h = getFactHandle( h, ksession );
        ksession.delete( h );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);


        Collection list = ksession.getObjects();
        // CheeseEqual was updated, making it stated, so it wouldn't have been logically deleted
        assertEquals(1, list.size());
        assertEquals(new CheeseEqual("person", 3), list.iterator().next());
        FactHandle fh = ksession.getFactHandle( list.iterator().next() );
        ksession.delete( fh );

        list = ksession.getObjects();
        assertEquals(0, list.size());

        TruthMaintenanceSystem tms =  ((NamedEntryPoint)ksession.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId()) ).getTruthMaintenanceSystem();

        final java.lang.reflect.Field field = tms.getClass().getDeclaredField( "equalityKeyMap" );
        field.setAccessible( true );
        final ObjectHashMap m = (ObjectHashMap) field.get( tms );
        field.setAccessible( false );
        assertEquals(0, m.size(), "assertMap should be empty");
    } finally {
        ksession.dispose();
    }
}
 
Example 18
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogicalInsertionsAccumulatorPattern() throws Exception {
    // JBRULES-449
    KieBase kbase = loadKnowledgeBase( "test_LogicalInsertionsAccumulatorPattern.drl" );
    kbase = SerializationHelper.serializeObject(kbase);
    KieSession ksession = kbase.newKieSession();
    try {
        ksession.setGlobal( "ga",
                            "a" );
        ksession.setGlobal( "gb",
                            "b" );
        ksession.setGlobal( "gs",
                            new Short( (short) 3 ) );

        ksession.fireAllRules();

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession,
                                                                             true);

        FactHandle h = ksession.insert( new Integer( 6 ) );
        assertEquals(1, ksession.getObjects().size());

        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession,
                                                                             true);
        assertEquals(2, ksession.getObjects(new ClassObjectFilter(CheeseEqual.class ) ).size(),
                                "There should be 2 CheeseEqual in Working Memory, 1 justified, 1 stated");
        assertEquals(6, ksession.getObjects().size());

        h = getFactHandle( h, ksession );
        ksession.delete( h );
        ksession.fireAllRules();

        for ( Object o : ksession.getObjects() ) {
            System.out.println( o );
        }

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession,
                                                                             true);
        assertEquals(0, ksession.getObjects(new ClassObjectFilter(CheeseEqual.class ) ).size());
        assertEquals(0, ksession.getObjects(new ClassObjectFilter(Short.class ) ).size());
        assertEquals(0, ksession.getObjects().size());
    } finally {
        ksession.dispose();
    }
}
 
Example 19
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testRestateJustified() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

            "declare Foo id : int @key end \n\n" +

            "rule Zero \n" +
            "when \n" +
            " $s : String( this == \"go\" ) \n" +
            "then \n" +
            " insertLogical( new Foo(1) ); \n" +
            "end \n" +

            "rule Restate \n" +
            "when \n" +
            " $s : String( this == \"go2\" ) \n" +
            " $f : Foo( id == 1 ) \n" +
            "then \n" +
            " insert( $f ); \n" +
            "end \n" ;

    /////////////////////////////////////


    KieSession session = loadKnowledgeBaseFromString( droolsSource ).newKieSession();
    try {
        session.fireAllRules();
        FactHandle handle = session.insert( "go" );
        session.fireAllRules();

        FactHandle handle2 = session.insert( "go2" );
        session.fireAllRules();

        session.delete( handle );
        session.delete( handle2 );
        session.fireAllRules();

        assertEquals(1, session.getObjects().size());
    } finally {
        session.dispose();
    }
}
 
Example 20
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPrimeJustificationWithEqualityMode() {
    String droolsSource =
            "package org.drools.tms.test; \n" +
            "declare Bar end \n" +
            "" +
            "declare Holder x : Bar end \n" +
            "" +
            "" +
            "rule Init \n" +
            "when \n" +
            "then \n" +
            "   insert( new Holder( new Bar() ) ); \n" +
            "end \n" +

            "rule Justify \n" +
            "when \n" +
            " $s : Integer() \n" +
            " $h : Holder( $b : x ) \n" +
            "then \n" +
            " insertLogical( $b ); \n" +
            "end \n" +

            "rule React \n" +
            "when \n" +
            " $b : Bar(  ) \n" +
            "then \n" +
            " System.out.println( $b );  \n" +
            "end \n" ;

    /////////////////////////////////////

    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
        kieConf.setOption( EqualityBehaviorOption.EQUALITY );
    KieBase kbase = loadKnowledgeBaseFromString( kieConf, droolsSource );
    KieSession session = kbase.newKieSession();
    try {
        FactHandle handle1 = session.insert( 10 );
        FactHandle handle2 = session.insert( 20 );

        assertEquals(4, session.fireAllRules());

        session.delete( handle1 );
        assertEquals(0, session.fireAllRules());
    } finally {
        session.dispose();
    }
}