Java Code Examples for org.drools.core.impl.KnowledgeBaseFactory#newKnowledgeBaseConfiguration()

The following examples show how to use org.drools.core.impl.KnowledgeBaseFactory#newKnowledgeBaseConfiguration() . 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: FireUntilHaltAccumulateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors().toString());
    }
    final KieBaseConfiguration config =
            KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM);

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(config);
    kbase.addPackages(kbuilder.getKnowledgePackages());

    final KieSessionConfiguration sessionConfig =
            KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ));

    this.statefulSession = kbase.newKieSession(sessionConfig, null);
    this.stockFactory = new StockFactory(kbase);
}
 
Example 2
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllLinkedInWithJoinNodesOnly() {
    setUp( JOIN_NODE );

    assertEquals( JoinNode.class, n3.getClass() ); // make sure it created JoinNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    DefaultFactHandle f1 = (DefaultFactHandle) ksession.insert( "test1" );
    n3.assertObject( f1, context, ksession );

    BetaMemory bm = (BetaMemory) ksession.getNodeMemory( n3 );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n4.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n5.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n6.assertObject( f1, context, ksession );
    assertTrue( bm.getSegmentMemory().isSegmentLinked() ); // only after all 4 nodes are populated, is the segment linked in
}
 
Example 3
Source File: RuleUnlinkingWithSegmentMemoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleSegmentsAllLinkedTestMasks() {
    setUp( JOIN_NODE );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl( 1L, kBase );
    
    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn1 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 1, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn2 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 3, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn3 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 7, rs.getAllLinkedMaskTest() );
}
 
Example 4
Source File: FailureOnRemovalTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBaseConfiguration createKnowledgeBaseConfiguration(boolean shareBetaNodes) {
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( SequentialOption.NO );
    kconf.setOption( ShareAlphaNodesOption.YES );
    kconf.setOption( shareBetaNodes ? ShareBetaNodesOption.YES : ShareBetaNodesOption.NO );
    return kconf;
}
 
Example 5
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieSession getSessionFromString( String drlString) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newByteArrayResource(drlString.getBytes()),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    KieBaseConfiguration kieBaseConfiguration = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieBaseConfiguration.setOption( EqualityBehaviorOption.EQUALITY );

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase( kieBaseConfiguration );
    kBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

        assertSame(jfh1, session.getFactHandle("f1") );
    } finally {
        session.dispose();
    }
}
 
Example 10
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogicalThenStatedShadowSingleOccurance() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

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

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


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

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

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

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

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

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

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

        EqualityKey key = jfh1.getEqualityKey();
        assertSame( fh1.getEqualityKey(), key );
        assertNotSame( fh1, jfh1 );

        assertEquals(2, key.size());
        assertSame( jfh1,  key.getLogicalFactHandle() );

        // Make sure f1 only occurs once
        assertEquals(1, list.size());
        assertEquals("f1", list.get(0 ));
    } finally {
        session.dispose();
    }
}
 
Example 11
Source File: NullTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBindingToNullFieldWithEquality() {
    // JBRULES-3396
    final String str = "package org.drools.compiler.test; \n" +
            "\n" +
            "global java.util.List list;" +
            "\n" +
            "declare Bean\n" +
            "  id    : String @key\n" +
            "  field : String\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"Init\"\n" +
            "when  \n" +
            "then\n" +
            "  insert( new Bean( \"x\" ) );\n" +
            "end\n" +
            "\n" +
            "rule \"Check\"\n" +
            "when\n" +
            "  $b : Bean( $fld : field )\n" +
            "then\n" +
            "  System.out.println( $fld );\n" +
            "  list.add( \"OK\" ); \n" +
            "end";

    final KieBaseConfiguration kbConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbConf.setOption(EqualityBehaviorOption.EQUALITY);

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

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

    ksession.fireAllRules();
    assertTrue(list.contains("OK"));

    ksession.dispose();
}
 
Example 12
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void setUp(int... type) {
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    buildContext = new BuildContext( kBase );

    PropagationContextFactory pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    context = pctxFactory.createPropagationContext(0, PropagationContext.Type.INSERTION, null, null, null);

    MockTupleSource mockTupleSource = new MockTupleSource( 9 );

    rule1 = new RuleImpl( "rule1" );
    rule2 = new RuleImpl( "rule2" );
    rule3 = new RuleImpl( "rule3" );
    
    ObjectTypeNode otn = new ObjectTypeNode( 3, null, new ClassObjectType( String.class ), buildContext );
    liaNode = new LeftInputAdapterNode(4, otn, buildContext );
    
    // 3, 4, 5, 6 are in same shared segment
    n1 = createBetaNode( 10, type[0], liaNode );
    n2 = createBetaNode( 11, type[1], n1 );
    RuleTerminalNode rtn1 = new RuleTerminalNode( 18,
                                                  n2,
                                                  rule1,
                                                  rule1.getLhs(),
                                                  0,
                                                  buildContext );
    rtn1.attach(buildContext);
    
    
    n3 = createBetaNode( 12, type[2], n1 );
    n4 = createBetaNode( 13, type[3], n3 );
    n5 = createBetaNode( 14, type[4], n4 );
    n6 = createBetaNode( 15, type[5], n5 ); 
    RuleTerminalNode rtn2 = new RuleTerminalNode( 19,
                                                  n6,
                                                  rule2,
                                                  rule2.getLhs(),
                                                  0,
                                                  buildContext );
    rtn2.attach(buildContext);

    n7 = createBetaNode( 16, type[6], n6 );
    n8 = createBetaNode( 17, type[7], n7 );
    RuleTerminalNode rtn3 = new RuleTerminalNode( 20,
                                                  n8,
                                                  rule3,
                                                  rule3.getLhs(),
                                                  0,
                                                  buildContext );
    rtn3.attach(buildContext);
    
    // n1 -> n2 -> r1
    //  \ 
    //   n3 -> n4 -> n5 -> n6 -> r2
    //                      \
    //                      n7 -> n8 -> r3          
    
    n1.addAssociation( rule1 );
    n1.addAssociation( rule2 );
    n1.addAssociation( rule3 );
    n2.addAssociation( rule1 );
    n2.addAssociation( rule2 );
    n2.addAssociation( rule3 );

    n3.addAssociation( rule2 );
    n3.addAssociation( rule3 );
    n4.addAssociation( rule2 );
    n4.addAssociation( rule3 );
    n5.addAssociation( rule2 );
    n5.addAssociation( rule3 );
    n6.addAssociation( rule2 );
    n6.addAssociation( rule3 );

    n7.addAssociation( rule3 );
    n8.addAssociation( rule3 );
}
 
Example 13
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test @Disabled("beta4 phreak")
public void testMarshallEntryPointsWithSlidingTimeWindow() throws Exception {
    String str =
            "package org.domain.test \n" +
                    "import " + getClass().getCanonicalName() + ".*\n" +
                    "import java.util.List\n" +
                    "global java.util.List list\n" +
                    "declare A\n" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "declare B\n" +
                    "" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "" +
                    "rule a1\n" +
                    "when\n" +
                    "   $l : List() from collect( A()  over window:time(30s) from entry-point 'a-ep') \n" +
                    "then\n" +
                    "   list.add( $l );" +
                    "end\n";

    KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption( EventProcessingOption.STREAM );
    final KieBase kbase = loadKnowledgeBaseFromString( conf, str );

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    KieSession ksession = createKnowledgeSession(kbase, ksconf);

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

    EntryPoint aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    list.clear();
    ksession.fireAllRules();
    ksession = marsallStatefulKnowledgeSession( ksession );
    assertEquals( 2, ((List) list.get( 0 )).size() );

    PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();
    timeService.advanceTime( 15, TimeUnit.SECONDS );
    ksession = marsallStatefulKnowledgeSession( ksession );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    list.clear();
    ksession.fireAllRules();
    ksession = marsallStatefulKnowledgeSession( ksession );
    assertEquals( 4, ((List) list.get( 0 )).size() );

    timeService = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();
    timeService.advanceTime( 20, TimeUnit.SECONDS );
    ksession = marsallStatefulKnowledgeSession( ksession );

    list.clear();
    ksession.fireAllRules();
    assertEquals( 2, ((List) list.get( 0 )).size() );
}
 
Example 14
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 15
Source File: MultithreadTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testRaceOnAccumulateNodeSimple() throws InterruptedException {

    final String drl = "package org.drools.integrationtests;\n" +
            "" +
            "import " + Server.class.getCanonicalName() + ";\n" +
            "import " + IntEvent.class.getCanonicalName() + ";\n" +
            "" +
            "declare IntEvent\n" +
            "  @role ( event )\n" +
            "  @expires( 15s )\n" +
            "end\n" +
            "\n" +
            "" +
            "rule \"average temperature\"\n" +
            "when\n" +
            "  $s : Server (hostname == \"hiwaesdk\")\n" +
            " $avg := Number( ) from accumulate ( " +
            "      IntEvent ( $temp : data ) over window:length(10) from entry-point ep01; " +
            "      average ($temp)\n" +
            "  )\n" +
            "then\n" +
            "  $s.avgTemp = $avg.intValue();\n" +
            "  System.out.println( $avg );\n" +
            "end\n" +
            "\n";

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

    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);

    final KieSession session = kbase.newKieSession();
    final EntryPoint ep01 = session.getEntryPoint("ep01");

    final Runner t = new Runner(session);
    t.start();
    try {
        Thread.sleep(1000);

        final Server hiwaesdk = new Server("hiwaesdk");
        session.insert(hiwaesdk);
        final long LIMIT = 20;

        for (long i = LIMIT; i > 0; i--) {
            ep01.insert(new IntEvent((int) i)); //Thread.sleep (0x1); }
            if (i % 1000 == 0) {
                System.out.println(i);
            }
        }
        Thread.sleep(1000);
    } finally {
        session.halt();
        session.dispose();
    }

    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }
}
 
Example 16
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLiaNodeLinking() {
    setUp( JOIN_NODE );
    // Initialise from lian
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    SegmentUtilities.createSegmentMemory( liaNode, ksession );
    
    InternalFactHandle fh1 = (InternalFactHandle) ksession.insert( "str1" );
    n1.assertObject( fh1, context, ksession );
    
    LiaNodeMemory liaMem = (LiaNodeMemory) ksession.getNodeMemory( liaNode );
    assertEquals( 1, liaMem.getNodePosMaskBit() );
    assertEquals( 3, liaMem.getSegmentMemory().getAllLinkedMaskTest() ); 
    
    BetaMemory bm1 = (BetaMemory) ksession.getNodeMemory( n1 );
    assertEquals( 2, bm1.getNodePosMaskBit() );
    assertEquals( 3, bm1.getSegmentMemory().getAllLinkedMaskTest() );     
    
    // still unlinked
    assertFalse( liaMem.getSegmentMemory().isSegmentLinked() );
    
    // now linked
    InternalFactHandle fh2 = (InternalFactHandle) ksession.insert( "str2" );
    liaNode.assertObject( fh2, context, ksession );
    assertTrue( liaMem.getSegmentMemory().isSegmentLinked() );
    
    // test unlink after one retract
    liaNode.retractLeftTuple( fh2.getFirstLeftTuple(), context, ksession );
    assertFalse( liaMem.getSegmentMemory().isSegmentLinked() );
    
    // check counter, after multiple asserts
    InternalFactHandle fh3 = (InternalFactHandle) ksession.insert( "str3" );
    InternalFactHandle fh4 = (InternalFactHandle) ksession.insert( "str4" );
    liaNode.assertObject( fh3, context, ksession );
    liaNode.assertObject( fh4, context, ksession );
    
    assertTrue( liaMem.getSegmentMemory().isSegmentLinked() );
    
    liaNode.retractLeftTuple( fh3.getFirstLeftTuple(), context, ksession );
    assertTrue( liaMem.getSegmentMemory().isSegmentLinked() );

    liaNode.retractLeftTuple( fh4.getFirstLeftTuple(), context, ksession );
    assertFalse( liaMem.getSegmentMemory().isSegmentLinked() );
}
 
Example 17
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected KieBase getKnowledgeBase() {
    KieBaseConfiguration kBaseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    return getKnowledgeBase(kBaseConfig);
}
 
Example 18
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCancelMultipleActivations() {
    String str = "package org.domain.test\n" +
            "import " + Match.class.getName() + "\n" +
            "global java.util.List list\n" +
            "rule sales1 @department('sales')\n" +
            "when\n" +
            "    String( this == 'fireRules' )\n" +
            "then\n" +
            "    list.add(\"sales1\");\n" +
            "end\n" +
            "\n" +
            "rule sales2 @department('sales') \n" +
            "when\n" +
            "    String( this == 'fireRules' )\n" +
            "then\n" +
            "    list.add(\"sales2\");\n" +
            "end\n" +
            "\n" +
            "rule salesCancel @activationListener('direct')\n" +
            "when\n" +
            "    $i : Match( department == 'sales' )\n" +
            "then\n" +
            "    kcontext.cancelMatch($i);\n" +
            "end";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);

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

    ksession.insert("fireRules");
    ksession.fireAllRules();
    System.out.println(list);
    assertEquals(0, list.size());

    ksession.dispose();
}
 
Example 19
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicBlockOnAnnotation() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";
    str += "rule rule1 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";
    str += "rule rule2 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";
    str += "rule rule3 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";
    str += "rule blockerAllSalesRules @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go2' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.insert( "go1" );
    FactHandle go2 = ksession.insert( "go2" );        
    ksession.fireAllRules();
    
    assertEquals( 3,
                  list.size() );
    assertTrue( list.contains( "rule1:go2" ) );
    assertTrue( list.contains( "rule2:go2" ) );
    assertTrue( list.contains( "rule3:go2" ) );

    list.clear();
    ksession.retract( go2 );
    ksession.fireAllRules();

    assertEquals( 3,
                  list.size() );
    assertTrue( list.contains( "rule1:go1" ) );
    assertTrue( list.contains( "rule2:go1" ) );
    assertTrue( list.contains( "rule3:go1" ) );

    ksession.dispose();
}
 
Example 20
Source File: WindowTest.java    From kogito-runtimes with Apache License 2.0 3 votes vote down vote up
@BeforeEach
public void initialization() {
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();

    kfs.write("src/main/resources/kbase1/window_test.drl", drl);

    KieBuilder kbuilder = KieServices.Factory.get().newKieBuilder(kfs);

    kbuilder.buildAll();

    List<Message> res = kbuilder.getResults().getMessages(Level.ERROR);

    assertEquals(0, res.size(), res.toString());

    KieBaseConfiguration kbconf = KnowledgeBaseFactory
            .newKnowledgeBaseConfiguration();

    kbconf.setOption(EventProcessingOption.STREAM);

    KieBase kbase = KieServices.Factory.get()
                               .newKieContainer(kbuilder.getKieModule().getReleaseId())
                               .newKieBase(kbconf);

    KieSessionConfiguration ksconfig = KnowledgeBaseFactory
            .newKnowledgeSessionConfiguration();
    ksconfig.setOption(ClockTypeOption.get("pseudo"));

    ksession = kbase.newKieSession(ksconfig, null);

    clock = ksession.getSessionClock();
}