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

The following examples show how to use org.kie.api.runtime.KieSession#getObjects() . 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: DroolsUtil.java    From qzr with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates through the facts currently in working memory, and logs their details.
 * 
 * @param session The session to search for facts.
 */
public static void printFacts(KieSession session) {
    StringBuilder sb = new StringBuilder();
    sb.append("\n************************************************************");
    sb.append("\nThe following facts are currently in the system...");
    for (Object fact : session.getObjects()) {
        sb.append("\n\nFact: " + DroolsUtil.objectDetails(fact));
    }
    sb.append("\n************************************************************\n");
    log.info(sb.toString());
}
 
Example 2
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogicalInsertionsLoop() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsLoop.drl",
                                                        getClass() ),
                  ResourceType.DRL );
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject(kbase);
    final KieSession session = createKnowledgeSession(kbase);
    try {
        final List l = new ArrayList();
        final Person a = new Person( "a" );
        session.setGlobal( "a",
                           a );
        session.setGlobal( "l",
                           l );

        session.fireAllRules();
        Collection< ? > list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(0, list.size(), "a still asserted.");
        assertEquals(10, l.size(), "Rule has not fired (looped) expected number of times");
    } finally {
        session.dispose();
    }
}
 
Example 3
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefeaterNeutrality() {
    KieSession kSession = getSession( "org/drools/compiler/beliefsystem/defeasible/defeaterOnly.drl" );
    ArrayList list = new ArrayList();
    kSession.setGlobal( "list", list );
    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, 1, DefeasibilityStatus.DEFEATEDLY );
        } else {
            fail( "Unrecognized object has been logically justified : " + factClass );
        }
    }

    for ( Object o : kSession.getObjects() ) {
        System.out.println( o );
    }
    assertEquals( 0, list.size() );
    assertEquals( 1, kSession.getFactCount() );
}
 
Example 4
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 5
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSerializable() throws Exception {
    Collection<KiePackage>  kpkgs = loadKnowledgePackages("../test_Serializable.drl" );
    KiePackage kpkg = kpkgs.iterator().next();
    kpkg = SerializationHelper.serializeObject( kpkg );

    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase();
    kbase.addPackages( Collections.singleton( kpkg ) );

    Map<String, InternalKnowledgeBase> map = new HashMap<String, InternalKnowledgeBase>();
    map.put( "x",
             kbase );
    map = SerializationHelper.serializeObject( map );
    kbase = map.get( "x" );

    final org.kie.api.definition.rule.Rule[] rules = kbase.getKiePackages().iterator().next().getRules().toArray( new org.kie.api.definition.rule.Rule[0] );
    assertEquals( 4,
                  rules.length );

    assertEquals( "match Person 1",
                  rules[0].getName() );
    assertEquals( "match Person 2",
                  rules[1].getName() );
    assertEquals( "match Person 3",
                  rules[2].getName() );
    assertEquals( "match Integer",
                  rules[3].getName() );

    KieSession ksession = kbase.newKieSession();

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

    final Person bob = new Person( "bob" );
    ksession.insert( bob );

    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession( ksession,
                                                                          true );

    assertEquals( 1,
                  ksession.getFactCount() );
    assertEquals( bob,
                  ksession.getObjects().iterator().next() );

    assertEquals( 2,
                  ((InternalAgenda) ksession.getAgenda()).agendaSize() );

    ksession.fireAllRules();

    List list = (List) ksession.getGlobal( "list" );

    assertEquals( 3,
                  list.size() );
    // because of agenda-groups
    assertEquals( new Integer( 4 ),
                  list.get( 0 ) );

    // need to create a new collection or otherwise the collection will be identity based
    List< ? > objects = new ArrayList<Object>( ksession.getObjects() );
    assertEquals( 2, objects.size() );
    assertTrue( objects.contains( bob ) );
    assertTrue( objects.contains( new Person( "help" ) ) );
}
 
Example 6
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbductiveLogicWithConstructorArgs() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : Integer @key \n" +
            "   name : String @key \n" +
            "   value : double \n" +
            "   flag : boolean \n" +
            "end \n" +

            "query foo() \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "query foo2( Integer $i, String $name ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "   $i := Integer() from new Integer( 4 ) \n" +
            "   $name := String() " +
            "end \n" +

            "query foo3( Integer $i, String $name, double $val, boolean $bool ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "rule Init " +
            "   salience 9999 " +
            "when " +
            "then " +
            "   System.out.println( 'Foo zero is in' ); \n" +
            "   insert( new Foo() ); \n" +
            "end " +

            "rule R1 " +
            "when " +
            "   $fx : foo() " +
            "then " +
            "   list.add( 1 ); " +
            "end \n" +
            "" +
            "rule R2 " +
            "when " +
            "   foo2( 4, $n ; ) " +
            "then " +
            "   list.add( 2 ); " +
            "end \n" +
            "" +
            "rule R3 " +
            "when " +
            "   foo3( 42, \"test2\", $dbl, $bool ; ) " +
            "then " +
            "   list.add( 3 ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

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

    session.insert( "john" );

    session.fireAllRules();

    for ( Object o : session.getObjects() ) {
        System.out.println( ">> " + o );
    }
    System.err.println( list );
    assertEquals( Arrays.asList( 1, 2, 3 ), list );
}
 
Example 7
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 8
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testShadowAliasTraitOnClass(VirtualPropertyMode mode) {

    String drl = "package org.drools.test; \n" +
            "import org.drools.core.factmodel.traits.*; \n" +
            "import org.drools.core.factmodel.traits.Trait; \n" +
            "" +
            "global java.util.List list; \n" +
            "" +
            "declare trait X \n" +
            "  fld : T \n" +
            "end \n" +
            "" +
            "declare Y \n" +
            "@Traitable( logical = true ) \n" +
            "  fld : K \n" +
            "end \n" +
            "" +
            "declare trait T @Trait( logical=true ) end \n" +
            "declare K @Traitable() end \n" +
            "" +
            "rule Don \n" +
            "when \n" +
            "then \n" +
            "  Y y = new Y( new K() ); \n" +
            "  don( y, X.class ); \n" +
            "end \n" +
            "" +
            "rule Check \n" +
            "when \n" +
            "  X( fld isA T ) \n" +
            "then \n" +
            "  list.add( \"ok\" );" +
            "end \n";

    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());

    TraitFactory.setMode(mode, kbase);

    KieSession ks = kbase.newKieSession();
    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);

    ks.fireAllRules();
    for (Object o : ks.getObjects()) {
        System.out.println(o);
    }
    assertEquals(Arrays.asList("ok"), list);

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 9
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testFieldTypeDonMap(VirtualPropertyMode mode) {
    String drl = "package org.drools.test; \n" +
            "" +
            "global java.util.List list; \n" +
            "global java.util.List list2; \n" +
            "" +
            "declare trait T " +
            "  hardShort : short = 1 \n" +
            "  hardChar : char = 1 \n" +
            "  hardByte : byte = 1 \n" +
            "  hardInt : int = 1 \n" +
            "  hardLong : long = 1 \n" +
            "  hardFloat : float = 1.0f \n" +
            "  hardDouble : double = 1.0 \n" +
            "  hardBoolean : boolean = true \n" +
            "  hardString : String = \"x\" \n" +
            "  softShort : short = 1 \n" +
            "  softChar : char = 1 \n" +
            "  softByte : byte = 1 \n" +
            "  softInt : int = 1 \n" +
            "  softLong : long = 1 \n" +
            "  softFloat : float = 1.0f \n" +
            "  softDouble : double = 1.0 \n" +
            "  softBoolean : boolean = true \n" +
            "  softString : String = \"x\" \n" +
            "end \n" +
            "" +
            "declare X @Traitable( logical = true ) " +
            "  hardShort : short  \n" +
            "  hardChar : char  \n" +
            "  hardByte : byte  \n" +
            "  hardInt : int \n" +
            "  hardLong : long  \n" +
            "  hardFloat : float  \n" +
            "  hardDouble : double  \n" +
            "  hardBoolean : boolean  \n" +
            "end \n" +
            "" +
            "" +
            "rule Init \n" +
            "when \n" +
            "then \n" +
            "  X x = new X(); \n" +
            "  don( x, T.class ); \n" +
            "end \n" +
            "" +
            "" +
            "";
    KieBase knowledgeBase = loadKnowledgeBaseFromString(drl);
    TraitFactory.setMode(mode, knowledgeBase);

    KieSession knowledgeSession = knowledgeBase.newKieSession();

    knowledgeSession.fireAllRules();

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

    try {
        knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession(knowledgeSession, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    knowledgeSession.dispose();
}
 
Example 10
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 11
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogicalInsertionsBacking() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsBacking.drl",
                                                        getClass() ),
                  ResourceType.DRL );
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject(kbase);
    KieSession session = createKnowledgeSession(kbase);
    try {
        final Cheese cheese1 = new Cheese( "c",
                                           1 );
        final Cheese cheese2 = new Cheese( cheese1.getType(),
                                           1 );

        FactHandle h1 = session.insert( cheese1 );
        session.fireAllRules();

        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );

        Collection< ? > list = session.getObjects( new ClassObjectFilter( cheese1.getType().getClass() ) );
        assertEquals(1, list.size());
        // probably dangerous, as contains works with equals, not identity
        assertEquals(cheese1.getType(), list.iterator().next());

        FactHandle h2 = session.insert( cheese2 );
        session.fireAllRules();

        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );

        list = session.getObjects( new ClassObjectFilter( cheese1.getType().getClass() ) );
        assertEquals(1, list.size());
        assertEquals(cheese1.getType(), list.iterator().next());

        assertEquals(3, session.getObjects().size());

        h1 = getFactHandle( h1, session );
        session.delete( h1 );
        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );
        session.fireAllRules();
        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );
        list = session.getObjects( new ClassObjectFilter( cheese1.getType().getClass() ) );
        assertEquals(1, list.size(),
                                "cheese-type " + cheese1.getType() + " was deleted, but should not. Backed by cheese2 => type.");
        assertEquals(cheese1.getType(), list.iterator().next(),
                                "cheese-type " + cheese1.getType() + " was deleted, but should not. Backed by cheese2 => type.");

        h2 = getFactHandle( h2, session );
        session.delete( h2 );
        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );
        session.fireAllRules();
        session = getSerialisedStatefulKnowledgeSession( session,
                                                         true );
        list = session.getObjects( new ClassObjectFilter( cheese1.getType().getClass() ) );
        assertEquals(0, list.size(), "cheese-type " + cheese1.getType() +
                    " was not deleted, but should have. Neither  cheese1 => type nor cheese2 => type is true.");
    } finally {
        session.dispose();
    }
}
 
Example 12
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testManyDefeasibles() {
    String drl = "package org.drools.defeasible; " +
                 "declare Fact " +
                 "     fact: String @key " +
                 "end " +
                 " " +
                 "rule init " +
                 "     when " +
                 "     then " +
                 "         insert( new Fact( 'one' ) ); " +
                 "         insert( new Fact( 'two' ) ); " +
                 "         insert( new Fact( 'two' ) ); " +
                 "end " +
                 " " +
                 "rule rule1 " +
                 "     @Defeasible " +
                 "     enabled true " +
                 "     when " +
                 "         Fact( \"one\"; ) " +
                 "     then " +
                 "         System.out.println(\"one causes wibble\"); " +
                 "         insertLogical( new Fact( \"wibble\") ); " +
                 "end " +
                 " " +
                 "rule rule2 " +
                 "     @Defeasible " +
                 "     when " +
                 "         Fact( \"two\"; ) " +
                 "     then " +
                 "         System.out.println(\"two causes wibble\"); " +
                 "         insertLogical( new Fact( \"wibble\") ); " +
                 "end " +
                 " " +
                 "rule rule3 " +
                 "     @Defeater " +
                 "     @Defeats( \"rule2\" ) " +
                 "     when " +
                 "         Fact( \"two\"; ) " +
                 "     then " +
                 "         System.out.println(\"two negates wibble\"); " +
                 "         insertLogical( new Fact( \"wibble\"), \"neg\" ); " +
                 "end";

    KieSession session = getSessionFromString( drl );
    session.fireAllRules();

    FactType factType = session.getKieBase().getFactType( "org.drools.defeasible", "Fact" );
    for ( Object o : session.getObjects( new ClassObjectFilter( factType.getFactClass() ) ) ) {
        if ( "wibble".equals( factType.get( o, "fact" ) ) ) {
            InternalFactHandle handle = (InternalFactHandle) session.getFactHandle( o );
            DefeasibleBeliefSet dbs = (DefeasibleBeliefSet) handle.getEqualityKey().getBeliefSet();

            assertEquals( 3, dbs.size() );
            assertTrue( dbs.isConflicting() );
        }
    }

}
 
Example 13
Source File: TraitMapCoreTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapCoreAliasing(  ) {
    String source = "package org.drools.core.factmodel.traits.test;\n" +
                    "\n" +
                    "import java.util.*;\n" +
                    "import org.drools.core.factmodel.traits.*;\n" +
                    "" +
                    "global List list;\n " +
                    "" +
                    "declare HashMap @Traitable() end \n" +
                    "\n" +
                    "global List list; \n" +
                    "\n" +
                    "declare trait PersonMap\n" +
                    "@propertyReactive  \n" +
                    "   name : String  \n" +
                    "   age  : Integer  @Alias( \"years\" ) \n" +
                    "   eta  : Integer  @Alias( \"years\" ) \n" +
                    "   height : Double  @Alias( \"tall\" ) \n" +
                    "   sen : String @Alias(\"years\") \n " +
                    "end\n" +
                    "\n" +
                    "rule Don  \n" +
                    "when  \n" +
                    "  $m : Map()\n" +
                    "then  \n" +
                    "   don( $m, PersonMap.class );\n" +
                    "\n" +
                    "end\n" +
                    "\n" +
                    "rule Log  \n" +
                    "when  \n" +
                    "   $p : PersonMap( name == \"john\", age > 10 && < 35 )\n" +
                    "then  \n" +
                    "   modify ( $p ) {  \n" +
                    "       setHeight( 184.0 ), \n" +
                    "       setEta( 42 );  \n" +
                    "   }\n" +
                    "   System.out.println(\"Log: \" +  $p );\n" +
                    "end\n" +
                    "" +
                    "\n";

    KieSession ks = loadKnowledgeBaseFromString( source ).newKieSession();
    TraitFactory.setMode( VirtualPropertyMode.MAP, ks.getKieBase() );

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

    Map<String,Object> map = new HashMap<String, Object>(  );
    map.put( "name", "john" );
    map.put( "years", new Integer( 18 ) );
    ks.insert( map );

    ks.fireAllRules();


    for ( Object o : ks.getObjects() ) {
        System.err.println( o );
    }

    assertEquals( 42, map.get( "years" ) );
    assertEquals( 184.0, map.get( "tall" ) );

}
 
Example 14
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled( "Not implemented yet" )
public void testBacktracking() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "import org.kie.api.runtime.rule.Match;\n" +
            "" +

            "declare Foo " +
            "@Abducible " +
            "   id : Integer @key " +
            "end " +

            "query bar( Integer $id ) " +
            "   @Abductive( target=Foo.class, backtracking=true ) " +
            "   $id := Integer() " +
            "end " +

            "rule Check " +
            "when " +
            "   bar( $i ; ) " +
            "then " +
            "   System.out.println( 'YES ' + $i ); " +
            "end " +

            "rule Check2 " +
            "when " +
            "   bar( $i ; ) " +
            "then " +
            "   System.out.println( 'HAH ' + $i ); " +
            "end " +

            "rule Init " +
            "when " +
            "then" +
            "   insert( new Integer( 1 ) ); " +
            "   insert( new Integer( 2 ) ); " +
            "end  " +

            "";

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

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );

    KieSession session = getSessionFromString( droolsSource, kconf );

    session.fireAllRules();

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


}
 
Example 15
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void initializationConflictManagement(VirtualPropertyMode mode) {
    String drl = "package org.drools.test; \n" +
            "" +
            "global java.util.List list; \n" +
            "global java.util.List list2; \n" +
            "" +
            "declare trait A name : String = \"1\" age : Integer = 18 end \n" +
            "declare trait B name : String = \"5\" age : Integer = 50 end \n" +
            "declare trait C extends A,B name : String = \"7\" age : Integer = 37 end \n" +
            "" +
            "declare X @Traitable( logical = true ) name : String end \n" +
            "" +
            "" +
            "rule Init \n" +
            "when \n" +
            "then \n" +
            "  X x = new X(); \n" +
            "  A a = don( x, A.class ); \n" +
            // default 1, from A
            "      list.add( x.getName() ); \n" +
            "      list2.add( a.getAge() ); \n" +
            "  B b = don( x, B.class ); \n" +
            // conflicting defaults A and B, nullify
            "      list.add( x.getName() ); \n" +
            "      list2.add( b.getAge() ); \n" +
            "end \n" +
            "" +
            "rule Later \n" +
            "no-loop \n" +
            "when \n" +
            "  $x : X() \n" +
            "then \n" +
            "  $x.setName( \"xyz\" ); \n" +
            // set to "xyz"
            "      list.add( $x.getName() ); \n" +
            "  C c = don( $x, C.class ); \n" +
            // keep "xyz" even if C has a default
            "      list.add( $x.getName() ); \n" +
            "      list2.add( c.getAge() ); \n" +
            "  $x.setName( null ); \n" +
            "  c.setAge( 99 ); \n" +
            // now revert to default by current most specific type, C
            "      list.add( $x.getName() ); \n" +
            "      list2.add( c.getAge() ); \n" +
            "  c.setName( \"aaa\" ); \n" +
            "  c.setAge( null ); \n" +
            // set to "aaa"
            "      list.add( $x.getName() ); \n" +
            "      list2.add( c.getAge() ); \n" +
            "end \n" +
            "" +
            "";
    KieBase knowledgeBase = loadKnowledgeBaseFromString(drl);
    TraitFactory.setMode(mode, knowledgeBase);

    KieSession knowledgeSession = knowledgeBase.newKieSession();
    ArrayList list = new ArrayList();
    ArrayList list2 = new ArrayList();
    knowledgeSession.setGlobal("list", list);
    knowledgeSession.setGlobal("list2", list2);

    knowledgeSession.fireAllRules();

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

    System.out.println(list);
    System.out.println(list2);
    assertEquals(Arrays.asList("1", null, "xyz", "xyz", "7", "aaa"), list);
    assertEquals(Arrays.asList(18, null, 37, 99, 37), list2);

    try {
        knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession(knowledgeSession, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 16
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCitizenshipExample() {
    // from wikipedia, abductive reasoning example
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "declare CitizenUS " +
            "   name : String @key " +
            "end " +

            "declare Parent " +
            "   parent : String @key " +
            "   child : String @key " +
            "end " +

            "declare BornUS @Abducible name : String @key end " +
            "declare BornOutsideUS @Abducible name : String @key end " +
            "declare ResidentUS @Abducible name : String @key end " +
            "declare NaturalizedUS @Abducible name : String @key end " +
            "declare RegisteredUS @Abducible name : String @key end " +

            "query extractCitizen( CitizenUS $cit ) " +
            "   $cit := CitizenUS() " +
            "end " +

            "query citizen( String $name ) " +
            "   @Abductive( target=CitizenUS.class ) " +
            "   bornUS( $name ; ) " +
            "   or " +
            "   ( bornOutsideUS( $name ; ) and residentUS( $name ; ) and naturalizedUS( $name ; ) ) " +
            "   or " +
            "   ( bornOutsideUS( $name ; ) and Parent( $parent, $name ; ) and CitizenUS( $parent ; ) and registeredUS( $name ; ) ) " +
            "end " +

            "query bornUS( String $name ) @Abductive( target=BornUS.class ) end " +
            "query bornOutsideUS( String $name ) @Abductive( target=BornOutsideUS.class ) end " +
            "query residentUS( String $name ) @Abductive( target=ResidentUS.class ) end " +
            "query naturalizedUS( String $name ) @Abductive( target=NaturalizedUS.class ) end " +
            "query registeredUS( String $name ) @Abductive( target=RegisteredUS.class ) end " +

            "rule Facts " +
            "when " +
            "then " +
            "   insert( new CitizenUS( 'Mary' ) ); " +
            "   insert( new Parent( 'Mary', 'John' ) ); " +
            "   insertLogical( new ResidentUS( 'John' ), 'neg' ); " +
            "end " +

            "rule CheckCitizen " +
            "when " +
            "   $cit : ?citizen( 'John' ; ) " +
            "then " +
            "   System.out.println( 'John is a citizen ' + $cit ); " +
            "end " +

            "";

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

    KieSession session = getSessionFromString( droolsSource );

    session.fireAllRules();

    FactType type = session.getKieBase().getFactType( "org.drools.abductive.test", "CitizenUS" );

    for ( Object o : session.getObjects() ) {
        System.out.println( ">>> " + o );
        if ( o.getClass().equals( type.getFactClass() ) ) {
            InternalFactHandle h = (InternalFactHandle) session.getFactHandle( o );
            String name = (String) type.get( o, "name" );
            if ( "Mary".equals( name ) ) {
                assertNull( h.getEqualityKey().getBeliefSet() );
            } else if ( "John".equals( name ) ) {
                BeliefSet bs = h.getEqualityKey().getBeliefSet();
                assertTrue( bs.isPositive() );
                assertEquals( 2, bs.size() );
            }
        }
    }


}
 
Example 17
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testShadowAliasTraitOnTrait(VirtualPropertyMode mode) {

    String drl = "package org.drools.test; \n" +
            "import org.drools.core.factmodel.traits.*; \n" +
            "import org.drools.core.factmodel.traits.Trait; \n" +
            "" +
            "global java.util.List list; \n" +
            "" +
            "declare trait X \n" +
            "  fld : A \n" +
            "end \n" +
            "" +
            "declare Y \n" +
            "@Traitable( logical = true ) \n" +
            "  fld : B \n" +
            "end \n" +
            "" +
            "declare trait A @Trait( logical=true ) end \n" +
            "declare trait B @Trait( logical=true ) end \n" +
            "declare K @Traitable() end \n" +
            "" +
            "rule Don \n" +
            "when \n" +
            "then \n" +
            "  K k = new K(); \n" +
            "  B b = don( k, B.class ); \n" +
            "  Y y = new Y( b ); \n" +
            "  don( y, X.class ); \n" +
            "end \n" +
            "" +
            "rule Check \n" +
            "salience 1 \n" +
            "when \n" +
            "  $x : Y( fld isA B, fld isA A ) \n" +
            "then \n" +
            "  list.add( \"ok\" ); \n" +
            "end \n" +
            "" +
            "" +
            "";

    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());

    TraitFactory.setMode(mode, kbase);

    KieSession ks = kbase.newKieSession();
    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);

    ks.fireAllRules();
    for (Object o : ks.getObjects()) {
        System.out.println(o);
    }
    assertEquals(Arrays.asList("ok"), list);

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 18
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryTwice() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : String @key \n" +
            "end \n" +

            "query foo1( String $x ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "query foo2( String $x ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "rule R1 " +
            "when " +
            "   $x := ?foo1( \"x\" ; ) " +
            "   $x := ?foo2( \"x\" ; ) " +
            "then " +
            "   System.out.println( 'aaaa' ); " +
            "   list.add( $x ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

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

    session.fireAllRules();

    for ( Object o : session.getObjects() ) {
        System.out.println( ">> " + o );
    }
    System.err.println( list );
    assertEquals( 1, list.size() );
}
 
Example 19
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbductiveLogicUnlinking() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : Integer @key \n" +
            "end \n" +

            "query foo( Integer $i ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "rule R1 " +
            "when " +
            "   foo( 42 ; ) " +
            "   Foo( 42 ; ) " +
            "then " +
            "   list.add( 1 ); " +
            "end \n" +
            "" +
            "rule R2 " +
            "when " +
            "   foo( 24 ; ) " +
            "   String() " +
            "   Foo( 24 ; ) " +
            "then " +
            "   list.add( 2 ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

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

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

    for ( Object o : session.getObjects() ) {
        System.out.println( ">> " + o );
    }
    System.err.println( list );
    assertEquals( Arrays.asList( 1, 2 ), list );
}
 
Example 20
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbductiveLogicWithSelectiveConstructorArgs() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : String @key \n" +
            "   name : String @key \n" +
            "   value : double \n" +
            "   flag : boolean \n" +
            "end \n" +

            "query foo( String $name, double $val, String $x ) \n" +
            "   @Abductive( target=Foo.class, args={ $x, $name } ) \n" +
            "end \n" +

            "rule R3 " +
            "when " +
            "   $f := foo( \"name_test\", 99.0, \"id_0\" ; ) " +
            "then " +
            "   list.add( $f ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

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

    session.fireAllRules();

    FactType type = session.getKieBase().getFactType( "org.drools.abductive.test", "Foo" );
    for ( Object o : session.getObjects() ) {
        if ( type.getFactClass().isInstance( o ) ) {
            assertEquals( "id_0", type.get( o, "id" ) );
            assertEquals( "name_test", type.get( o, "name" ) );
            assertEquals( 0.0, type.get( o, "value" ) );
        }
    }
    System.err.println( list );
}