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

The following examples show how to use org.kie.api.runtime.KieSession#fireAllRules() . 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: MVELTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyObjectWithMutableHashCodeInEqualityMode2() {
    // DROOLS-2828
    String str = "package com.sample\n" +
            "import " + Human.class.getCanonicalName() + ";\n" +
            "rule \"Step A\"\n" +
            "dialect \"mvel\"\n" +
            "when\n" +
            "    e : Human()\n" +
            "    not String()\n" +
            "then\t\n" +
            "    insert(\"test\");\n" +
            "    modify( e ) {\n" +
            "        setAge( 10 );\n" +
            "    }\n" +
            "end";

    KieSession ksession = new KieHelper().addContent( str, ResourceType.DRL ).build( EqualityBehaviorOption.EQUALITY ).newKieSession();
    Human h = new Human(2);
    ksession.insert(h);
    ksession.fireAllRules();
    assertEquals( 10, h.getAge() );
}
 
Example 3
Source File: FunctionsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunctionWithPrimitives() throws Exception {
    KieBase kbase = loadKnowledgeBase( "test_FunctionWithPrimitives.drl" );
    KieSession ksession = createKnowledgeSession(kbase);

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

    final Cheese stilton = new Cheese( "stilton",
                                       5 );
    ksession.insert( stilton );

    ksession.fireAllRules();

    assertEquals( new Integer( 10 ),
                  list.get( 0 ) );
}
 
Example 4
Source File: DeleteTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyRetractAndModifyInsert() throws Exception {
    final KieBase kbase = SerializationHelper.serializeObject( loadKnowledgeBase( "test_ModifyRetractInsert.drl" ) );
    final KieSession ksession = createKnowledgeSession( kbase );

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

    final org.drools.compiler.Person bob = new org.drools.compiler.Person("Bob");
    bob.setStatus("hungry");
    ksession.insert(bob);
    ksession.insert(new org.drools.compiler.Cheese());
    ksession.insert(new org.drools.compiler.Cheese());

    ksession.fireAllRules(2);

    assertEquals(1, list.size(), "should have fired only once");
}
 
Example 5
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
    public void readDrlInEncodingLatin1() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_latin1.drl.latin1", "ISO-8859-1", 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.setGarçon("Value 1");
//        i18nPerson.setÉlève("Value 2");
        ksession.insert(i18nPerson);
        ksession.fireAllRules();

        assertTrue(list.contains("garçon"));
//        assertTrue(list.contains("élève"));
        ksession.dispose();
    }
 
Example 6
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
 public void testExtendsAcrossFiles() throws Exception {
    KieSession ksession = new KieHelper()
            .addResource( ResourceFactory.newClassPathResource( "test_Ext1.drl", getClass() ), ResourceType.DRL )
            .addResource( ResourceFactory.newClassPathResource( "test_Ext2.drl", getClass() ), ResourceType.DRL )
            .addResource( ResourceFactory.newClassPathResource( "test_Ext3.drl", getClass() ), ResourceType.DRL )
            .addResource( ResourceFactory.newClassPathResource( "test_Ext4.drl", getClass() ), ResourceType.DRL )
            .build().newKieSession();

    FactType person = ksession.getKieBase().getFactType("org.drools.compiler.ext.test","Person");
        assertNotNull(person);
    FactType student = ksession.getKieBase().getFactType("org.drools.compiler.ext.test","Student");
        assertNotNull(student);

    FactType worker = ksession.getKieBase().getFactType("org.drools.compiler.anothertest","Worker");
        assertNotNull(worker);

    FactType ltss = ksession.getKieBase().getFactType("defaultpkg","SubLTStudent");
        assertNotNull(ltss);

    Constructor ctor = worker.getFactClass().getConstructor(String.class,int.class,String.class, double.class, int.class);
        assertNotNull(ctor);

    Object w = ctor.newInstance("Adam",20,"Carpenter",150.0,40);
    System.out.println(w);
        assertEquals("Adam",worker.get(w,"name"));

    ksession.fireAllRules();
}
 
Example 7
Source File: HelloworldTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 测试规则的触发
 */
@Test
public void helloTest(){

    KieSession kieSession = kieBase.newKieSession();
    //激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
    kieSession.fireAllRules(new RuleNameEqualsAgendaFilter("rule_helloworld"));
    kieSession.dispose();
}
 
Example 8
Source File: OOPathTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotReactivePeer() {
    // DROOLS-1727
    String drl1 =
            "import org.drools.compiler.oopath.model.*;\n" +
            "global java.util.List list\n\n" +
            "rule R1 when\n" +
            "  not String()\n" +
            "  $a : Man( name == \"Mario\" )\n" +
            "then\n" +
            "  list.add(\"Found\");\n" +
            "  insert($a.getName());\n" +
            "end\n\n" +
            "rule R2 when\n" +
            "  not String()\n" +
            "  $a : Man( $c: /children[age == 6], name == \"Mario\" )\n" +
            "then\n" +
            "  list.add(\"Found\");\n" +
            "  insert($a.getName());\n" +
            "end\n\n";

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

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

    Man mario = new Man("Mario", 40);
    mario.addChild( new Child("Sofia", 6) );

    ksession.insert( mario );
    ksession.fireAllRules();

    assertEquals( 1, list.size() );
}
 
Example 9
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDispose() throws Exception {
    final StringBuilder rule = new StringBuilder();
    rule.append("package org.drools.compiler\n");
    rule.append("rule X\n");
    rule.append("when\n");
    rule.append("    Message()\n");
    rule.append("then\n");
    rule.append("end\n");

    //building stuff
    final KieBase kbase = loadKnowledgeBaseFromString(rule.toString());
    final KieSession ksession = createKnowledgeSession(kbase);

    ksession.insert(new Message("test"));
    final int rules = ksession.fireAllRules();
    assertEquals(1, rules);

    ksession.dispose();

    try {
        // the following should raise an IllegalStateException as the session was already disposed
        ksession.fireAllRules();
        fail("An IllegallStateException should have been raised as the session was disposed before the method call.");
    } catch (final IllegalStateException ise) {
        // success
    }
}
 
Example 10
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleDefeats() {
    KieSession kSession = getSession( "org/drools/compiler/beliefsystem/defeasible/multiDefeat.drl" );
    kSession.fireAllRules();

    TruthMaintenanceSystem tms = ((NamedEntryPoint) kSession.getEntryPoint( "DEFAULT" )).getTruthMaintenanceSystem();
    FactType Xtype = kSession.getKieBase().getFactType( "org.drools.defeasible", "X" );


    ObjectHashMap keys = tms.getEqualityKeyMap();
    Iterator iter = keys.iterator();
    ObjectHashMap.ObjectEntry entry;
    while ( ( entry = ( ObjectHashMap.ObjectEntry) iter.next() ) != null ) {
        EqualityKey key = (EqualityKey) entry.getValue();

        Class factClass = key.getFactHandle().getObject().getClass();
        if ( factClass == Xtype.getFactClass() ) {
            checkStatus( key, 2, DefeasibilityStatus.DEFEATEDLY );
        } else {
            fail( "Unrecognized object has been logically justified : " + factClass );
        }
    }

    for ( Object o : kSession.getObjects() ) {
        System.out.println( o );
    }
    assertEquals( 2, kSession.getObjects().size() );


    kSession.fireAllRules();
}
 
Example 11
Source File: FirstOrderLogicTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollectResultBetaConstraint() throws Exception {
    KieBase kbase = loadKnowledgeBase( "test_CollectResultsBetaConstraint.drl");
    KieSession wm = createKnowledgeSession(kbase);

    List results = new ArrayList();

    wm.setGlobal( "results",
                  results );

    wm.insert( new Double( 10 ) );
    wm.insert( new Integer( 2 ) );

    wm.fireAllRules();

    assertEquals( 0,
                         results.size() );

    wm.insert( new Double( 15 ) );
    wm.fireAllRules();

    assertEquals( 2,
                         results.size() );

    assertEquals( "collect",
                         results.get( 0 ) );
    assertEquals( "accumulate",
                         results.get( 1 ) );
}
 
Example 12
Source File: NullTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullHandling() throws Exception {
    final KieBase kbase = loadKnowledgeBase("test_NullHandling.drl");
    KieSession session = createKnowledgeSession(kbase);

    final List list = new ArrayList();
    session.setGlobal("list", list);
    final Cheese nullCheese = new Cheese(null, 2);
    session.insert(nullCheese);

    final Person notNullPerson = new Person("shoes butt back");
    notNullPerson.setBigDecimal(new BigDecimal("42.42"));

    session.insert(notNullPerson);

    Person nullPerson = new Person("whee");
    nullPerson.setBigDecimal(null);

    session.insert(nullPerson);

    session = SerializationHelper.getSerialisedStatefulKnowledgeSession(session, true);
    session.fireAllRules();
    //System.out.println(((List) session.getGlobal("list")).get(0));
    assertEquals(3, ((List) session.getGlobal("list")).size());

    nullPerson = new Person(null);

    session.insert(nullPerson);
    session.fireAllRules();
    assertEquals(4, ((List) session.getGlobal("list")).size());
}
 
Example 13
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 14
Source File: DateComparisonTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDateComparisonAfterWithThisBinding() throws Exception {
    String str = "";
    str += "package org.drools.compiler;\n";
    str += "global java.util.List results;\n";
    str += "rule \"test date greater than\"\n";
    str += "     when\n";
    str += "         Cheese(type == \"Yesterday\", $c: this)\n";
    str += "         Cheese(type == \"Tomorrow\", $c.usedBy before usedBy)\n";
    str += "     then\n";
    str += "         results.add( \"test date greater than\" );\n";
    str += "end\n";

    str += "rule \"test date less than\"\n";
    str += "    when\n";
    str += "        Cheese(type == \"Tomorrow\", $c: this)\n";
    str += "        Cheese(type == \"Yesterday\", $c.usedBy after usedBy);\n";
    str += "    then\n";
    str += "        results.add( \"test date less than\" );\n";
    str += "end\n";

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

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

    // go !
    Cheese yesterday = new Cheese( "Yesterday" );
    yesterday.setUsedBy( yesterday() );
    Cheese tomorrow = new Cheese( "Tomorrow" );
    tomorrow.setUsedBy( tomorrow() );
    ksession.insert( yesterday );
    ksession.insert( tomorrow );
    ksession.fireAllRules();
    assertEquals( 2,
                  results.size() );
    assertTrue( results.contains( "test date greater than" ) );
    assertTrue( results.contains( "test date less than" ) );
}
 
Example 15
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdeographicSpaceInDSL() throws Exception {
    // JBRULES-3723
    String dsl =
            "// Testing 'IDEOGRAPHIC SPACE' (U+3000)\n" +
            "[when]名前が {firstName}=Person(name==\"山本 {firstName}\")\n" +
            "[then]メッセージ {message}=messages.add(\"メッセージ \" + {message});";

    String dslr =
            "package test\n" +
            "\n" +
            "import org.drools.compiler.Person\n" +
            "\n" +
            "expander test_I18n.dsl\n" +
            "\n" +
            "global java.util.List messages;\n" +
            "\n" +
            "rule \"IDEOGRAPHIC SPACE test\"\n" +
            "    when\n" +
            "        // Person(name==\"山本 太郎\")\n" +
            "        名前が 太郎\n" +
            "    then\n" +
            "        // messages.add(\"メッセージ ルールにヒットしました\");\n" +
            "         メッセージ \"ルールにヒットしました\"\n" +
            "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // Here I should explicitly set "UTF-8" because String.getBytes() depends on platform encoding and is not dealt by Drools side.
    kbuilder.add( ResourceFactory.newByteArrayResource(dsl.getBytes("UTF-8")), ResourceType.DSL );
    kbuilder.add( ResourceFactory.newByteArrayResource( dslr.getBytes("UTF-8") ), ResourceType.DSLR );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

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

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

    Person person = new Person();
    person.setName("山本 太郎");
    ksession.insert(person);
    ksession.fireAllRules();

    assertTrue(messages.contains("メッセージ ルールにヒットしました"));

    ksession.dispose();
}
 
Example 16
Source File: FirstOrderLogicTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCollectWithContainsOperators() throws Exception {
    KieBase kbase = loadKnowledgeBase( "test_CollectContainsOperator.drl");
    KieSession workingMemory = createKnowledgeSession(kbase);

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

    final Order order1 = new Order( 1,
                                    "bob" );
    final OrderItem item11 = new OrderItem( order1,
                                            1 );
    final OrderItem item12 = new OrderItem( order1,
                                            2 );
    final Order order2 = new Order( 2,
                                    "mark" );
    final OrderItem item21 = new OrderItem( order2,
                                            1 );
    final OrderItem item22 = new OrderItem( order2,
                                            2 );

    workingMemory.insert( order1 );
    workingMemory.insert( item11 );
    workingMemory.insert( item12 );
    workingMemory.insert( order2 );
    workingMemory.insert( item21 );
    workingMemory.insert( item22 );

    workingMemory.fireAllRules();

    int index = 0;
    assertEquals( 8,
                  list.size() );
    assertSame( order1,
                list.get( index++ ) );
    assertSame( item11,
                list.get( index++ ) );
    assertSame( order2,
                list.get( index++ ) );
    assertSame( item21,
                list.get( index++ ) );
    assertSame( order1,
                list.get( index++ ) );
    assertSame( item11,
                list.get( index++ ) );
    assertSame( order2,
                list.get( index++ ) );
    assertSame( item21,
                list.get( index++ ) );

}
 
Example 17
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 18
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCheckForItemsExample() {
    String droolsSource =
            "package org.drools.abductive.test; " +
            "import " + Abducible.class.getName() + "; " +
            "global java.util.List list; " +

            "declare Fruit id : int @key end " +

            "declare Apple extends Fruit end " +
            "declare Orange extends Fruit end " +
            "declare Banana extends Fruit end " +

            "declare Goal " +
            "   type : Class @key " +
            "end " +

            "query need( Class $type ) " +
            "   @Abductive( target = Goal.class ) " +
            "   not Fruit( $type.getName() == this.getClass().getName() ) " +
            "end " +

            "query check( Class $type ) " +
            "   ?need( $type ; ) " +
            "   or " +
            "   Fruit( $type.getName() == this.getClass().getName() ) " +
            "end " +

            "query checkRecipe() " +
            "   check( Apple.class ; ) " +
            "   check( Orange.class ; ) " +
            "   check( Banana.class ; ) " +
            "end " +

            "rule Fridge " +
            "   @Direct " +
            "when " +
            "then " +
            "   insert( new Banana( 1 ) ); " +
            //"   insert( new Apple( 2 ) ); " +
            "   insert( new Orange( 1 ) ); " +
            "end " +

            "rule Reminder " +
            "when " +
            "   accumulate( $f : Fruit() ," +
            "       $c : count( $f );" +
            "       $c == 2 " +         // works also with 1, or no fruit at all
            "   ) " +
            "   ?checkRecipe() " +
            "then " +
            "   System.out.println( 'You have ' + $c + ' ingredients ' ); " +
            "end " +

            "rule Suggest " +
            "when " +
            "   $g : Goal( $type ; ) " +
            "then " +
            "   System.out.println( 'You are missing ' + $type ); " +
            "   list.add( $type.getSimpleName() ); " +
            "end " +

            "rule FruitSalad " +
            "when " +
            "   Apple() " +
            "   Banana() " +
            "   Orange() " +
            "then " +
            "   System.out.println( 'Enjoy the salad' ); " +
            "end ";

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

    KieSession session = getSessionFromString( droolsSource );
    List list = new ArrayList(  );
    session.setGlobal( "list", list );

    session.fireAllRules();

    for ( Object o : session.getObjects() ) {
        System.out.println( ">>> " + o );
    }

    assertEquals( Arrays.asList( "Apple" ), list );
}
 
Example 19
Source File: TraitMapCoreTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapTraitPossibilities2()
{
    String drl = "" +
                 "package openehr.test;//org.drools.core.factmodel.traits;\n" +
                 "\n" +
                 "import org.drools.core.factmodel.traits.Traitable;\n" +
                 "import org.drools.core.factmodel.traits.Trait;\n" +
                 "import org.drools.core.factmodel.traits.Alias;\n" +
                 "import java.util.*;\n" +
                 "\n" +
                 "global java.util.List list;\n" +
                 "\n" + "" +
                 "declare HashMap @Traitable( logical = true ) end \n" +
                 "\n" +
                 "declare ESM @Traitable( logical = true )\n" +
                 " val : String\n" +
                 "end\n" +
                 "\n" +
                 "declare trait TName\n" +
                 "//@Trait( logical = true )\n" +
                 " length : Integer\n" +
                 "end\n" +
                 "\n" +
                 "declare trait TEsm extends TName\n" +
                 "//@Trait( logical = true )\n" +
                 " isValid : boolean\n" +
                 "end\n" +
                 "\n" +
                 "declare trait ChildTrait\n" +
                 "//@Trait( logical = true )\n" +
                 "@propertyReactive\n" +
                 " name : ESM\n" +
                 " id : int = 1002\n" +
                 "end\n" +
                 "\n" +
                 "rule \"init\"\n" +
                 "no-loop\n" +
                 "when\n" +
                 "then\n" +
                 " Map map = new HashMap();\n" +
                 " ESM esm = new ESM(\"ali\");\n" +
                 " TName tname = don( esm , TName.class );\n" +
                 " TEsm tesm = don( esm , TEsm.class );\n" +
                 " map.put(\"name\",tesm);\n" +
                 " insert(map);\n" +
                 "end\n" +
                 "\n" +
                 "\n" +
                 "rule \"don\"\n" +
                 "no-loop\n" +
                 "when\n" +
                 " $map : Map()" +
                 "then\n" +
                 " ChildTrait ct = don( $map , ChildTrait.class );\n" +
                 " list.add( ct );\n" +
                 " System.out.println(ct);\n" +
                 "end\n" +
                 "\n" +
                 "";

    KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession();
    TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase());

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

    assertEquals( 1, list.size() );
    assertNotNull(list.get(0));
}
 
Example 20
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTruthMaintenance() throws Exception {
    String header = "package org.drools.compiler.test;\n";
    header += "import java.util.List;\n";
    header += "import org.drools.compiler.Person\n";
    header += "import org.drools.compiler.Cheese\n";
    header += "global Cheese cheese;\n";
    header += "global Person person;\n";
    header += "global java.util.List list;\n";

    String rule1 = "rule \"not person then cheese\"\n";
    rule1 += "when \n";
    rule1 += "    not Person() \n";
    rule1 += "then \n";
    rule1 += "    if (list.size() < 3) { \n";
    rule1 += "        list.add(new Integer(0)); \n";
    rule1 += "        insertLogical( cheese ); \n" +
             "    }\n";
    rule1 += "    drools.halt();\n" +
             "end\n";

    String rule2 = "rule \"if cheese then person\"\n";
    rule2 += "when\n";
    rule2 += "    Cheese()\n";
    rule2 += "then\n";
    rule2 += "    if (list.size() < 3) {\n";
    rule2 += "        list.add(new Integer(0));\n";
    rule2 += "        insertLogical( person );\n";
    rule2 += "    }\n" +
             "    drools.halt();\n";
    rule2 += "end\n";


    KieBase kBase = loadKnowledgeBaseFromString( header + rule1 + rule2 );

    KieSession ksession = kBase.newKieSession( );

    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();
    assertEquals( 1,
                  list.size() );

    ksession = getSerialisedStatefulKnowledgeSession( ksession,
                                                      true );

    ksession.fireAllRules();
    assertEquals( 2,
                  list.size() );

    ksession = getSerialisedStatefulKnowledgeSession( ksession,
                                                      true );
    ksession.fireAllRules();
    assertEquals( 3,
                  list.size() );

    // should not grow any further
    ksession = getSerialisedStatefulKnowledgeSession( ksession,
                                                      true );
    ksession.fireAllRules();
    assertEquals( 3,
                  list.size() );
}