Search in sources :

Example 16 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testPastEventExipration.

@Test
public void testPastEventExipration() throws InterruptedException {
    // DROOLS-257
    String drl = "package org.test;\n" + "import org.drools.compiler.StockTick;\n " + "" + "global java.util.List list; \n" + "" + "declare StockTick @role(event) @timestamp( time ) @expires( 200ms ) end \n" + "" + "rule \"slidingTimeCount\"\n" + "when\n" + "  accumulate ( $e: StockTick() over window:length(10), $n : count($e) )\n" + "then\n" + "  list.add( $n ); \n" + "  System.out.println( \"Events in last X seconds: \" + $n );\n" + "end" + "";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get("pseudo"));
    // init stateful knowledge session
    KieSession ksession = kbase.newKieSession(sessionConfig, null);
    SessionPseudoClock clock = ksession.getSessionClock();
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);
    long now = 0;
    StockTick event1 = new StockTick(1, "XXX", 1.0, now);
    StockTick event2 = new StockTick(2, "XXX", 1.0, now + 240);
    StockTick event3 = new StockTick(2, "XXX", 1.0, now + 380);
    StockTick event4 = new StockTick(2, "XXX", 1.0, now + 500);
    ksession.insert(event1);
    ksession.insert(event2);
    ksession.insert(event3);
    ksession.insert(event4);
    clock.advanceTime(220, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    clock.advanceTime(400, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    assertEquals(Arrays.asList(3L, 1L), list);
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StockTick(org.drools.compiler.StockTick) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 17 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testExpiredEventWithPendingActivations.

@Test
public void testExpiredEventWithPendingActivations() throws Exception {
    String drl = "package org.drools.drools_usage_pZB7GRxZp64;\n" + "\n" + "declare time_Var\n" + "    @role( event )\n" + "    @expires( 1s )\n" + "    value : Long\n" + "end\n" + "\n" + "declare ExpiringEvent_Var\n" + "    @role( event )\n" + "    @expires( 10s )\n" + "    value : Double\n" + "end\n" + "\n" + "declare window ExpiringEvent_Window1 ExpiringEvent_Var() over window:length(1) end\n" + "\n" + "rule \"Expring variable - Init\"\n" + "activation-group \"ExpiringEvent\"\n" + "    when\n" + "        $t : time_Var($now : Value != null) over window:length(1)\n" + "\n" + "        not ExpiringEvent_Var()\n" + "\n" + "    then\n" + "        System.out.println($now + \" : Init\");\n" + "        insert(new ExpiringEvent_Var(0.0));\n" + "end\n" + "\n" + "rule \"Expiring variable - Rule 1\"\n" + "activation-group \"ExpiringEvent\"\n" + "    when\n" + "        $t : time_Var($now : Value != null) over window:length(1)\n" + "\n" + "        ExpiringEvent_Var(this before $t, $previousValue : Value < 1.0) from window ExpiringEvent_Window1\n" + "\n" + "    then\n" + "        System.out.println($now + \" : Rule 1\");\n" + "        insert(new ExpiringEvent_Var(1.0));\n" + "\n" + "end\n" + "\n" + "rule \"Expiring variable - Rule 2\"\n" + "activation-group \"ExpiringEvent\"\n" + "    when\n" + "        $t : time_Var($now : Value != null) over window:length(1)\n" + "\n" + "        ExpiringEvent_Var(this before $t, $previousValue : Value) from window ExpiringEvent_Window1\n" + "\n" + "    then\n" + "        System.out.println($now + \" : Rule 2\");\n" + "        insert(new ExpiringEvent_Var($previousValue));\n" + "\n" + "end";
    KieServices kieServices = KieServices.Factory.get();
    KieBaseConfiguration kieBaseConf = KieServices.Factory.get().newKieBaseConfiguration();
    kieBaseConf.setOption(EventProcessingOption.STREAM);
    KieBase kieBase = new KieHelper().addContent(drl, ResourceType.DRL).build(kieBaseConf);
    KieSessionConfiguration config = kieServices.newKieSessionConfiguration();
    config.setOption(ClockTypeOption.get("pseudo"));
    KieSession session = kieBase.newKieSession(config, null);
    SessionPseudoClock clock = session.getSessionClock();
    FactType time_VarType = kieBase.getFactType("org.drools.drools_usage_pZB7GRxZp64", "time_Var");
    clock.advanceTime(1472057509000L, TimeUnit.MILLISECONDS);
    Object time_Var = time_VarType.newInstance();
    time_VarType.set(time_Var, "value", 1472057509000L);
    session.insert(time_Var);
    session.fireAllRules();
    for (int i = 0; i < 10; i++) {
        clock.advanceTime(1, TimeUnit.SECONDS);
        Object time_VarP1 = time_VarType.newInstance();
        time_VarType.set(time_VarP1, "value", clock.getCurrentTime());
        session.insert(time_VarP1);
        session.fireAllRules();
    }
    clock.advanceTime(1, TimeUnit.SECONDS);
    session.fireAllRules();
    clock.advanceTime(1, TimeUnit.HOURS);
    Object time_VarP1 = time_VarType.newInstance();
    time_VarType.set(time_VarP1, "value", clock.getCurrentTime());
    session.insert(time_VarP1);
    session.fireAllRules();
    clock.advanceTime(1, TimeUnit.HOURS);
    Object time_VarP2 = time_VarType.newInstance();
    time_VarType.set(time_VarP2, "value", clock.getCurrentTime());
    session.insert(time_VarP2);
    session.fireAllRules();
    clock.advanceTime(1, TimeUnit.HOURS);
    session.fireAllRules();
    // actually should be empty..
    for (Object o : session.getFactHandles()) {
        if (o instanceof EventFactHandle) {
            EventFactHandle eventFactHandle = (EventFactHandle) o;
            assertFalse(eventFactHandle.isExpired());
        }
    }
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) KieHelper(org.kie.internal.utils.KieHelper) EventFactHandle(org.drools.core.common.EventFactHandle) KieServices(org.kie.api.KieServices) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) FactType(org.kie.api.definition.type.FactType) Test(org.junit.Test)

Example 18 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testDeleteOfDeserializedJob.

@Test
public void testDeleteOfDeserializedJob() throws Exception {
    // DROOLS-1660
    String drl = "import " + EventA.class.getCanonicalName() + "\n" + "import java.util.Date\n" + "global java.util.List list\n" + "declare EventA\n" + "	@role(event)\n" + "	@timestamp(timestamp)\n" + "end\n" + "rule test\n" + " when\n" + "  	$event : EventA(value == 1)\n" + "   not(EventA(value == 1, this after [1ms,4m] $event))\n" + " then\n" + "   list.add(\"Fired \"+ $event);\n" + "end\n";
    KieBase kieBase = new KieHelper().addContent(drl, ResourceType.DRL).build(EventProcessingOption.STREAM);
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get("pseudo"));
    KieSession ksession = kieBase.newKieSession(sessionConfig, null);
    List<String> list = new ArrayList<>();
    List<EventA> events = new ArrayList<>();
    events.add(new EventA("2010-01-01 02:00:00", 0));
    events.add(new EventA("2010-01-01 03:00:00", 1));
    events.add(new EventA("2010-01-01 03:01:00", 0));
    events.add(new EventA("2010-01-01 03:02:00", 1));
    events.add(new EventA("2010-01-01 03:03:00", 0));
    events.add(new EventA("2010-01-01 03:04:00", 0));
    events.add(new EventA("2010-01-01 03:05:00", 0));
    events.add(new EventA("2010-01-01 03:06:00", 0));
    events.add(new EventA("2010-01-01 03:07:00", 0));
    // set clock reference
    SessionPseudoClock clock = ksession.getSessionClock();
    clock.advanceTime(events.get(0).getTimestamp().getTime(), TimeUnit.MILLISECONDS);
    byte[] serializedSession = null;
    try {
        Marshaller marshaller = KieServices.Factory.get().getMarshallers().newMarshaller(kieBase);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshall(baos, ksession);
        serializedSession = baos.toByteArray();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    for (EventA current : events) {
        KieSession ksession2 = null;
        Marshaller marshaller = KieServices.Factory.get().getMarshallers().newMarshaller(kieBase);
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(serializedSession);
            ksession2 = marshaller.unmarshall(bais, sessionConfig, null);
            ksession2.setGlobal("list", list);
            clock = ksession2.getSessionClock();
            bais.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long currTime = clock.getCurrentTime();
        long nextTime = current.getTimestamp().getTime();
        while (currTime <= (nextTime - 1000)) {
            clock.advanceTime(1000, TimeUnit.MILLISECONDS);
            ksession2.fireAllRules();
            currTime += 1000;
        }
        long diff = nextTime - currTime;
        if (diff > 0) {
            clock.advanceTime(diff, TimeUnit.MILLISECONDS);
        }
        ksession2.insert(current);
        ksession2.fireAllRules();
        // serialize knowledge session
        try {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            marshaller.marshall(baos, ksession2);
            serializedSession = baos.toByteArray();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        ksession2.dispose();
    }
    assertEquals(1, list.size());
    assertEquals("Fired EventA at 2010-01-01 03:02:00", list.get(0));
}
Also used : Marshaller(org.kie.api.marshalling.Marshaller) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 19 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testEventExpiration4.

@Test(timeout = 10000)
public void testEventExpiration4() throws Exception {
    // read in the source
    final KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBase(conf, "test_CEP_EventExpiration4.drl");
    final KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sconf.setOption(ClockTypeOption.get("pseudo"));
    KieSession ksession = createKnowledgeSession(kbase, sconf);
    EntryPoint eventStream = ksession.getEntryPoint("Event Stream");
    SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    final List results = new ArrayList();
    ksession.setGlobal("results", results);
    EventFactHandle handle1 = (EventFactHandle) eventStream.insert(new StockTick(1, "ACME", 50, System.currentTimeMillis(), 3));
    ksession.fireAllRules();
    clock.advanceTime(11, TimeUnit.SECONDS);
    /**
     * clock.advance() will put the event expiration in the queue to be executed,
     *            but it has to wait for a "thread" to do that
     *            so we fire rules again here to get that
     *            alternative could run fireUntilHalt() *
     */
    ksession.fireAllRules();
    assertTrue(results.size() == 1);
    assertTrue(handle1.isExpired());
    assertFalse(ksession.getFactHandles().contains(handle1));
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) StockTick(org.drools.compiler.StockTick) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) EventFactHandle(org.drools.core.common.EventFactHandle) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 20 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testIdleTime.

// @Test(timeout=10000) @Ignore
// public void testTransactionCorrelation() throws Exception {
// // read in the source
// final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_TransactionCorrelation.drl" ) );
// final RuleBase ruleBase = loadRuleBase( reader );
// 
// final WorkingMemory wm = ruleBase.newStatefulSession();
// final List results = new ArrayList();
// 
// wm.setGlobal( "results",
// results );
// 
// 
// }
@Test(timeout = 10000)
public void testIdleTime() throws Exception {
    // read in the source
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newInputStreamResource(getClass().getResourceAsStream("test_CEP_SimpleEventAssertion.drl")), ResourceType.DRL);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("pseudo"));
    StatefulKnowledgeSessionImpl session = (StatefulKnowledgeSessionImpl) createKnowledgeSession(kbase, conf);
    SessionPseudoClock clock = (SessionPseudoClock) session.getSessionClock();
    final List results = new ArrayList();
    session.setGlobal("results", results);
    StockTickInterface tick1 = new StockTick(1, "DROO", 50, 10000);
    StockTickInterface tick2 = new StockTick(2, "ACME", 10, 10010);
    StockTickInterface tick3 = new StockTick(3, "ACME", 10, 10100);
    StockTickInterface tick4 = new StockTick(4, "DROO", 50, 11000);
    assertEquals(0, session.getIdleTime());
    InternalFactHandle handle1 = (InternalFactHandle) session.insert(tick1);
    clock.advanceTime(10, TimeUnit.SECONDS);
    assertEquals(10000, session.getIdleTime());
    InternalFactHandle handle2 = (InternalFactHandle) session.insert(tick2);
    assertEquals(0, session.getIdleTime());
    clock.advanceTime(15, TimeUnit.SECONDS);
    assertEquals(15000, session.getIdleTime());
    clock.advanceTime(15, TimeUnit.SECONDS);
    assertEquals(30000, session.getIdleTime());
    InternalFactHandle handle3 = (InternalFactHandle) session.insert(tick3);
    assertEquals(0, session.getIdleTime());
    clock.advanceTime(20, TimeUnit.SECONDS);
    InternalFactHandle handle4 = (InternalFactHandle) session.insert(tick4);
    clock.advanceTime(10, TimeUnit.SECONDS);
    assertNotNull(handle1);
    assertNotNull(handle2);
    assertNotNull(handle3);
    assertNotNull(handle4);
    assertTrue(handle1.isEvent());
    assertTrue(handle2.isEvent());
    assertTrue(handle3.isEvent());
    assertTrue(handle4.isEvent());
    assertEquals(10000, session.getIdleTime());
    session.fireAllRules();
    assertEquals(0, session.getIdleTime());
    assertEquals(2, ((List) session.getGlobal("results")).size());
}
Also used : StockTickInterface(org.drools.compiler.StockTickInterface) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StockTick(org.drools.compiler.StockTick) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Aggregations

SessionPseudoClock (org.kie.api.time.SessionPseudoClock)74 Test (org.junit.Test)66 KieSession (org.kie.api.runtime.KieSession)52 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)39 KieBase (org.kie.api.KieBase)37 ArrayList (java.util.ArrayList)30 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)20 MessageEvent (org.drools.testcoverage.common.model.MessageEvent)15 EntryPoint (org.kie.api.runtime.rule.EntryPoint)15 StockTick (org.drools.compiler.StockTick)14 Message (org.drools.testcoverage.common.model.Message)14 List (java.util.List)13 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)13 NamedEntryPoint (org.drools.core.common.NamedEntryPoint)12 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)11 StockTick (org.drools.modelcompiler.domain.StockTick)10 OrderEvent (org.drools.compiler.OrderEvent)6 QueryResults (org.kie.api.runtime.rule.QueryResults)4 KieHelper (org.kie.internal.utils.KieHelper)4 StockTickInterface (org.drools.compiler.StockTickInterface)3