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

The following examples show how to use org.kie.api.runtime.KieSession#dispose() . 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: StrEvaluatorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrLengthNoEquals() {
    KieBase kbase = readKnowledgeBase();
    KieSession ksession = createKnowledgeSession(kbase);
    try {
        List list = new ArrayList();
        ksession.setGlobal( "list", list );

        RoutingMessage m = new RoutingMessage();
        m.setRoutingValue("messageBody");

        ksession.insert(m);
        ksession.fireAllRules();
        assertTrue(list.size() == 3);

        assertTrue( list.get(0).equals("Message length is not 17") );
        assertTrue( list.get(1).equals("Message does not start with R2") );
        assertTrue( list.get(2).equals("Message does not end with R1") );
    } finally {
        ksession.dispose();
    }
}
 
Example 2
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogicalInsertionsNotPingPong() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsNotPingPong.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final List list = new ArrayList();

        final Person person = new Person( "person" );
        final Cheese cheese = new Cheese( "cheese",
                                          0 );
        ksession.setGlobal( "cheese", cheese );
        ksession.setGlobal( "person", person );
        ksession.setGlobal( "list", list );

        ksession.fireAllRules();

        // not sure about desired state of working memory.
        assertEquals(10, list.size(), "Rules have not fired (looped) expected number of times");
    } finally {
        ksession.dispose();
    }
}
 
Example 3
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewClassPathResource() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // newClassPathResource without specifying encoding
    kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_utf8_forTestNewClassPathResource.drl", getClass() ),
                  ResourceType.DRL );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);

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

    I18nPerson i18nPerson = new I18nPerson();
    i18nPerson.set名称("山田花子");
    ksession.insert(i18nPerson);
    ksession.fireAllRules();

    assertTrue(list.contains("名称は山田花子です"));

    ksession.dispose();
}
 
Example 4
Source File: InlineCastTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineCastOnRightOperandWithFQN() throws Exception {
    String str = "import org.drools.compiler.Person;\n" +
            "rule R1 when\n" +
            "   $person : Person( )\n" +
            "   String( this == $person.address#org.drools.compiler.LongAddress.country )\n" +
            "then\n" +
            "end\n";

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = kbase.newKieSession();

    Person mark1 = new Person("mark");
    mark1.setAddress(new LongAddress("uk"));
    ksession.insert(mark1);
    ksession.insert("uk");

    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
}
 
Example 5
Source File: MultiConditionRulesJUnitTest.java    From drools-workshop with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoomAndHouseRelated() {
    Assert.assertNotNull(kBase);
    KieSession kSession = kBase.newKieSession();
    System.out.println(" ---- Starting testRoomAndHouseRelated() Test ---");
    Room livingRoom = new Room("living room", 10);
    kSession.insert(livingRoom);

    House house = new House();
    List<Room> rooms = new ArrayList<Room>();
    rooms.add(livingRoom);
    house.setRooms(rooms);
    kSession.insert(house);

    Assert.assertEquals(1, kSession.fireAllRules());
    System.out.println(" ---- Finished testRoomAndHouseRelated() Test ---");
    kSession.dispose();
}
 
Example 6
Source File: KieSessionIterationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that disposing KieSessions does not throw ConcurrentModificationException when iterating through the list of KieBase's KieSessions
 * (related to BZ 1326329).
 */
@Test
public void testDisposingSeveralKieSessions() throws Exception {
    for (KieSession kieSession : this.kieBase.getKieSessions()) {
        kieSession.dispose();
    }
    assertTrue(this.kieBase.getKieSessions().isEmpty(), "All KieSessions of the KieBase should have been disposed.");
}
 
Example 7
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithEval() throws IOException, ClassNotFoundException {
    // [Regression in 5.2.0.M2]: NPE during rule evaluation on MVELPredicateExpression.evaluate(MVELPredicateExpression.java:82)

    String str = "package org.drools.compiler.integrationtests\n" +
                 "import " + DomainObject.class.getCanonicalName() + " \n" +
                 "query queryWithEval \n" +
                 "    $do: DomainObject()\n" +
                 "    not DomainObject( id == $do.id, eval(interval.isAfter($do.getInterval())))\n" +
                 "end";

    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
    KieSession ksession = createKieSession( kbase );

    DomainObject do1 = new DomainObject();
    do1.setId( 1 );
    do1.setInterval( new Interval( 10,
                                   5 ) );
    DomainObject do2 = new DomainObject();
    do2.setId( 1 );
    do2.setInterval( new Interval( 20,
                                   5 ) );
    ksession.insert( do1 );
    ksession.insert( do2 );

    org.kie.api.runtime.rule.QueryResults results = ksession.getQueryResults( "queryWithEval" );
    assertEquals( 1,
                  results.size() );
    assertEquals( do2,
                  results.iterator().next().get( "$do" ) );

    ksession.dispose();
}
 
Example 8
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testJBRULES_2206() {
    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    ((RuleBaseConfiguration) config).setRuleBaseUpdateHandler( null );
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) getKnowledgeBase( config );
    KieSession session = createKnowledgeSession( kbase );

    AgendaEventListener ael = mock( AgendaEventListener.class );
    session.addEventListener( ael );

    for ( int i = 0; i < 5; i++ ) {
        session.insert( new Cheese() );
    }

    kbase.addPackages( loadKnowledgePackages( "test_JBRULES_2206_1.drl" ));
    ((InternalAgenda) session.getAgenda()).evaluateEagerList();

    // two matching rules were added, so 2 activations should have been created 
    verify( ael, times( 2 ) ).matchCreated(any(MatchCreatedEvent.class));
    int fireCount = session.fireAllRules();
    // both should have fired
    assertEquals( 2, fireCount );

    kbase.addPackages( loadKnowledgePackages( "test_JBRULES_2206_2.drl" ));
    ((InternalAgenda) session.getAgenda()).evaluateEagerList();

    // one rule was overridden and should activate 
    verify( ael, times( 3 ) ).matchCreated(any(MatchCreatedEvent.class));
    fireCount = session.fireAllRules();
    // that rule should fire again
    assertEquals( 1, fireCount );

    session.dispose();
}
 
Example 9
Source File: WorkingMemoryLoggerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutOfMemory() throws Exception {
    final KieBase kbase = loadKnowledgeBase( "empty.drl");

    for (int i = 0; i < 10000; i++) {
        final KieSession session = createKnowledgeSession(kbase);
        session.fireAllRules();
        session.dispose();
    }
}
 
Example 10
Source File: ConcurrentBasesParallelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedConcurrentBasesParallelTest
public void testAccumulatesMatchOnlyBeanA(Parameters params) throws InterruptedException {
    final String ruleA = "import " + BeanA.class.getCanonicalName() + ";\n" +
            "rule RuleA " +
            "when " +
            "    $n : Number( doubleValue == 1 ) from accumulate($bean : BeanA(), count($bean)) " +
            "then " +
            "end";

    final String ruleB = "import " + BeanB.class.getCanonicalName() + ";\n" +
            "rule RuleB " +
            "when " +
            "    $n : Number( doubleValue == 1 ) from accumulate($bean : BeanB(), count($bean)) " +
            "then " +
            "end";

    final TestExecutor exec = counter -> {

        final KieBase base = getKieBase(params, ruleA, ruleB);
        final KieSession session = base.newKieSession();

        try {
            if (counter % 2 == 0) {
                session.insert(new BeanA(counter));
                assertThat(session.fireAllRules()).isEqualTo(1);
            } else {
                assertThat(session.fireAllRules()).isEqualTo(0);
            }
            return true;
        } finally {
            session.dispose();
        }
    };

    parallelTest(NUMBER_OF_THREADS, exec);
}
 
Example 11
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 12
Source File: NestedAccessorsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testNestedAccessors2() throws Exception {
    final String rule = "package org.drools.compiler\n" +
            "rule 'rule1'" +
            "    salience 10\n" +
            "when\n" +
            "    Cheesery( typedCheeses[0].type == 'stilton' );\n" +
            "then\n" +
            "end\n" +
            "rule 'rule2'\n" +
            "when\n" +
            "    Cheesery( typedCheeses[0].price == 10 );\n" +
            "then\n" +
            "end";

    final KieBase kbase = loadKnowledgeBaseFromString(rule);
    final KieSession ksession = createKnowledgeSession(kbase);
    final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
    ksession.addEventListener(ael);

    final Cheesery c1 = new Cheesery();
    c1.addCheese(new Cheese("stilton", 20));
    final Cheesery c2 = new Cheesery();
    c2.addCheese(new Cheese("brie", 10));
    final Cheesery c3 = new Cheesery();
    c3.addCheese(new Cheese("muzzarella", 30));

    ksession.insert(c1);
    ksession.insert(c2);
    ksession.insert(c3);
    ksession.fireAllRules();

    final ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
    verify(ael, times(2)).afterMatchFired(captor.capture());

    final List<org.kie.api.event.rule.AfterMatchFiredEvent> values = captor.getAllValues();
    assertThat(values.get(0).getMatch().getObjects()).first().isEqualTo(c1);
    assertThat(values.get(1).getMatch().getObjects()).first().isEqualTo(c2);

    ksession.dispose();
}
 
Example 13
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTMSwithQueries() {
    String str =""+
            "package org.drools.compiler.test;\n" +
            "\n" +
            "global java.util.List list; \n" +
            "\n" +
            "declare Bean\n" +
            "    str : String\n" +
            "end\n" +
            "\n" +
            "query bean ( String $s )\n" +
            "    Bean(  $s ; )\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"init\"\n" +
            "when\n" +
            "then\n" +
            "    insert( new Bean(\"AAA\") );\n" +
            "    insert( \"x\" );\n" +
            "end\n" +
            "\n" +
            "rule \"LogicIn\"\n" +
            "when\n" +
            "    String( this == \"x\" )\n" +
            "    ?bean(  \"AAA\" ; )\n" +
            "then\n" +
            "    insertLogical(\"y\");\n" +
            "    retract(\"x\");\n" +
            "end " +
            "\n" +
            "rule \"Never\"\n" +
            "salience -999\n" +
            "when\n" +
            "    $s : String( this == \"y\" )\n" +
            "then\n" +
            "    list.add($s);\n" +
            "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()),
            ResourceType.DRL );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession kSession = createKnowledgeSession(kbase);
    try {
        List list = new ArrayList();
        kSession.setGlobal("list",list);


        kSession.fireAllRules();
        assertEquals(0, list.size());
    } finally {
        kSession.dispose();
    }
}
 
Example 14
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleBlockers() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";

    str += "rule rule0 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go0' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";

    str += "rule blockerAllSalesRules1 @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    str += "rule blockerAllSalesRules2 @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go2' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    str += "rule blockerAllSalesRules3 @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go3' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    FactHandle go0 = ksession.insert( "go0" );
    FactHandle go1 = ksession.insert( "go1" );
    FactHandle go2 = ksession.insert( "go2" );
    FactHandle go3 = ksession.insert( "go3" );

    ksession.fireAllRules();
    assertEquals( 3,
                  list.size() );
    assertTrue( list.contains( "rule0:go1" ) );
    assertTrue( list.contains( "rule0:go2" ) );
    assertTrue( list.contains( "rule0:go3" ) );

    list.clear();

    ksession.retract( go3 );
    ksession.fireAllRules();
    assertEquals( 0,
                  list.size() );

    ksession.retract( go2 );
    ksession.fireAllRules();
    assertEquals( 0,
                  list.size() );

    ksession.retract( go1 );
    ksession.fireAllRules();
    assertEquals( 1,
                  list.size() );

    assertTrue( list.contains( "rule0:go0" ) );
    ksession.dispose();
}
 
Example 15
Source File: FireUntilHaltTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubmitOnFireUntilHalt() throws InterruptedException {
    final String drl =
            "import " + Person.class.getCanonicalName() + "\n" +
            "global java.util.List list;" +
            "rule R when\n" +
            "    Person( happy, age >= 18 )\n" +
            "then\n" +
            "    list.add(\"happy adult\");" +
            "end";

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

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

    new Thread(kSession::fireUntilHalt).start();

    final Person p = new Person("me", 17, true);
    final FactHandle fh = kSession.insert(p);

    Thread.sleep(100L);
    assertEquals(0, list.size());

    kSession.submit(kieSession -> {
        p.setAge(18);
        p.setHappy(false);
        kieSession.update(fh, p);
    });

    Thread.sleep(100L);
    assertEquals(0, list.size());

    kSession.submit(kieSession -> {
        p.setHappy(true);
        kieSession.update(fh, p);
    });

    Thread.sleep(100L);
    assertEquals(1, list.size());

    kSession.halt();
    kSession.dispose();
}
 
Example 16
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();
    }
}
 
Example 17
Source File: AbstractConcurrentInsertionsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected void testConcurrentInsertions(final String drl, final int objectCount, final int threadCount,
                                        final boolean newSessionForEachThread,
                                        final boolean updateFacts) throws InterruptedException {

    final KieBase kieBase = new KieHelper().addContent(drl, ResourceType.DRL).build();

    final ExecutorService executor = Executors.newFixedThreadPool(threadCount, r -> {
        final Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    });

    KieSession ksession = null;
    try {
        final Callable[] tasks = new Callable[threadCount];
        if (newSessionForEachThread) {
            for (int i = 0; i < threadCount; i++) {
                tasks[i] = getTask(objectCount, kieBase, updateFacts);
            }
        } else {
            ksession = kieBase.newKieSession();
            for (int i = 0; i < threadCount; i++) {
                tasks[i] = getTask(objectCount, ksession, false, updateFacts);
            }
        }

        final CompletionService<Boolean> ecs = new ExecutorCompletionService<>(executor);
        for (final Callable task : tasks) {
            ecs.submit(task);
        }

        org.junit.jupiter.api.Assertions.assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
            int successCounter = 0;
            for (int i = 0; i < threadCount; i++) {
                try {
                    if (ecs.take().get()) {
                        successCounter++;
                    }
                } catch (final Exception e) {
                    throw new RuntimeException(e);
                }
            }
            assertThat(successCounter).isEqualTo(threadCount);
        });
        if (ksession != null) {
            ksession.dispose();
        }
    } finally {
        executor.shutdown();
        if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
            executor.shutdownNow();
        }
    }
}
 
Example 18
Source File: MultithreadTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled
public void testConcurrencyWithChronThreads() throws InterruptedException {

    final String drl = "package it.intext.drools.fusion.bug;\n" +
            "\n" +
            "import " + MyFact.class.getCanonicalName() + ";\n " +
            " global java.util.List list; \n" +
            "\n" +
            "declare MyFact\n" +
            "\t@role( event )\n" +
            "\t@expires( 1s )\n" +
            "end\n" +
            "\n" +
            "rule \"Dummy\"\n" +
            "timer( cron: 0/1 * * * * ? )\n" +
            "when\n" +
            "  Number( $count : intValue ) from accumulate( MyFact( ) over window:time(1s); sum(1) )\n" +
            "then\n" +
            "    System.out.println($count+\" myfact(s) seen in the last 1 seconds\");\n" +
            "    list.add( $count ); \n" +
            "end";

    final KieBaseConfiguration kbconfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconfig.setOption(EventProcessingOption.STREAM);

    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);

    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("REALTIME"));
    final KieSession ksession = kbase.newKieSession(conf, null);

    final List list = new ArrayList();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();

    final Runner t = new Runner(ksession);
    t.start();
    try {
        final int FACTS_PER_POLL = 1000;
        final int POLL_INTERVAL = 500;

        final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        try {
            executor.scheduleAtFixedRate(
                    () -> {
                        for (int j = 0; j < FACTS_PER_POLL; j++) {
                            ksession.insert(new MyFact());
                        }
                    },
                    0,
                    POLL_INTERVAL,
                    TimeUnit.MILLISECONDS);

            Thread.sleep(10200);
        } finally {
            executor.shutdownNow();
        }
    } finally {
        ksession.halt();
        ksession.dispose();
    }

    t.join();

    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }

    System.out.println("Final size " + ksession.getObjects().size());

    ksession.dispose();
}
 
Example 19
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 testLogicalInsertionsWithExists() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionWithExists.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final Person p1 = new Person( "p1",
                                      "stilton",
                                      20 );
        p1.setStatus( "europe" );
        FactHandle c1FactHandle = ksession.insert( p1 );
        final Person p2 = new Person( "p2",
                                      "stilton",
                                      30 );
        p2.setStatus( "europe" );
        FactHandle c2FactHandle = ksession.insert( p2 );
        final Person p3 = new Person( "p3",
                                      "stilton",
                                      40 );
        p3.setStatus( "europe" );
        FactHandle c3FactHandle = ksession.insert( p3 );
        ksession.fireAllRules();

        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);

        // all 3 in europe, so, 2 cheese
        Collection cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(2, cheeseList.size());

        // europe=[ 1, 2 ], america=[ 3 ]
        p3.setStatus( "america" );
        c3FactHandle = getFactHandle( c3FactHandle, ksession );
        ksession.update( c3FactHandle,
                         p3 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(1, cheeseList.size());

        // europe=[ 1 ], america=[ 2, 3 ]
        p2.setStatus( "america" );
        c2FactHandle = getFactHandle( c2FactHandle, ksession );
        ksession.update( c2FactHandle,
                         p2 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(1, cheeseList.size());

        // europe=[ ], america=[ 1, 2, 3 ]
        p1.setStatus( "america" );
        c1FactHandle = getFactHandle( c1FactHandle, ksession );
        ksession.update( c1FactHandle,
                         p1 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(2, cheeseList.size());

        // europe=[ 2 ], america=[ 1, 3 ]
        p2.setStatus( "europe" );
        c2FactHandle = getFactHandle( c2FactHandle, ksession );
        ksession.update( c2FactHandle,
                         p2 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(1, cheeseList.size());

        // europe=[ 1, 2 ], america=[ 3 ]
        p1.setStatus( "europe" );
        c1FactHandle = getFactHandle( c1FactHandle, ksession );
        ksession.update( c1FactHandle,
                         p1 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(1, cheeseList.size());

        // europe=[ 1, 2, 3 ], america=[ ]
        p3.setStatus( "europe" );
        c3FactHandle = getFactHandle( c3FactHandle, ksession );
        ksession.update( c3FactHandle,
                         p3 );
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        ksession.fireAllRules();
        ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
        cheeseList = ksession.getObjects(new ClassObjectFilter(Cheese.class));
        assertEquals(2, cheeseList.size());
    } finally {
        ksession.dispose();
    }
}
 
Example 20
Source File: NodeHashingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testNodeHashTypeMismatch() throws Exception {
    // BZ-1328380

    // 2 rules -- Mvel coercion
    String drl1 = "import " + Person.class.getCanonicalName() + ";\n" +
                  "rule \"rule1\"\n" +
                  "when\n" +
                  "    Person( status == 1 )\n" +
                  "then\n" +
                  "end\n" +
                  "rule \"rule2\"\n" +
                  "when\n" +
                  "    Person( status == 2 )\n" +
                  "then\n" +
                  "end\n";

    KieSession ksession1 = new KieHelper().addContent( drl1, ResourceType.DRL )
                                          .build()
                                          .newKieSession();

    Person p1 = new Person();
    p1.setStatus( "1" );
    ksession1.insert( p1 );

    assertEquals( 1, ksession1.fireAllRules() );
    ksession1.dispose();

    // 3 rules -- Node Hashing
    String drl2 = "import " + Person.class.getCanonicalName() + ";\n" +
                  "rule \"rule1\"\n" +
                  "when\n" +
                  "    Person( status == 1 )\n" +
                  "then\n" +
                  "end\n" +
                  "rule \"rule2\"\n" +
                  "when\n" +
                  "    Person( status == 2 )\n" +
                  "then\n" +
                  "end\n" +
                  "rule \"rule3\"\n" +
                  "when\n" +
                  "    Person( status == 3 )\n" +
                  "then\n" +
                  "end\n";

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

    Person p2 = new Person();
    p2.setStatus( "1" );
    ksession2.insert( p2 );

    assertEquals( 1, ksession2.fireAllRules() );
    ksession2.dispose();
}