Search in sources :

Example 16 with StatefulKnowledgeSession

use of org.kie.internal.runtime.StatefulKnowledgeSession in project drools by kiegroup.

the class JpaOptLockPersistentStatefulSessionTest method testOptimisticLockInterceptor.

@Test
public void testOptimisticLockInterceptor() {
    String str = "";
    str += "package org.kie.test\n";
    str += "global java.util.List list\n";
    str += "rule rule1\n";
    str += "when\n";
    str += "  Integer(intValue > 0)\n";
    str += "then\n";
    str += "  list.add( 1 );\n";
    str += "end\n";
    str += "\n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    kbase.addPackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    List<?> list = new ArrayList<Object>();
    for (int i = 0; i < 2; i++) {
        new InsertAndFireThread(ksession.getIdentifier(), kbase, list).start();
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    assertEquals(6, list.size());
    ksession.dispose();
}
Also used : KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 17 with StatefulKnowledgeSession

use of org.kie.internal.runtime.StatefulKnowledgeSession in project drools by kiegroup.

the class ReloadSessionTest method reloadKnowledgeSessionTest.

@Test
public void reloadKnowledgeSessionTest() {
    // Initialize drools environment stuff
    Environment env = createEnvironment();
    KieBase kbase = initializeKnowledgeBase(simpleRule);
    StatefulKnowledgeSession commandKSession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    assertTrue("There should be NO facts present in a new (empty) knowledge session.", commandKSession.getFactHandles().isEmpty());
    // Persist a facthandle to the database
    Integer integerFact = (new Random()).nextInt(Integer.MAX_VALUE - 1) + 1;
    commandKSession.insert(integerFact);
    // At this point in the code, the fact has been persisted to the database
    // (within a transaction via the PersistableRunner)
    Collection<FactHandle> factHandles = commandKSession.getFactHandles();
    assertTrue("At least one fact should have been inserted by the ksession.insert() method above.", !factHandles.isEmpty());
    FactHandle origFactHandle = factHandles.iterator().next();
    assertTrue("The stored fact should contain the same number as the value inserted (but does not).", Integer.parseInt(((DefaultFactHandle) origFactHandle).getObject().toString()) == integerFact.intValue());
    // Save the sessionInfo id in order to retrieve it later
    long sessionInfoId = commandKSession.getIdentifier();
    // Clean up the session, environment, etc.
    PersistenceContextManager pcm = (PersistenceContextManager) commandKSession.getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
    commandKSession.dispose();
    pcm.dispose();
    emf.close();
    // Reload session from the database
    emf = Persistence.createEntityManagerFactory(DROOLS_PERSISTENCE_UNIT_NAME);
    context.put(ENTITY_MANAGER_FACTORY, emf);
    env = createEnvironment();
    // Re-initialize the knowledge session:
    StatefulKnowledgeSession newCommandKSession = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionInfoId, kbase, null, env);
    // Test that the session has been successfully reinitialized
    factHandles = newCommandKSession.getFactHandles();
    assertTrue("At least one fact should have been persisted by the ksession.insert above.", !factHandles.isEmpty() && factHandles.size() == 1);
    FactHandle retrievedFactHandle = factHandles.iterator().next();
    assertTrue("If the retrieved and original FactHandle object are the same, then the knowledge session has NOT been reloaded!", origFactHandle != retrievedFactHandle);
    assertTrue("The retrieved fact should contain the same info as the original (but does not).", Integer.parseInt(((DefaultFactHandle) retrievedFactHandle).getObject().toString()) == integerFact.intValue());
    // Test to see if the (retrieved) facts can be processed
    ArrayList<Object> list = new ArrayList<Object>();
    newCommandKSession.setGlobal("list", list);
    newCommandKSession.fireAllRules();
    assertEquals(1, list.size());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) PersistenceContextManager(org.drools.persistence.api.PersistenceContextManager) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) Random(java.util.Random) KieBase(org.kie.api.KieBase) Environment(org.kie.api.runtime.Environment) Test(org.junit.Test)

Example 18 with StatefulKnowledgeSession

use of org.kie.internal.runtime.StatefulKnowledgeSession in project drools by kiegroup.

the class GlobalTest method testGlobalAccess.

@Test
public void testGlobalAccess() {
    final String drl = "import org.drools.core.base.MapGlobalResolver;\n" + "global java.lang.String myGlobal;\n" + "global String unused; \n";
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    final KieSession session1 = kbase.newKieSession();
    final String sample = "default string";
    // Testing 1.
    System.out.println("Start testing 1.");
    session1.setGlobal("myGlobal", "Testing 1");
    session1.insert(sample);
    session1.fireAllRules();
    final Map.Entry[] entries1 = ((MapGlobalResolver) session1.getGlobals()).getGlobals();
    assertEquals(1, entries1.length);
    assertEquals(entries1[0].getValue(), "Testing 1");
    assertEquals(1, session1.getGlobals().getGlobalKeys().size());
    assertTrue(session1.getGlobals().getGlobalKeys().contains("myGlobal"));
    session1.dispose();
    // Testing 2.
    System.out.println("Start testing 2.");
    final StatelessKieSession session2 = session1.getKieBase().newStatelessKieSession();
    session2.setGlobal("myGlobal", "Testing 2");
    session2.execute(sample);
    final Map.Entry[] entries2 = ((MapGlobalResolver) session2.getGlobals()).getGlobals();
    assertEquals(1, entries2.length);
    assertEquals(entries2[0].getValue(), "Testing 2");
    assertEquals(1, session2.getGlobals().getGlobalKeys().size());
    assertTrue(session2.getGlobals().getGlobalKeys().contains("myGlobal"));
    // Testing 3.
    System.out.println("Start testing 3.");
    final StatefulKnowledgeSession session3 = ((StatelessKnowledgeSessionImpl) session2).newWorkingMemory();
    session3.insert(sample);
    session3.fireAllRules();
    Map.Entry[] entries3 = ((MapGlobalResolver) session3.getGlobals()).getGlobals();
    assertEquals(1, entries3.length);
    assertEquals(entries3[0].getValue(), "Testing 2");
    assertEquals(1, session3.getGlobals().getGlobalKeys().size());
    assertTrue(session3.getGlobals().getGlobalKeys().contains("myGlobal"));
    session3.setGlobal("myGlobal", "Testing 3 Over");
    entries3 = ((MapGlobalResolver) session3.getGlobals()).getGlobals();
    assertEquals(1, entries3.length);
    assertEquals(entries3[0].getValue(), "Testing 3 Over");
    assertEquals(1, session3.getGlobals().getGlobalKeys().size());
    assertTrue(session3.getGlobals().getGlobalKeys().contains("myGlobal"));
    session3.dispose();
    // Testing 4.
    System.out.println("Start testing 4.");
    final StatefulKnowledgeSession session4 = ((StatelessKnowledgeSessionImpl) session2).newWorkingMemory();
    session4.setGlobal("myGlobal", "Testing 4");
    session4.insert(sample);
    session4.fireAllRules();
    final Map.Entry[] entries4 = ((MapGlobalResolver) session4.getGlobals()).getGlobals();
    assertEquals(1, entries4.length);
    assertEquals(entries4[0].getValue(), "Testing 4");
    assertEquals(1, session4.getGlobals().getGlobalKeys().size());
    assertTrue(session4.getGlobals().getGlobalKeys().contains("myGlobal"));
    session4.dispose();
}
Also used : StatelessKnowledgeSessionImpl(org.drools.core.impl.StatelessKnowledgeSessionImpl) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) MapGlobalResolver(org.drools.core.base.MapGlobalResolver) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 19 with StatefulKnowledgeSession

use of org.kie.internal.runtime.StatefulKnowledgeSession in project drools by kiegroup.

the class StatefulKnowledgeSessionImpl method writeExternal.

public void writeExternal(ObjectOutput out) throws IOException {
    // all we do is create marshall to a byte[] and write to the stream
    StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) getKnowledgeRuntime();
    Marshaller marshaller = MarshallerFactory.newMarshaller(ksession.getKieBase(), new ObjectMarshallingStrategy[] { MarshallerFactory.newSerializeMarshallingStrategy() });
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    marshaller.marshall(stream, (StatefulKnowledgeSession) getKnowledgeRuntime());
    stream.close();
    byte[] bytes = stream.toByteArray();
    out.writeInt(bytes.length);
    out.write(bytes);
}
Also used : Marshaller(org.kie.api.marshalling.Marshaller) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 20 with StatefulKnowledgeSession

use of org.kie.internal.runtime.StatefulKnowledgeSession in project drools by kiegroup.

the class StatelessKnowledgeSessionImpl method execute.

public void execute(Object object) {
    StatefulKnowledgeSession ksession = newWorkingMemory();
    try {
        ksession.insert(object);
        ksession.fireAllRules();
    } finally {
        dispose(ksession);
    }
}
Also used : StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession)

Aggregations

StatefulKnowledgeSession (org.kie.internal.runtime.StatefulKnowledgeSession)21 Test (org.junit.Test)11 ArrayList (java.util.ArrayList)10 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)9 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)6 Collection (java.util.Collection)4 KieBase (org.kie.api.KieBase)4 Environment (org.kie.api.runtime.Environment)4 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 List (java.util.List)3 TraitableBean (org.drools.core.factmodel.traits.TraitableBean)3 KieSession (org.kie.api.runtime.KieSession)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 CommandBasedStatefulKnowledgeSession (org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession)2 RegistryContext (org.drools.core.command.impl.RegistryContext)2 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)2 FactHandle (org.kie.api.runtime.rule.FactHandle)2 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1