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

The following examples show how to use org.kie.api.runtime.KieSession#getFactHandle() . 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: UpdateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyCommand() {
    final String str =
            "rule \"sample rule\"\n" +
                    "   when\n" +
                    "   then\n" +
                    "       System.out.println(\"\\\"Hello world!\\\"\");\n" +
                    "end";

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

    final Person p1 = new Person("John", "nobody", 25);
    ksession.execute(CommandFactory.newInsert(p1));
    final FactHandle fh = ksession.getFactHandle(p1);

    final Person p = new Person("Frank", "nobody", 30);
    final List<Setter> setterList = new ArrayList<Setter>();
    setterList.add(CommandFactory.newSetter("age", String.valueOf(p.getAge())));
    setterList.add(CommandFactory.newSetter("name", p.getName()));
    setterList.add(CommandFactory.newSetter("likes", p.getLikes()));

    ksession.execute(CommandFactory.newModify(fh, setterList));
}
 
Example 2
Source File: GetFactHandleCommand.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public FactHandle execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
    InternalFactHandle factHandle = (InternalFactHandle) ksession.getFactHandle( object );
    if ( factHandle != null ){
        InternalFactHandle handle = factHandle.clone();
        if ( disconnected ) {
            handle.disconnect();
        }

        if ( this.outIdentifier != null ) {
            ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult(this.outIdentifier,
                                                                                      handle);
        }

        return handle;
    }
    return null;
}
 
Example 3
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandle() throws Exception {
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("../empty.drl"));
    final KieSession ksession = createKnowledgeSession(kbase);

    for (int i = 0; i < 20; i++) {
        final Object object = new Object();
        ksession.insert(object);
        final FactHandle factHandle = ksession.getFactHandle(object);
        assertNotNull(factHandle);
        assertEquals(object, ksession.getObject(factHandle));
    }
    ksession.dispose();
}
 
Example 4
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandleEqualityBehavior() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EqualityBehaviorOption.EQUALITY);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc));
    final KieSession ksession = createKnowledgeSession(kbase);

    final CheeseEqual cheese = new CheeseEqual("stilton", 10);
    ksession.insert(cheese);
    final FactHandle fh = ksession.getFactHandle(new CheeseEqual("stilton", 10));
    assertNotNull(fh);
}
 
Example 5
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandleIdentityBehavior() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EqualityBehaviorOption.IDENTITY);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc));
    final KieSession ksession = createKnowledgeSession(kbase);

    final CheeseEqual cheese = new CheeseEqual("stilton", 10);
    ksession.insert(cheese);
    final FactHandle fh1 = ksession.getFactHandle(new Cheese("stilton", 10));
    assertNull(fh1);
    final FactHandle fh2 = ksession.getFactHandle(cheese);
    assertNotNull(fh2);
}
 
Example 6
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbducedWithStatus() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Bean.class.getCanonicalName() + ";" +
            "global java.util.Map map; \n" +
            "" +

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

            "rule R1 " +
            "when " +
            "   $x : foo( $v ; ) " +
            "then " +
            "   map.put( $v, $x ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

    KieSession session = getSessionFromString( droolsSource );
    Map map = new HashMap();
    session.setGlobal( "map", map );

    session.insert( 42 );
    session.insert( 11 );
    Bean b = new Bean( 11 );
    session.insert( b );

    session.fireAllRules();

    System.out.println( map );
    assertTrue( map.keySet().containsAll( Arrays.asList( 11, 42 ) ) );
    assertEquals( 2, map.size() );

    Bean b11 = (Bean) map.get( 11 );
    InternalFactHandle f11 = (( InternalFactHandle ) session.getFactHandle( b11 ));
    assertSame( b, b11 );

    Bean b42 = (Bean) map.get( 42 );
    InternalFactHandle f42 = ( InternalFactHandle ) session.getFactHandle( b42 );
    assertEquals( EqualityKey.JUSTIFIED, f42.getEqualityKey().getStatus() );

}
 
Example 7
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 8
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testWMStatusOnNegativeDefeat() {
    String droolsSource =
            "package org.drools.tms.test; " +
            "global java.util.List posList;" +
            "global java.util.List negList;" +

            "declare Bar value : int @key end " +

            "rule Top " +
            "@Defeasible " +
            "@Defeats( 'Sub' ) " +
            "when " +
            "   $i : Integer( this < 10 ) " +
            "then " +
            "   insertLogical( new Bar( $i ) ); " +
            "end " +

            "rule Sub " +
            "@Defeasible " +
            "when " +
            "   $i : Integer() " +
            "then " +
            "   insertLogical( new Bar( $i ), $i > 10 ? 'pos' : 'neg' ); " +
            "end " +

            "rule Sup " +
            "@Defeasible " +
            "@Defeats( 'Sub' ) " +
            "when " +
            "   $i : Integer( this > 10 ) " +
            "then " +
            "   insertLogical( new Bar( $i ), 'neg' ); " +
            "end " +

            "rule React_Pos " +
            "when " +
            "   $b : Bar() " +
            "then " +
            "   posList.add( $b ); " +
            "   System.out.println( ' ++++ ' + $b ); " +
            "end " +

            "rule React_Neg " +
            "when " +
            "   $b : Bar( _.neg )" +
            "then " +
            "   negList.add( $b ); " +
            "   System.out.println( ' ---- ' + $b ); " +
            "end " +

            "";

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

    session.insert( 20 );
    session.insert( 5 );

    session.fireAllRules();

    assertEquals( 1, posList.size() );
    assertEquals( 1, negList.size() );

    Object posBar = posList.get( 0 );
    InternalFactHandle posHandle = (InternalFactHandle) session.getFactHandle( posBar );
    DefeasibleBeliefSet dbs = (DefeasibleBeliefSet) posHandle.getEqualityKey().getBeliefSet();
    assertEquals( 1, dbs.size() );
    assertFalse( dbs.isNegated() );
    assertTrue( dbs.isDecided() );
    assertTrue( dbs.isPositive() );

    assertSame( posHandle, dbs.getFactHandle() );
    assertFalse(posHandle.isNegated());
    assertTrue(  dbs.isDefeasiblyPosProveable());
    assertTrue( session.getObjects().contains( posBar ) );

    Object negBar = negList.get( 0 );

    InternalFactHandle negHandle = (InternalFactHandle) getNegativeHandles(session).get(0);
    dbs = (DefeasibleBeliefSet) negHandle.getEqualityKey().getBeliefSet();
    assertEquals( 1, dbs.size() );
    assertFalse( dbs.isPositive() );
    assertTrue( dbs.isDecided() );
    assertTrue( dbs.isNegated() );

    assertSame( negHandle, dbs.getFactHandle() );
    assertTrue( negHandle.isNegated());

    assertTrue(  dbs.isDefeasiblyNegProveable() );
    assertTrue( session.getObjects().contains( negBar ) );

}
 
Example 9
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 10
Source File: JBRULESTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testJBRULES3323() throws Exception {

    //adding rules. it is important to add both since they reciprocate
    final StringBuilder rule = new StringBuilder();
    rule.append( "package de.orbitx.accumulatetesettest;\n" );
    rule.append( "import java.util.Set;\n" );
    rule.append( "import java.util.HashSet;\n" );
    rule.append( "import org.drools.compiler.Foo;\n" );
    rule.append( "import org.drools.compiler.Bar;\n" );

    rule.append( "rule \"Sub optimal foo parallelism - this rule is causing NPE upon reverse\"\n" );
    rule.append( "when\n" );
    rule.append( "$foo : Foo($leftId : id, $leftBar : bar != null)\n" );
    rule.append( "$fooSet : Set()\n" );
    rule.append( "from accumulate ( Foo(id > $leftId, bar != null && != $leftBar, $bar : bar),\n" );
    rule.append( "collectSet( $bar ) )\n" );
    rule.append( "then\n" );
    rule.append( "//System.out.println(\"ok\");\n" );
    rule.append( "end\n" );

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

    //adding test data
    final Bar[] barList = new Bar[3];
    for (int i = 0; i < barList.length; i++) {
        barList[i] = new Bar(String.valueOf(i));
    }

    final Foo[] fooList = new Foo[4];
    for (int i = 0; i < fooList.length; i++) {
        fooList[i] = new Foo(String.valueOf(i), i == 3 ? barList[2] : barList[i]);
    }

    for (final Foo foo : fooList) {
        ksession.insert(foo);
    }

    //the NPE is caused by exactly this sequence. of course there are more sequences but this
    //appears to be the most short one
    final int[] magicFoos = new int[]{3, 3, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 3, 3, 2, 2, 3, 1, 1};
    final int[] magicBars = new int[]{1, 2, 0, 1, 1, 0, 1, 2, 2, 1, 2, 0, 0, 2, 0, 2, 0, 0, 1};

    //upon final rule firing an NPE will be thrown in org.drools.core.rule.Accumulate
    for (int i = 0; i < magicFoos.length; i++) {
        final Foo tehFoo = fooList[magicFoos[i]];
        final FactHandle fooFactHandle = ksession.getFactHandle(tehFoo);
        tehFoo.setBar(barList[magicBars[i]]);
        ksession.update(fooFactHandle, tehFoo);
        ksession.fireAllRules();
    }
    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 testLogicalInsertionsSelfreferencing() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsSelfreferencing.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 Person b = new Person( "b" );
        final Person a = new Person( "a" );

        session.setGlobal( "b",
                           b );

        FactHandle h1 = session.insert( a );
        session.fireAllRules();
        Collection< ? > list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(2, list.size());
        assertTrue(list.contains(a ));
        assertTrue(list.contains(b ));

        session.delete( h1 );
        session.fireAllRules();
        list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(1, list.size(),
                                "b was deleted, but it should not have. Is backed by b => b being true.");
        assertEquals(b, list.iterator().next(),
                                "b was deleted, but it should not have. Is backed by b => b being true.");

        h1 = session.getFactHandle( b );
        assertSame( ((InternalFactHandle)h1).getEqualityKey().getLogicalFactHandle(), h1);
        ((StatefulKnowledgeSessionImpl)session).getTruthMaintenanceSystem().delete( h1 );
        session.fireAllRules();
        list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(0, list.size());
    } finally {
        session.dispose();
    }
}
 
Example 12
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled("Currently cannot support updates")
//@Disabled("in Java 8, the byte[] generated by serialization are not the same and requires investigation")
public void testLogicalInsertionsUpdateEqual() throws Exception {
    // calling update on a justified FH, states it
    KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsUpdateEqual.drl");
    KieSession ksession = kbase.newKieSession();
    try {
        final Person p = new Person( "person" );
        p.setAge( 2 );
        FactHandle h = ksession.insert( p );
        assertEquals(1, ksession.getObjects().size());

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

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


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

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

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

        final java.lang.reflect.Field field = tms.getClass().getDeclaredField( "equalityKeyMap" );
        field.setAccessible( true );
        final ObjectHashMap m = (ObjectHashMap) field.get( tms );
        field.setAccessible( false );
        assertEquals(0, m.size(), "assertMap should be empty");
    } finally {
        ksession.dispose();
    }
}
 
Example 13
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testInheritAnnotationsInOtherPackage() throws Exception {

    String s1 = "package org.drools.compiler.test.pack1;\n" +
            "global java.util.List list;" +
            "\n" +
            "declare Event\n" +
            "@role(event)" +
            "  id    : int\n" +
            "end\n" +
            "\n" +
            "rule \"X\"\n" +
            "when\n" +
            "  $s1 : Event()\n" +
            "then\n" +
            "  System.out.println( $s1 );\n" +
            "  list.add( $s1.getId() );\n " +
            "end";


    String s2 = "package org.drools.compiler.test.pack2;\n" +
            "\n" +
            "import org.drools.compiler.test.pack1.Event;\n" +
            "global java.util.List list;" +
            "\n" +
            "declare Event end\n" +
            "\n" +
            "declare SubEvent extends Event\n" +
            "end\n" +
            "\n" +
            "rule \"Init\"\n" +
            "when\n" +
            "then\n" +
            "  list.add( 0 );\n" +
            "  insert( new SubEvent( 1 ) );\n" +
            "  insert( new SubEvent( 2 ) );\n" +
            "end\n" +
            "\n" +
            "rule \"Seq\"\n" +
            "when\n" +
            "  $s1 : SubEvent( id == 1 )\n" +
            "  $s2 : SubEvent( id == 2, this after[0,10s] $s1 )\n" +
            "then\n" +
            "  list.add( 3 );\n" +
            "  System.out.println( $s1 + \" after \" + $s1 );\n" +
            "end \n" +
            "\n" +
            "rule \"Seq 2 \"\n" +
            "when\n" +
            "  $s1 : Event( id == 1 )\n" +
            "  $s2 : Event( id == 2, this after[0,10s] $s1 )\n" +
            "then\n" +
            "  list.add( 4 );\n" +
            "  System.out.println( $s1 + \" after II \" + $s1 );\n" +
            "end";


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

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

    kSession.fireAllRules();

    for ( Object o : kSession.getObjects() ) {
        FactHandle h = kSession.getFactHandle( o );
        assertTrue( h instanceof EventFactHandle );
    }

    System.out.println( list );
    assertEquals( 5, list.size() );
    assertTrue( list.contains( 0 ) );
    assertTrue( list.contains( 1 ) );
    assertTrue( list.contains( 2 ) );
    assertTrue( list.contains( 3 ) );
    assertTrue( list.contains( 4 ) );

}