Search in sources :

Example 56 with StatefulKnowledgeSessionImpl

use of org.drools.kiesession.session.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class LinkingTest method testExistsNodes1.

@Test
public void testExistsNodes1() 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 " + X.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 += "   exists A() \n";
    str += "then \n";
    str += "  list.add( 'x' ); \n";
    str += "end \n";
    KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
    KieSession wm = kbase.newKieSession();
    List list = new ArrayList();
    wm.setGlobal("list", list);
    wm.fireAllRules();
    assertEquals(0, list.size());
    wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    list = new ArrayList();
    wm.setGlobal("list", list);
    FactHandle fh = wm.insert(new A(1));
    wm.fireAllRules();
    assertEquals(1, list.size());
    wm.retract(fh);
    wm.fireAllRules();
    assertEquals(1, list.size());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) ArrayList(java.util.ArrayList) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 57 with StatefulKnowledgeSessionImpl

use of org.drools.kiesession.session.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class ProtobufOutputMarshaller method serializeSession.

private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context) throws IOException {
    StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.getWorkingMemory();
    try {
        wm.getLock().lock();
        for (EntryPoint ep : wm.getEntryPoints()) {
            if (ep instanceof NamedEntryPoint) {
                ((NamedEntryPoint) ep).lock();
            }
        }
        evaluateRuleActivations(wm);
        ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();
        long time = 0;
        if (context.getWorkingMemory().getTimerService() instanceof PseudoClockScheduler) {
            time = context.getClockTime();
        }
        _ruleData.setLastId(wm.getFactHandleFactory().getId());
        _ruleData.setLastRecency(wm.getFactHandleFactory().getRecency());
        InternalFactHandle handle = context.getWorkingMemory().getInitialFactHandle();
        if (handle != null) {
            // can be null for RETE, if fireAllRules has not yet been called
            ProtobufMessages.FactHandle _ifh = ProtobufMessages.FactHandle.newBuilder().setType(ProtobufMessages.FactHandle.HandleType.INITIAL_FACT).setId(handle.getId()).setRecency(handle.getRecency()).build();
            _ruleData.setInitialFact(_ifh);
        }
        writeAgenda(context, _ruleData);
        writeNodeMemories(context, _ruleData);
        for (EntryPoint wmep : wm.getEntryPoints()) {
            ProtobufMessages.EntryPoint.Builder _epb = ProtobufMessages.EntryPoint.newBuilder();
            _epb.setEntryPointId(wmep.getEntryPointId());
            writeObjectTypeConfiguration(context, ((WorkingMemoryEntryPoint) wmep).getObjectTypeConfigurationRegistry(), _epb);
            writeFactHandles(context, _epb, ((NamedEntryPoint) wmep).getObjectStore());
            writeTruthMaintenanceSystem(context, wmep, _epb);
            _ruleData.addEntryPoint(_epb.build());
        }
        writeActionQueue(context, _ruleData);
        ProtobufMessages.KnowledgeSession.Builder _session = ProtobufMessages.KnowledgeSession.newBuilder().setMultithread(false).setTime(time).setRuleData(_ruleData.build());
        if (processMarshaller != null) {
            Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
            if (context.isMarshalProcessInstances()) {
                context.setParameterObject(_pdata);
                processMarshaller.writeProcessInstances(context);
            }
            if (context.isMarshalWorkItems()) {
                context.setParameterObject(_pdata);
                processMarshaller.writeWorkItems(context);
            }
            // this now just assigns the writer, it will not write out any timer information
            context.setParameterObject(_pdata);
            processMarshaller.writeProcessTimers(context);
            _session.setProcessData(_pdata.build());
        }
        Timers _timers = writeTimers(context.getWorkingMemory().getTimerJobInstances(context.getWorkingMemory().getIdentifier()), context);
        if (_timers != null) {
            _session.setTimers(_timers);
        }
        return _session.build();
    } finally {
        for (EntryPoint ep : wm.getEntryPoints()) {
            if (ep instanceof NamedEntryPoint) {
                ((NamedEntryPoint) ep).unlock();
            }
        }
        wm.getLock().unlock();
    }
}
Also used : NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) Builder(org.drools.serialization.protobuf.ProtobufMessages.ProcessData.Builder) FactHandle(org.drools.serialization.protobuf.ProtobufMessages.FactHandle) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) InternalFactHandle(org.drools.core.common.InternalFactHandle) Timers(org.drools.serialization.protobuf.ProtobufMessages.Timers)

Example 58 with StatefulKnowledgeSessionImpl

use of org.drools.kiesession.session.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class IndexingTest method testIndexingOnQueryUnificationWithNot.

@Test(timeout = 10000)
public void testIndexingOnQueryUnificationWithNot() {
    final String drl = "package org.drools.compiler.test  \n" + "import " + Person.class.getCanonicalName() + "\n" + "query peeps( String $name, int $age ) \n" + "    not $p2 : Person( $name := name, age > $age ) \n" + "end\n";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("indexing-test", kieBaseTestConfiguration, drl);
    final StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) kbase.newKieSession();
    ReteDumper.dumpRete(wm);
    try {
        final List<ObjectTypeNode> nodes = ((RuleBase) kbase).getRete().getObjectTypeNodes();
        ObjectTypeNode node = null;
        for (final ObjectTypeNode n : nodes) {
            if (((ClassObjectType) n.getObjectType()).getClassType() == DroolsQuery.class) {
                node = n;
                break;
            }
        }
        assertNotNull(node);
        final AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
        final LeftInputAdapterNode liaNode = (LeftInputAdapterNode) alphanode.getObjectSinkPropagator().getSinks()[0];
        final NotNode n = (NotNode) liaNode.getSinkPropagator().getSinks()[0];
        final DoubleNonIndexSkipBetaConstraints c = (DoubleNonIndexSkipBetaConstraints) n.getRawConstraints();
        assertTrue(c.isIndexed());
        final BetaMemory bm = (BetaMemory) wm.getNodeMemory(n);
        assertTrue(bm.getLeftTupleMemory() instanceof TupleIndexHashTable);
        assertTrue(bm.getRightTupleMemory() instanceof TupleIndexHashTable);
        final Map<String, Integer> map = new HashMap<>();
        map.put("inserted", 0);
        map.put("deleted", 0);
        map.put("updated", 0);
        wm.openLiveQuery("peeps", new Object[] { Variable.v, 99 }, new ViewChangedEventListener() {

            @Override
            public void rowInserted(final Row row) {
                final Integer integer = map.get("inserted");
                map.put("inserted", integer + 1);
            }

            @Override
            public void rowDeleted(final Row row) {
                final Integer integer = map.get("deleted");
                map.put("deleted", integer + 1);
            }

            @Override
            public void rowUpdated(final Row row) {
                final Integer integer = map.get("updated");
                map.put("updated", integer + 1);
            }
        });
        final Map<String, InternalFactHandle> peeps = new HashMap<>();
        Person p;
        InternalFactHandle fh;
        final int max = 3;
        // 1 matched, prior to any insertions
        assertInsertedUpdatedDeleted(map, 1, 0, 0);
        // x0 is the blocker
        for (int i = 0; i < max; i++) {
            p = new Person("x" + i, 100);
            fh = (InternalFactHandle) wm.insert(p);
            wm.fireAllRules();
            peeps.put(p.getName(), fh);
        }
        // insertions case 1 deletion
        assertInsertedUpdatedDeleted(map, 1, 0, 1);
        // each x is blocker in turn up to x99
        for (int i = 0; i < (max - 1); i++) {
            fh = peeps.get("x" + i);
            p = (Person) fh.getObject();
            p.setAge(90);
            wm.update(fh, p);
            wm.fireAllRules();
            // make sure this doesn't change
            assertEquals("i=" + i, 1, map.get("inserted").intValue());
        }
        // no change
        assertInsertedUpdatedDeleted(map, 1, 0, 1);
        // x99 is still the blocker, everything else is just added
        for (int i = 0; i < (max - 1); i++) {
            fh = peeps.get("x" + i);
            p = (Person) fh.getObject();
            p.setAge(102);
            wm.update(fh, p);
            wm.fireAllRules();
            // make sure this doesn't change
            assertEquals("i=" + i, 1, map.get("inserted").intValue());
        }
        // no change
        assertInsertedUpdatedDeleted(map, 1, 0, 1);
        // x99 is still the blocker
        for (int i = (max - 2); i >= 0; i--) {
            fh = peeps.get("x" + i);
            p = (Person) fh.getObject();
            p.setAge(90);
            wm.update(fh, p);
            wm.fireAllRules();
            // make sure this doesn't change
            assertEquals("i=" + i, 1, map.get("inserted").intValue());
        }
        // move x99, should no longer be a blocker, now it can increase
        fh = peeps.get("x" + (max - 1));
        p = (Person) fh.getObject();
        p.setAge(90);
        wm.update(fh, p);
        wm.fireAllRules();
        assertEquals(2, map.get("inserted").intValue());
    } finally {
        wm.dispose();
    }
}
Also used : NotNode(org.drools.core.reteoo.NotNode) HashMap(java.util.HashMap) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) BetaMemory(org.drools.core.reteoo.BetaMemory) TupleIndexHashTable(org.drools.core.util.index.TupleIndexHashTable) AlphaNode(org.drools.core.reteoo.AlphaNode) DoubleNonIndexSkipBetaConstraints(org.drools.core.common.DoubleNonIndexSkipBetaConstraints) ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) Row(org.kie.api.runtime.rule.Row) InternalFactHandle(org.drools.core.common.InternalFactHandle) Person(org.drools.testcoverage.common.model.Person) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) Test(org.junit.Test)

Example 59 with StatefulKnowledgeSessionImpl

use of org.drools.kiesession.session.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class CepEspTest method testIdleTimeAndTimeToNextJob.

@Test(timeout = 10000)
public void testIdleTimeAndTimeToNextJob() {
    final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("cep-esp-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_CEP_SimpleTimeWindow.drl");
    final StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) kbase.newKieSession(KieSessionTestConfiguration.STATEFUL_PSEUDO.getKieSessionConfiguration(), null);
    try {
        final WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger((WorkingMemory) wm);
        final File testTmpDir = new File("target/test-tmp/");
        testTmpDir.mkdirs();
        logger.setFileName("target/test-tmp/testIdleTimeAndTimeToNextJob-audit");
        try {
            final List results = new ArrayList();
            wm.setGlobal("results", results);
            // how to initialize the clock?
            // how to configure the clock?
            final SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock();
            // 5 seconds
            clock.advanceTime(5, 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
            // 10 seconds
            clock.advanceTime(10, 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
            // 10 seconds
            clock.advanceTime(10, 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
            // 10 seconds
            clock.advanceTime(10, 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
            // 10 seconds
            clock.advanceTime(10, 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();
        }
    } finally {
        wm.dispose();
    }
}
Also used : WorkingMemoryFileLogger(org.drools.kiesession.audit.WorkingMemoryFileLogger) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) OrderEvent(org.drools.testcoverage.common.model.OrderEvent) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) File(java.io.File) Test(org.junit.Test)

Example 60 with StatefulKnowledgeSessionImpl

use of org.drools.kiesession.session.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class KieContainerImpl method getKieSession.

public KieSession getKieSession(String kSessionName) {
    KieSession kieSession = kSessions.get(kSessionName);
    if (kieSession instanceof StatefulKnowledgeSessionImpl && !((StatefulKnowledgeSessionImpl) kieSession).isAlive()) {
        kSessions.remove(kSessionName);
        kieSession = null;
    }
    return kieSession != null ? kieSession : newKieSession(kSessionName);
}
Also used : StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) KieSession(org.kie.api.runtime.KieSession)

Aggregations

StatefulKnowledgeSessionImpl (org.drools.kiesession.session.StatefulKnowledgeSessionImpl)66 Test (org.junit.Test)57 InternalKnowledgeBase (org.drools.kiesession.rulebase.InternalKnowledgeBase)34 ArrayList (java.util.ArrayList)15 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)15 KieBase (org.kie.api.KieBase)15 ClassObjectType (org.drools.core.base.ClassObjectType)14 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)14 BetaMemory (org.drools.core.reteoo.BetaMemory)14 List (java.util.List)13 InternalFactHandle (org.drools.core.common.InternalFactHandle)13 KieSession (org.kie.api.runtime.KieSession)12 FactHandle (org.kie.api.runtime.rule.FactHandle)11 MockObjectSink (org.drools.core.reteoo.MockObjectSink)10 BuildContext (org.drools.core.reteoo.builder.BuildContext)10 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)8 HashMap (java.util.HashMap)7 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)7 PathMemory (org.drools.core.reteoo.PathMemory)7 Rete (org.drools.core.reteoo.Rete)7