Search in sources :

Example 51 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class LinkingTest method testNotNodes2.

@Test
public void testNotNodes2() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "import " + F.class.getCanonicalName() + "\n";
    str += "import " + G.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";
    str += "rule rule1 when \n";
    str += "   $a : A() \n";
    str += "   not B() \n";
    str += "   $c : C() \n";
    str += "then \n";
    str += "  list.add( 'x' ); \n";
    str += "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);
    ObjectTypeNode botn = getObjectTypeNode(kbase, A.class);
    ObjectTypeNode cotn = getObjectTypeNode(kbase, A.class);
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);
    for (int i = 0; i < 3; i++) {
        wm.insert(new A(i));
    }
    for (int i = 0; i < 3; i++) {
        wm.insert(new C(i));
    }
    wm.fireAllRules();
    assertEquals(9, list.size());
    wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    list = new ArrayList();
    wm.setGlobal("list", list);
    for (int i = 0; i < 3; i++) {
        wm.insert(new A(i));
    }
    FactHandle fh = wm.insert(new B(1));
    for (int i = 0; i < 3; i++) {
        wm.insert(new C(i));
    }
    wm.fireAllRules();
    assertEquals(0, list.size());
    wm.retract(fh);
    wm.fireAllRules();
    assertEquals(9, list.size());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ArrayList(java.util.ArrayList) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) ArrayList(java.util.ArrayList) List(java.util.List) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 52 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class CepEspTest method testIdleTimeAndTimeToNextJob.

@Test(timeout = 10000)
public void testIdleTimeAndTimeToNextJob() throws Exception {
    // read in the source
    KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBase(conf, "test_CEP_SimpleTimeWindow.drl");
    KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sconf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) createKnowledgeSession(kbase, sconf);
    WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger((WorkingMemory) wm);
    File testTmpDir = new File("target/test-tmp/");
    testTmpDir.mkdirs();
    logger.setFileName("target/test-tmp/testIdleTimeAndTimeToNextJob-audit");
    try {
        List results = new ArrayList();
        wm.setGlobal("results", results);
        // how to initialize the clock?
        // how to configure the clock?
        SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock();
        clock.advanceTime(5, // 5 seconds
        TimeUnit.SECONDS);
        // there is no next job, so returns -1
        assertEquals(-1, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("1", "customer A", 70));
        wm.fireAllRules();
        assertEquals(0, wm.getIdleTime());
        // now, there is a next job in 30 seconds: expire the event
        assertEquals(30000, wm.getTimeToNextJob());
        wm.fireAllRules();
        assertEquals(1, results.size());
        assertEquals(70, ((Number) results.get(0)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // next job is in 20 seconds: expire the event
        assertEquals(20000, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("2", "customer A", 60));
        wm.fireAllRules();
        assertEquals(2, results.size());
        assertEquals(65, ((Number) results.get(1)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // next job is in 10 seconds: expire the event
        assertEquals(10000, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("3", "customer A", 50));
        wm.fireAllRules();
        assertEquals(3, results.size());
        assertEquals(60, ((Number) results.get(2)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // advancing clock time will cause events to expire
        assertEquals(0, wm.getIdleTime());
        // next job is in 10 seconds: expire another event
        // assertEquals( 10000, iwm.getTimeToNextJob());
        wm.insert(new OrderEvent("4", "customer A", 25));
        wm.fireAllRules();
        // first event should have expired, making average under the rule threshold, so no additional rule fire
        assertEquals(3, results.size());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        wm.insert(new OrderEvent("5", "customer A", 70));
        assertEquals(0, wm.getIdleTime());
        // wm  = SerializationHelper.serializeObject(wm);
        wm.fireAllRules();
        // still under the threshold, so no fire
        assertEquals(3, results.size());
    } finally {
        logger.writeToDisk();
    }
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) WorkingMemoryFileLogger(org.drools.core.audit.WorkingMemoryFileLogger) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) OrderEvent(org.drools.compiler.OrderEvent) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 53 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class FactHandleMarshallingTest method backwardsCompatibleEventFactHandleTest.

@Test
public void backwardsCompatibleEventFactHandleTest() throws IOException, ClassNotFoundException {
    InternalKnowledgeBase kBase = createKnowledgeBase();
    StatefulKnowledgeSessionImpl wm = createWorkingMemory(kBase);
    InternalFactHandle factHandle = createEventFactHandle(wm, kBase);
    // marshall/serialize workItem
    byte[] byteArray;
    {
        ObjectMarshallingStrategy[] strats = new ObjectMarshallingStrategy[] { MarshallerFactory.newSerializeMarshallingStrategy(), new MarshallerProviderImpl().newIdentityMarshallingStrategy() };
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MarshallerWriteContext outContext = new MarshallerWriteContext(baos, null, null, null, new ObjectMarshallingStrategyStoreImpl(strats), true, true, null);
        OldOutputMarshallerMethods.writeFactHandle_v1(outContext, (ObjectOutputStream) outContext, outContext.objectMarshallingStrategyStore, 2, factHandle);
        outContext.close();
        byteArray = baos.toByteArray();
    }
    // unmarshall/deserialize workItem
    InternalFactHandle newFactHandle;
    {
        // Only put serialization strategy in
        ObjectMarshallingStrategy[] newStrats = new ObjectMarshallingStrategy[] { MarshallerFactory.newSerializeMarshallingStrategy() };
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
        MarshallerReaderContext inContext = new MarshallerReaderContext(bais, null, null, new ObjectMarshallingStrategyStoreImpl(newStrats), Collections.EMPTY_MAP, true, true, null);
        inContext.wm = wm;
        newFactHandle = InputMarshaller.readFactHandle(inContext);
        inContext.close();
    }
    assertTrue("Serialized FactHandle not the same as the original.", compareInstances(factHandle, newFactHandle));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) MarshallerProviderImpl(org.drools.core.marshalling.impl.MarshallerProviderImpl) MarshallerWriteContext(org.drools.core.marshalling.impl.MarshallerWriteContext) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InternalFactHandle(org.drools.core.common.InternalFactHandle) ObjectOutputStream(java.io.ObjectOutputStream) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) ObjectMarshallingStrategyStoreImpl(org.drools.core.marshalling.impl.ObjectMarshallingStrategyStoreImpl) Test(org.junit.Test)

Example 54 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class ParallelEvaluationTest method testFireUntilHaltWithAsyncInsert.

@Test(timeout = 10000L)
public void testFireUntilHaltWithAsyncInsert() {
    StringBuilder sb = new StringBuilder(400);
    sb.append("global java.util.List list;\n");
    for (int i = 0; i < 10; i++) {
        sb.append(getRule(i, ""));
    }
    KieSession ksession = new KieHelper().addContent(sb.toString(), ResourceType.DRL).build(MultithreadEvaluationOption.YES).newKieSession();
    assertTrue(((InternalWorkingMemory) ksession).getAgenda().isParallelAgenda());
    StatefulKnowledgeSessionImpl session = (StatefulKnowledgeSessionImpl) ksession;
    CountDownLatch done = new CountDownLatch(1);
    DebugList<Integer> list = new DebugList<Integer>();
    list.onItemAdded = (l -> {
        if (l.size() == 10) {
            ksession.halt();
            done.countDown();
        }
    });
    ksession.setGlobal("list", list);
    new Thread(() -> ksession.fireUntilHalt()).start();
    for (int i = 0; i < 10; i++) {
        session.insertAsync(i);
        session.insertAsync("" + i);
    }
    try {
        done.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    assertEquals(10, list.size());
}
Also used : Arrays(java.util.Arrays) ClassObjectType(org.drools.core.base.ClassObjectType) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) EntryPointId(org.drools.core.rule.EntryPointId) MultithreadEvaluationOption(org.kie.internal.conf.MultithreadEvaluationOption) Callable(java.util.concurrent.Callable) ClockType(org.drools.core.ClockType) ResourceType(org.kie.api.io.ResourceType) ArrayList(java.util.ArrayList) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompositePartitionAwareObjectSinkAdapter(org.drools.core.reteoo.CompositePartitionAwareObjectSinkAdapter) EntryPointNode(org.drools.core.reteoo.EntryPointNode) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) ExecutorService(java.util.concurrent.ExecutorService) KieHelper(org.kie.internal.utils.KieHelper) EventProcessingOption(org.kie.api.conf.EventProcessingOption) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) DebugList(org.drools.compiler.util.debug.DebugList) Test(org.junit.Test) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler) Executors(java.util.concurrent.Executors) FactHandle(org.kie.api.runtime.rule.FactHandle) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ClockTypeOption(org.kie.api.runtime.conf.ClockTypeOption) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KnowledgeBaseFactory(org.drools.core.impl.KnowledgeBaseFactory) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) Assert(org.junit.Assert) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) KieHelper(org.kie.internal.utils.KieHelper) CountDownLatch(java.util.concurrent.CountDownLatch) DebugList(org.drools.compiler.util.debug.DebugList) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) KieSession(org.kie.api.runtime.KieSession) Test(org.junit.Test)

Example 55 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class ParallelEvaluationTest method testWithAsyncInsertions.

@Test(timeout = 10000L)
public void testWithAsyncInsertions() {
    StringBuilder sb = new StringBuilder(4000);
    sb.append("global java.util.List list;\n");
    int ruleNr = 200;
    for (int i = 0; i < ruleNr; i++) {
        sb.append(getRule(i, "insertAsync( $i + 10 );\ninsertAsync( \"\" + ($i + 10) );\n"));
    }
    KieSession ksession = new KieHelper().addContent(sb.toString(), ResourceType.DRL).build(MultithreadEvaluationOption.YES).newKieSession();
    assertTrue(((InternalWorkingMemory) ksession).getAgenda().isParallelAgenda());
    StatefulKnowledgeSessionImpl session = (StatefulKnowledgeSessionImpl) ksession;
    List<Integer> list = new DebugList<Integer>();
    ksession.setGlobal("list", list);
    for (int i = 0; i < 10; i++) {
        session.insertAsync(i);
        session.insertAsync("" + i);
    }
    ksession.fireAllRules();
    assertEquals(ruleNr, list.size());
}
Also used : InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) DebugList(org.drools.compiler.util.debug.DebugList) Test(org.junit.Test)

Aggregations

StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)84 Test (org.junit.Test)63 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)41 KieSession (org.kie.api.runtime.KieSession)24 ArrayList (java.util.ArrayList)22 InternalFactHandle (org.drools.core.common.InternalFactHandle)22 List (java.util.List)20 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)17 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)17 ClassObjectType (org.drools.core.base.ClassObjectType)14 FactHandle (org.kie.api.runtime.rule.FactHandle)14 KieBase (org.kie.api.KieBase)13 HashMap (java.util.HashMap)9 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)8 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)8 BuildContext (org.drools.core.reteoo.builder.BuildContext)8 Cheese (org.drools.core.test.model.Cheese)8 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)7 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)6 TruthMaintenanceSystem (org.drools.core.common.TruthMaintenanceSystem)6