Search in sources :

Example 1 with StatefulKnowledgeSession

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

the class StatelessKnowledgeSessionImpl method newWorkingMemory.

public StatefulKnowledgeSession newWorkingMemory() {
    this.kBase.readLock();
    try {
        StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) wmFactory.createWorkingMemory(this.kBase.nextWorkingMemoryCounter(), this.kBase, (SessionConfiguration) this.conf, this.environment);
        StatefulKnowledgeSessionImpl ksessionImpl = (StatefulKnowledgeSessionImpl) ksession;
        ((Globals) ksessionImpl.getGlobalResolver()).setDelegate(this.sessionGlobals);
        registerListeners(ksessionImpl);
        for (Map.Entry<String, Channel> entry : this.channels.entrySet()) {
            ksession.registerChannel(entry.getKey(), entry.getValue());
        }
        wmCreated.incrementAndGet();
        return ksession;
    } finally {
        this.kBase.readUnlock();
    }
}
Also used : Globals(org.kie.api.runtime.Globals) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) Channel(org.kie.api.runtime.Channel) HashMap(java.util.HashMap) Map(java.util.Map) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) SessionConfiguration(org.drools.core.SessionConfiguration)

Example 2 with StatefulKnowledgeSession

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

the class StatelessKnowledgeSessionImpl method executeWithResults.

public List executeWithResults(Iterable objects, ObjectFilter filter) {
    List list = new ArrayList();
    StatefulKnowledgeSession ksession = newWorkingMemory();
    try {
        for (Object object : objects) {
            ksession.insert(object);
        }
        ksession.fireAllRules();
        for (FactHandle fh : ksession.getFactHandles(filter)) {
            list.add(((InternalFactHandle) fh).getObject());
        }
    } finally {
        dispose(ksession);
    }
    return list;
}
Also used : InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 3 with StatefulKnowledgeSession

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

the class StatelessKnowledgeSessionImpl method execute.

public <T> T execute(Command<T> command) {
    StatefulKnowledgeSession ksession = newWorkingMemory();
    RegistryContext context = new ContextImpl().register(KieSession.class, ksession);
    try {
        if (command instanceof BatchExecutionCommand) {
            ((RegistryContext) context).register(ExecutionResultImpl.class, new ExecutionResultImpl());
        }
        ((StatefulKnowledgeSessionImpl) ksession).startBatchExecution();
        Object o = ((ExecutableCommand) command).execute(context);
        // did the user take control of fireAllRules, if not we will auto execute
        boolean autoFireAllRules = true;
        if (command instanceof FireAllRulesCommand) {
            autoFireAllRules = false;
        } else if (command instanceof BatchExecutionCommandImpl) {
            for (Command nestedCmd : ((BatchExecutionCommandImpl) command).getCommands()) {
                if (nestedCmd instanceof FireAllRulesCommand) {
                    autoFireAllRules = false;
                    break;
                }
            }
        }
        if (autoFireAllRules) {
            ksession.fireAllRules();
        }
        if (command instanceof BatchExecutionCommand) {
            return (T) ((RegistryContext) context).lookup(ExecutionResultImpl.class);
        } else {
            return (T) o;
        }
    } finally {
        ((StatefulKnowledgeSessionImpl) ksession).endBatchExecution();
        dispose(ksession);
    }
}
Also used : FireAllRulesCommand(org.drools.core.command.runtime.rule.FireAllRulesCommand) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) RegistryContext(org.drools.core.command.impl.RegistryContext) ContextImpl(org.drools.core.command.impl.ContextImpl) BatchExecutionCommandImpl(org.drools.core.command.runtime.BatchExecutionCommandImpl) FireAllRulesCommand(org.drools.core.command.runtime.rule.FireAllRulesCommand) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) Command(org.kie.api.command.Command) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) ExecutionResultImpl(org.drools.core.runtime.impl.ExecutionResultImpl) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand)

Example 4 with StatefulKnowledgeSession

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

the class SerializationHelper method getSerialisedStatefulKnowledgeSession.

public static StatefulKnowledgeSession getSerialisedStatefulKnowledgeSession(KieSession ksession, KieBase kbase, boolean dispose, boolean testRoundTrip) throws Exception {
    ProtobufMarshaller marshaller = (ProtobufMarshaller) MarshallerFactory.newMarshaller(kbase, (ObjectMarshallingStrategy[]) ksession.getEnvironment().get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES));
    long time = ksession.<SessionClock>getSessionClock().getCurrentTime();
    // make sure globas are in the environment of the session
    ksession.getEnvironment().set(EnvironmentName.GLOBALS, ksession.getGlobals());
    // Serialize object
    final byte[] b1;
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        marshaller.marshall(bos, ksession, time);
        b1 = bos.toByteArray();
        bos.close();
    }
    // Deserialize object
    StatefulKnowledgeSession ksession2;
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(b1);
        ksession2 = marshaller.unmarshall(bais, ksession.getSessionConfiguration(), ksession.getEnvironment());
        bais.close();
    }
    if (testRoundTrip) {
        // for now, we can ensure the IDs will match because queries are creating untraceable fact handles at the moment
        // int previous_id = ((StatefulKnowledgeSessionImpl)ksession).session.getFactHandleFactory().getId();
        // long previous_recency = ((StatefulKnowledgeSessionImpl)ksession).session.getFactHandleFactory().getRecency();
        // int current_id = ((StatefulKnowledgeSessionImpl)ksession2).session.getFactHandleFactory().getId();
        // long current_recency = ((StatefulKnowledgeSessionImpl)ksession2).session.getFactHandleFactory().getRecency();
        // ((StatefulKnowledgeSessionImpl)ksession2).session.getFactHandleFactory().clear( previous_id, previous_recency );
        // Reserialize and check that byte arrays are the same
        final byte[] b2;
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            marshaller.marshall(bos, ksession2, time);
            b2 = bos.toByteArray();
            bos.close();
        }
        // bytes should be the same.
        if (!areByteArraysEqual(b1, b2)) {
        // throw new IllegalArgumentException( "byte streams for serialisation test are not equal" );
        }
    // ((StatefulKnowledgeSessionImpl) ksession2).session.getFactHandleFactory().clear( current_id, current_recency );
    // ((StatefulKnowledgeSessionImpl) ksession2).session.setGlobalResolver( ((StatefulKnowledgeSessionImpl) ksession).session.getGlobalResolver() );
    }
    if (dispose) {
        ksession.dispose();
    }
    return ksession2;
}
Also used : ProtobufMarshaller(org.drools.core.marshalling.impl.ProtobufMarshaller) ByteArrayInputStream(java.io.ByteArrayInputStream) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 5 with StatefulKnowledgeSession

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

the class JpaPersistenceTraitTest method testTripleBasedTraitsWithJPA.

@Test
public void testTripleBasedTraitsWithJPA() {
    String str = "package org.drools.trait.test; \n" + "global java.util.List list; \n" + "" + "declare TBean \n" + "  @propertyReactive \n" + "  @Traitable \n" + "  fld : String \n" + "end \n " + "" + "declare trait Mask \n" + "  @propertyReactive \n" + "  fld : String \n" + "  xyz : int  \n" + "end \n" + "\n " + "declare trait Cloak \n" + "  @propertyReactive \n" + "  fld : String \n" + "  ijk : String  \n" + "end \n" + "" + "rule Init \n" + "when \n" + "then \n" + "  insert( new TBean(\"abc\") ); \n" + "end \n" + "" + "rule Don \n" + "no-loop \n" + "when \n" + "  $b : TBean( ) \n" + "then \n" + "  Mask m = don( $b, Mask.class ); \n" + "  modify (m) { setXyz( 10 ); } \n" + "  list.add( m ); \n" + "  System.out.println( \"Don result : \" + m ); \n " + "end \n" + "\n" + "rule Don2 \n" + "no-loop \n" + "when \n" + "  $b : TBean( ) \n" + "then \n" + "  Cloak c = don( $b, Cloak.class ); \n" + "  modify (c) { setIjk( \"ijklmn\" ); } \n" + "  list.add( c ); \n" + "  System.out.println( \"Don result : \" + c ); \n " + "end \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);
    // StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    List<?> list = new ArrayList<Object>();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    assertEquals(2, list.size());
    long id = ksession.getIdentifier();
    StatefulKnowledgeSession ksession2 = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    // StatefulKnowledgeSession ksession2 = kbase.newStatefulKnowledgeSession();
    ksession2.fireAllRules();
    Collection x = ksession2.getObjects();
    assertEquals(3, x.size());
    TraitableBean core = null;
    for (Object o : x) {
        if (o instanceof TraitableBean) {
            core = (TraitableBean) o;
            break;
        }
    }
    assertNotNull(core);
    assertEquals(2, core._getDynamicProperties().size());
    assertNotNull(core.getTrait("org.drools.trait.test.Mask"));
    assertNotNull(core.getTrait("org.drools.trait.test.Cloak"));
}
Also used : KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) Collection(java.util.Collection) TraitableBean(org.drools.core.factmodel.traits.TraitableBean) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Aggregations

StatefulKnowledgeSession (org.kie.internal.runtime.StatefulKnowledgeSession)114 Test (org.junit.Test)79 KieBase (org.kie.api.KieBase)52 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)40 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)30 ArrayList (java.util.ArrayList)29 CommandBasedStatefulKnowledgeSession (org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession)22 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)20 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)18 HashMap (java.util.HashMap)16 Environment (org.kie.api.runtime.Environment)12 KieSession (org.kie.api.runtime.KieSession)11 WorkflowProcessInstance (org.kie.api.runtime.process.WorkflowProcessInstance)11 RuleFlowProcess (org.jbpm.ruleflow.core.RuleFlowProcess)10 ClassPathResource (org.drools.core.io.impl.ClassPathResource)9 WorkItem (org.kie.api.runtime.process.WorkItem)9 TestWorkItemHandler (org.jbpm.bpmn2.objects.TestWorkItemHandler)8 TestWorkItemHandler (org.jbpm.persistence.session.objects.TestWorkItemHandler)8 Resource (org.kie.api.io.Resource)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7