Java Code Examples for org.kie.api.runtime.KieSessionConfiguration#setOption()

The following examples show how to use org.kie.api.runtime.KieSessionConfiguration#setOption() . 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: LengthSlidingWindowTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void checkPrice( String drl, double expectedPrice ) {
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM )
                                         .newKieSession( sessionConfig, null );

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

    ksession.insert( "RHT" );
    ksession.insert( new StockTick( 1L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 2L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 3L, "ABC", 20.0 ) );
    ksession.insert( new StockTick( 4L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 5L, "XYZ", 20.0 ) );
    ksession.insert( new StockTick( 6L, "XYZ", 20.0 ) );
    ksession.insert( new StockTick( 7L, "RHT", 10.0 ) );

    ksession.fireAllRules();

    assertEquals( 1, list.size() );
    assertEquals( expectedPrice, (double)list.get(0), 0.01 );
}
 
Example 2
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private KieSession marsallStatefulKnowledgeSession(KieSession ksession) throws IOException,
                                                                                                   ClassNotFoundException {
    Globals globals = ksession.getGlobals();

    KieBase kbase = ksession.getKieBase();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MarshallerFactory.newMarshaller( kbase ).marshall( out,
                                                       ksession );

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );

    Environment env = EnvironmentFactory.newEnvironment();
    env.set( EnvironmentName.GLOBALS, globals );
    ksession = MarshallerFactory.newMarshaller( kbase ).unmarshall( new ByteArrayInputStream( out.toByteArray() ), ksconf, env );

    return ksession;
}
 
Example 3
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testEventsExpiredInThePast(final String drl) {
    final KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    final KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    final KieBase kieBase = helper.build( EventProcessingOption.STREAM );
    final KieSession kieSession = kieBase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = kieSession.getSessionClock();

    final long currentTime = clock.getCurrentTime();

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 10L, "20ms-30ms"));
    clock.advanceTime(1, TimeUnit.MILLISECONDS);
    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 20L, "20ms-40ms"));

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    assertThat(kieSession.fireAllRules()).isEqualTo(1);
    clock.advanceTime(10, TimeUnit.MILLISECONDS);
    assertThat(kieSession.getObjects()).isEmpty();
}
 
Example 4
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBetaRightExpired() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( id == $Aid )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );

    sessionClock.advanceTime( 20, TimeUnit.MILLISECONDS );
    ksession.insert( new B(1) );

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}
 
Example 5
Source File: FactHandleMarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatefulKnowledgeSessionImpl createWorkingMemory(InternalKnowledgeBase kBase) {
    // WorkingMemoryEntryPoint
    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    SessionConfiguration sessionConf = ((SessionConfiguration) ksconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl(1L, kBase, true, sessionConf, EnvironmentFactory.newEnvironment());
    
    return wm;
}
 
Example 6
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlpha() {
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.insert( new A(2) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals(2, counter.get());
}
 
Example 7
Source File: ActivationIteratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEagerEvaluation() throws Exception {
    String str =
            "package org.simple \n" +
            "rule xxx @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "rule yyy @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = createKnowledgeSession(kbase, conf);

    final List list = new ArrayList();

    AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
        public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
            list.add("activated");
        }
    };
    ksession.addEventListener(agendaEventListener);

    ksession.insert("test");

    assertEquals(2, list.size());
}
 
Example 8
Source File: AbstractBaseTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession createKieSession(boolean serializeKbase, KiePackage... pkg) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList(pkg));
    if( serializeKbase ) { 
        kbase = JbpmSerializationHelper.serializeObject( kbase );
    }

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );
    return kbase.newKieSession(conf, null);
}
 
Example 9
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 10
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallEntryPointsWithSlidingLengthWindow() 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:length(3) 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() );

    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( 3, ((List) list.get( 0 )).size() );
}
 
Example 11
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSnapshotRecoveryScheduledRulesPlain() throws Exception {
    // DROOLS-1537
    String drl = "package com.drools.restore.reproducer\n" +
                 "global java.util.List list;\n" +
                 "global java.util.List list2;\n" +
                 "rule R1\n" +
                 " timer (int: 20s)\n" +
                 " when\n" +
                 "   $m : String( this == \"Hello World1\" )\n" +
                 " then\n" +
                 "   list.add( $m );\n" +
                 "   retract( $m );\n" +
                 "end\n" +
                 "rule R2\n" +
                 " timer (int: 30s)\n" +
                 " when\n" +
                 "   $m : String( this == \"Hello World2\" )\n" +
                 " then\n" +
                 "   list2.add( $m );\n" +
                 "   retract( $m );\n" +
                 "end\n";

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );
    ksconf.setOption( TimedRuleExecutionOption.YES );
    ksconf.setOption(TimerJobFactoryOption.get("trackable"));
    ksconf.setOption(ClockTypeOption.get("pseudo"));

    KieBase kbase1 = new KieHelper().addContent( drl, ResourceType.DRL )
                                    .build( EventProcessingOption.STREAM );
    KieSession ksession = kbase1.newKieSession( ksconf, null );

    PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();

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

    ksession.insert("Hello World1");
    ksession.insert("Hello World2");

    ksession.fireAllRules();
    timeService.advanceTime(10500, TimeUnit.MILLISECONDS);

    KieBase kbase2 = new KieHelper().addContent( drl, ResourceType.DRL )
                                    .build( EventProcessingOption.STREAM );

    ksession = marshallAndUnmarshall( kbase1, kbase2, ksession, ksconf );
    ksession.setGlobal("list", list);
    ksession.setGlobal("list2", list2);

    PseudoClockScheduler timeService2 = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();

    ksession.fireAllRules();

    long accumulatedSleepTime = 0;
    for (int i = 0; i < 6; i++) {
        timeService2.advanceTime(5050, TimeUnit.MILLISECONDS);
        accumulatedSleepTime += 5050;
        assertEquals( i < 1 ? 0 : 1, list.size() );
        assertEquals( i < 3 ? 0 : 1, list2.size() );
    }
}
 
Example 12
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallEntryPointsWithNot() throws Exception {
    String str =
            "package org.domain.test \n" +
                    "import " + getClass().getCanonicalName() + ".*\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" +
                    "   $a : A() from entry-point 'a-ep'\n" +
                    "   not B( this after[0s, 10s] $a) from entry-point 'a-ep'\n" +
                    "then\n" +
                    "list.add( $a );" +
                    "end\n";

    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM );

    KieBase kBase = loadKnowledgeBaseFromString(config, str);

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    KieSession ksession = kBase.newKieSession( ksconf, null );

    List list = new ArrayList();
    ksession.setGlobal( "list", list );
    EntryPoint aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );

    ksession = marsallStatefulKnowledgeSession( ksession );

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

    ksession = marsallStatefulKnowledgeSession( ksession );

    ksession.fireAllRules();

    ksession = marsallStatefulKnowledgeSession( ksession );

    assertEquals( 0,
                  list.size() );
}
 
Example 13
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallEvents() throws Exception {
    String str =
            "import " + getClass().getCanonicalName() + ".*\n" +
                    "declare A\n" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "declare B\n" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "rule one\n" +
                    "when\n" +
                    "   $a : A()\n" +
                    "   B(this after $a)\n" +
                    "then\n" +
                    "insert(new C());" +
                    "end\n";

    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM );

    KieBase kBase = loadKnowledgeBaseFromString(config, str);

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    KieSession ksession = kBase.newKieSession( ksconf, null );

    ksession.insert( new A() );

    ksession = marsallStatefulKnowledgeSession( ksession );

    ksession.insert( new B() );

    ksession = marsallStatefulKnowledgeSession( ksession );

    ksession.fireAllRules();
    assertEquals( 2,
                  ksession.getObjects().size() );
}
 
Example 14
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testFireUntilHaltWithExpiration2() throws InterruptedException {
    String drl =
            "import " + A.class.getCanonicalName() + "\n" +
            "import " + B.class.getCanonicalName() + "\n" +
            "declare A @role( event ) @expires(11ms) end\n" +
            "declare B @role( event ) @expires(11ms) end\n" +
            "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
            "global java.util.concurrent.CountDownLatch fireLatch;\n" +
            "rule R0 when\n" +
            "  $A: A( $Aid : value > 0 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R1 when\n" +
            "  $A: A( $Aid: value > 1 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R2 when\n" +
            "  $A: A( $Aid: value > 2 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R3 when\n" +
            "  $A: A( $Aid: value > 3 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end";

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

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES )
                                         .newKieSession( sessionConfig, null );

    try {
        assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() );

        PseudoClockScheduler sessionClock = ksession.getSessionClock();
        sessionClock.setStartupTime( 0 );

        AtomicInteger counter = new AtomicInteger( 0 );
        ksession.setGlobal( "counter", counter );

        new Thread( () -> ksession.fireUntilHalt() ).start();

        int eventsNr = 5;
        final CountDownLatch fireLatch = new CountDownLatch(eventsNr * 4);
        ksession.setGlobal("fireLatch", fireLatch);
        for ( int i = 0; i < eventsNr; i++ ) {
            ksession.insert( new A( i + 4 ) );
            ksession.insert( new B( i + 4 ) );
            sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
        }

        fireLatch.await();
        assertEquals( eventsNr * 4, counter.get() );
    } finally {
        ksession.halt();
        ksession.dispose();
    }
}
 
Example 15
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEventsExpiration() {
    StringBuilder sb = new StringBuilder( 400 );
    sb.append( "global java.util.List list;\n" );
    sb.append( "import " + MyEvent.class.getCanonicalName() + ";\n" );
    sb.append( "declare MyEvent @role( event ) @expires( 20ms ) @timestamp( timestamp ) end\n" );
    for (int i = 0; i < 10; i++) {
        sb.append( getRuleWithEvent( i ) );
    }

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

    KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES )
                                         .newKieSession( sessionConfig, null );

    assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();
    sessionClock.setStartupTime(0);

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

    for (int i = 0; i < 10; i++) {
        ksession.insert( new MyEvent( i, i*2L ) );
    }

    ksession.fireAllRules();

    assertEquals(10, list.size());
    assertEquals( 10L, ksession.getFactCount() );

    sessionClock.advanceTime( 29, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals( 5L, ksession.getFactCount() );

    sessionClock.advanceTime( 12, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals( 0L, ksession.getFactCount() );
}
 
Example 16
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBeta() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( ($Bid: id <= $Aid) && (id > ($Aid - 1 )))\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );
    ksession.insert( new B(1) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.insert( new A(2) );
    ksession.insert( new B(2) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );

    ksession.fireAllRules();
    assertEquals(2, counter.get());
}
 
Example 17
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEagerEvaluation() {
    String str =
            "package org.simple \n" +
            "@Propagation(EAGER) rule xxx \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "@Propagation(EAGER) rule yyy \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieServices ks = KieServices.Factory.get();

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ForceEagerActivationOption.YES);

    KieSession ksession = new KieHelper()
            .setKieModuleModel(ks.newKieModuleModel()
                                 .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                           LanguageLevelOption.DRL6_STRICT.toString()))
            .addContent(str, ResourceType.DRL)
            .build()
            .newKieSession(conf, null);
    try {
        final List list = new ArrayList();

        AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
            public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
                list.add("activated");
            }
        };
        ksession.addEventListener(agendaEventListener);

        ksession.insert("test");
        assertEquals(2, list.size());
    } finally {
        ksession.dispose();
    }
}
 
Example 18
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSoftExpiration() {
    // DROOLS-1483
    String drl = "import " + ExpiringEventA.class.getCanonicalName() + "\n" +
                 "import " + ExpiringEventB.class.getCanonicalName() + "\n" +
                 "import " + ExpiringEventC.class.getCanonicalName() + "\n" +
                 "rule Ra when\n" +
                 "  $e : ExpiringEventA() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rb when\n" +
                 "  $e : ExpiringEventB() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rc when\n" +
                 "  $e : ExpiringEventC()\n" +
                 "then end\n";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = ksession.getSessionClock();

    ksession.insert( new ExpiringEventA() );
    ksession.insert( new ExpiringEventB() );
    ksession.insert( new ExpiringEventC() );
    ksession.fireAllRules();

    clock.advanceTime( 5, TimeUnit.SECONDS );
    ksession.fireAllRules();

    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=15 -> hard expiration of A
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=25 -> implicit expiration of B
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=35 -> soft expiration of C
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );
}
 
Example 19
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallWithTimedRule() {
    // DROOLS-795
    String drl = "rule \"Rule A Timeout\"\n" +
                 "when\n" +
                 "    String( this == \"ATrigger\" )\n" +
                 "then\n" +
                 "   insert (new String( \"A-Timer\") );\n" +
                 "end\n" +
                 "\n" +
                 "rule \"Timer For rule A Timeout\"\n" +
                 "    timer ( int: 5s )\n" +
                 "when\n" +
                 "   String( this == \"A-Timer\")\n" +
                 "then\n" +
                 "   delete ( \"A-Timer\" );\n" +
                 "   delete ( \"ATrigger\" );\n" +
                 "end\n";

    KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL )
                                   .build( EqualityBehaviorOption.EQUALITY,
                                           DeclarativeAgendaOption.ENABLED,
                                           EventProcessingOption.STREAM );

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( "pseudo" ) );
    KieSession ksession = kbase.newKieSession(sessionConfig, null);

    ksession.insert( "ATrigger" );

    assertEquals( 1, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 2, ksession.getFactCount() );

    SessionPseudoClock clock = ksession.getSessionClock();
    clock.advanceTime( 4, TimeUnit.SECONDS );

    assertEquals( 2, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 2, ksession.getFactCount() );

    ksession = marshallAndUnmarshall( kbase, ksession, sessionConfig);
    clock = ksession.getSessionClock();

    clock.advanceTime( 4, TimeUnit.SECONDS );

    assertEquals( 2, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 0, ksession.getFactCount() );
}
 
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();
}