Search in sources :

Example 71 with InternalWorkingMemory

use of org.drools.core.common.InternalWorkingMemory in project jbpm by kiegroup.

the class TimerTest method testTimer.

@Test
@Ignore
public void testTimer() {
    // AbstractRuleBase ruleBase = (AbstractRuleBase) RuleBaseFactory.newRuleBase();
    // ExecutorService executorService = new DefaultExecutorService();
    // final StatefulSession workingMemory = new ReteooStatefulSession(1, ruleBase, executorService);
    // executorService.setCommandExecutor( new CommandExecutor( workingMemory ) );
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    final KieSession workingMemory = kbase.newKieSession();
    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance() {

        private static final long serialVersionUID = 510l;

        public void signalEvent(String type, Object event) {
            if ("timerTriggered".equals(type)) {
                TimerInstance timer = (TimerInstance) event;
                logger.info("Timer {} triggered", timer.getId());
                counter++;
            }
        }
    };
    processInstance.setKnowledgeRuntime(((InternalWorkingMemory) workingMemory).getKnowledgeRuntime());
    processInstance.setId(1234);
    InternalProcessRuntime processRuntime = ((InternalProcessRuntime) ((InternalWorkingMemory) workingMemory).getProcessRuntime());
    processRuntime.getProcessInstanceManager().internalAddProcessInstance(processInstance);
    new Thread(new Runnable() {

        public void run() {
            workingMemory.fireUntilHalt();
        }
    }).start();
    TimerManager timerManager = ((InternalProcessRuntime) ((InternalWorkingMemory) workingMemory).getProcessRuntime()).getTimerManager();
    TimerInstance timer = new TimerInstance();
    timerManager.registerTimer(timer, processInstance);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    // do nothing
    }
    assertEquals(1, counter);
    counter = 0;
    timer = new TimerInstance();
    timer.setDelay(500);
    timerManager.registerTimer(timer, processInstance);
    assertEquals(0, counter);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    // do nothing
    }
    assertEquals(1, counter);
    counter = 0;
    timer = new TimerInstance();
    timer.setDelay(500);
    timer.setPeriod(300);
    timerManager.registerTimer(timer, processInstance);
    assertEquals(0, counter);
    try {
        Thread.sleep(700);
    } catch (InterruptedException e) {
    // do nothing
    }
    assertEquals(1, counter);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    // do nothing
    }
    // we can't know exactly how many times this will fire as timers are not precise, but should be atleast 4
    assertTrue(counter >= 4);
    timerManager.cancelTimer(timer.getId());
    int lastCount = counter;
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    // do nothing
    }
    assertEquals(lastCount, counter);
}
Also used : RuleFlowProcessInstance(org.jbpm.ruleflow.instance.RuleFlowProcessInstance) TimerInstance(org.jbpm.process.instance.timer.TimerInstance) TimerManager(org.jbpm.process.instance.timer.TimerManager) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) InternalProcessRuntime(org.jbpm.process.instance.InternalProcessRuntime) Ignore(org.junit.Ignore) Test(org.junit.Test) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest)

Example 72 with InternalWorkingMemory

use of org.drools.core.common.InternalWorkingMemory in project jbpm by kiegroup.

the class AbstractProtobufProcessInstanceMarshaller method readProcessInstance.

// Input methods
public ProcessInstance readProcessInstance(MarshallerReaderContext context) throws IOException {
    InternalKnowledgeBase ruleBase = context.kBase;
    InternalWorkingMemory wm = context.wm;
    JBPMMessages.ProcessInstance _instance = (org.jbpm.marshalling.impl.JBPMMessages.ProcessInstance) context.parameterObject;
    if (_instance == null) {
        // try to parse from the stream
        ExtensionRegistry registry = PersisterHelper.buildRegistry(context, null);
        Header _header;
        try {
            _header = PersisterHelper.readFromStreamWithHeaderPreloaded(context, registry);
        } catch (ClassNotFoundException e) {
            // Java 5 does not accept [new IOException(String, Throwable)]
            IOException ioe = new IOException("Error deserializing process instance.");
            ioe.initCause(e);
            throw ioe;
        }
        _instance = JBPMMessages.ProcessInstance.parseFrom(_header.getPayload(), registry);
    }
    WorkflowProcessInstanceImpl processInstance = createProcessInstance();
    processInstance.setId(_instance.getId());
    String processId = _instance.getProcessId();
    processInstance.setProcessId(processId);
    String processXml = _instance.getProcessXml();
    Process process = null;
    if (processXml != null && processXml.trim().length() > 0) {
        processInstance.setProcessXml(processXml);
        process = processInstance.getProcess();
    } else {
        process = ruleBase.getProcess(processId);
        if (process == null) {
            throw new RuntimeException("Could not find process " + processId + " when restoring process instance " + processInstance.getId());
        }
        processInstance.setProcess(process);
    }
    processInstance.setDescription(_instance.getDescription());
    processInstance.setState(_instance.getState());
    processInstance.setParentProcessInstanceId(_instance.getParentProcessInstanceId());
    processInstance.setSignalCompletion(_instance.getSignalCompletion());
    processInstance.setDeploymentId(_instance.getDeploymentId());
    processInstance.setCorrelationKey(_instance.getCorrelationKey());
    processInstance.internalSetSlaCompliance(_instance.getSlaCompliance());
    if (_instance.getSlaDueDate() > 0) {
        processInstance.internalSetSlaDueDate(new Date(_instance.getSlaDueDate()));
    }
    processInstance.internalSetSlaTimerId(_instance.getSlaTimerId());
    long nodeInstanceCounter = _instance.getNodeInstanceCounter();
    processInstance.setKnowledgeRuntime(wm.getKnowledgeRuntime());
    processInstance.internalSetNodeInstanceCounter(nodeInstanceCounter);
    for (String completedNodeId : _instance.getCompletedNodeIdsList()) {
        processInstance.addCompletedNodeId(completedNodeId);
    }
    if (_instance.getSwimlaneContextCount() > 0) {
        Context swimlaneContext = ((org.jbpm.process.core.Process) process).getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE);
        SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) processInstance.getContextInstance(swimlaneContext);
        for (JBPMMessages.ProcessInstance.SwimlaneContextInstance _swimlane : _instance.getSwimlaneContextList()) {
            swimlaneContextInstance.setActorId(_swimlane.getSwimlane(), _swimlane.getActorId());
        }
    }
    for (JBPMMessages.ProcessInstance.NodeInstance _node : _instance.getNodeInstanceList()) {
        context.parameterObject = _node;
        readNodeInstance(context, processInstance, processInstance);
    }
    for (JBPMMessages.ProcessInstance.ExclusiveGroupInstance _excl : _instance.getExclusiveGroupList()) {
        ExclusiveGroupInstance exclusiveGroupInstance = new ExclusiveGroupInstance();
        processInstance.addContextInstance(ExclusiveGroup.EXCLUSIVE_GROUP, exclusiveGroupInstance);
        for (Long nodeInstanceId : _excl.getGroupNodeInstanceIdList()) {
            NodeInstance nodeInstance = ((org.jbpm.workflow.instance.NodeInstanceContainer) processInstance).getNodeInstance(nodeInstanceId, true);
            if (nodeInstance == null) {
                throw new IllegalArgumentException("Could not find node instance when deserializing exclusive group instance: " + nodeInstanceId);
            }
            exclusiveGroupInstance.addNodeInstance(nodeInstance);
        }
    }
    if (_instance.getVariableCount() > 0) {
        Context variableScope = ((org.jbpm.process.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
        VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance.getContextInstance(variableScope);
        for (JBPMMessages.Variable _variable : _instance.getVariableList()) {
            try {
                Object _value = ProtobufProcessMarshaller.unmarshallVariableValue(context, _variable);
                variableScopeInstance.internalSetVariable(_variable.getName(), _value);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Could not reload variable " + _variable.getName());
            }
        }
    }
    if (_instance.getIterationLevelsCount() > 0) {
        for (JBPMMessages.IterationLevel _level : _instance.getIterationLevelsList()) {
            processInstance.getIterationLevels().put(_level.getId(), _level.getLevel());
        }
    }
    processInstance.reconnect();
    return processInstance;
}
Also used : NodeInstanceContainer(org.kie.api.runtime.process.NodeInstanceContainer) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) Process(org.kie.api.definition.process.Process) ExtensionRegistry(com.google.protobuf.ExtensionRegistry) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) MarshallerWriteContext(org.drools.core.marshalling.impl.MarshallerWriteContext) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext) Context(org.jbpm.process.core.Context) SwimlaneContext(org.jbpm.process.core.context.swimlane.SwimlaneContext) ExclusiveGroupInstance(org.jbpm.process.instance.context.exclusive.ExclusiveGroupInstance) SwimlaneContextInstance(org.jbpm.process.instance.context.swimlane.SwimlaneContextInstance) IOException(java.io.IOException) Date(java.util.Date) Header(org.drools.core.marshalling.impl.ProtobufMessages.Header) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) WorkflowProcessInstance(org.kie.api.runtime.process.WorkflowProcessInstance) RuleSetNodeInstance(org.jbpm.workflow.instance.node.RuleSetNodeInstance) EventSubProcessNodeInstance(org.jbpm.workflow.instance.node.EventSubProcessNodeInstance) StateNodeInstance(org.jbpm.workflow.instance.node.StateNodeInstance) TimerNodeInstance(org.jbpm.workflow.instance.node.TimerNodeInstance) CompositeContextNodeInstance(org.jbpm.workflow.instance.node.CompositeContextNodeInstance) DynamicNodeInstance(org.jbpm.workflow.instance.node.DynamicNodeInstance) AsyncEventNodeInstance(org.jbpm.workflow.instance.node.AsyncEventNodeInstance) SubProcessNodeInstance(org.jbpm.workflow.instance.node.SubProcessNodeInstance) NodeInstance(org.kie.api.runtime.process.NodeInstance) HumanTaskNodeInstance(org.jbpm.workflow.instance.node.HumanTaskNodeInstance) EventNodeInstance(org.jbpm.workflow.instance.node.EventNodeInstance) ForEachNodeInstance(org.jbpm.workflow.instance.node.ForEachNodeInstance) MilestoneNodeInstance(org.jbpm.workflow.instance.node.MilestoneNodeInstance) WorkItemNodeInstance(org.jbpm.workflow.instance.node.WorkItemNodeInstance)

Example 73 with InternalWorkingMemory

use of org.drools.core.common.InternalWorkingMemory in project jbpm by kiegroup.

the class ProcessInstanceResolverStrategy method retrieveKnowledgeRuntime.

/**
 * Retrieve the {@link ProcessInstanceManager} object from the ObjectOutput- or ObjectInputStream.
 * The stream object will secretly also either be a {@link MarshallerReaderContext} or a
 * {@link MarshallerWriteContext}.
 * </p>
 * The knowledge runtime object is useful in order to reconnect the process instance to the
 * process and the knowledge runtime object.
 * @param streamContext The marshaller stream/context.
 * @return A {@link InternalKnowledgeRuntime} object.
 */
public static InternalKnowledgeRuntime retrieveKnowledgeRuntime(Object streamContext) {
    InternalKnowledgeRuntime kruntime = null;
    if (streamContext instanceof MarshallerWriteContext) {
        MarshallerWriteContext context = (MarshallerWriteContext) streamContext;
        kruntime = ((InternalWorkingMemory) context.wm).getKnowledgeRuntime();
    } else if (streamContext instanceof MarshallerReaderContext) {
        MarshallerReaderContext context = (MarshallerReaderContext) streamContext;
        kruntime = ((InternalWorkingMemory) context.wm).getKnowledgeRuntime();
    } else {
        throw new UnsupportedOperationException("Unable to retrieve " + ProcessInstanceManager.class.getSimpleName() + " from " + streamContext.getClass().getName());
    }
    return kruntime;
}
Also used : InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) ProcessInstanceManager(org.jbpm.process.instance.ProcessInstanceManager) MarshallerWriteContext(org.drools.core.marshalling.impl.MarshallerWriteContext) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext)

Example 74 with InternalWorkingMemory

use of org.drools.core.common.InternalWorkingMemory in project jbpm by kiegroup.

the class ProcessInstanceResolverStrategy method retrieveProcessInstanceManager.

/**
 * Retrieve the {@link ProcessInstanceManager} object from the ObjectOutput- or ObjectInputStream.
 * The stream object will secretly also either be a {@link MarshallerReaderContext} or a
 * {@link MarshallerWriteContext}.
 * @param streamContext The marshaller stream/context.
 * @return A {@link ProcessInstanceManager} object.
 */
public static ProcessInstanceManager retrieveProcessInstanceManager(Object streamContext) {
    ProcessInstanceManager pim = null;
    if (streamContext instanceof MarshallerWriteContext) {
        MarshallerWriteContext context = (MarshallerWriteContext) streamContext;
        pim = ((ProcessRuntimeImpl) ((InternalWorkingMemory) context.wm).getProcessRuntime()).getProcessInstanceManager();
    } else if (streamContext instanceof MarshallerReaderContext) {
        MarshallerReaderContext context = (MarshallerReaderContext) streamContext;
        pim = ((ProcessRuntimeImpl) ((InternalWorkingMemory) context.wm).getProcessRuntime()).getProcessInstanceManager();
    } else {
        throw new UnsupportedOperationException("Unable to retrieve " + ProcessInstanceManager.class.getSimpleName() + " from " + streamContext.getClass().getName());
    }
    return pim;
}
Also used : ProcessInstanceManager(org.jbpm.process.instance.ProcessInstanceManager) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) MarshallerWriteContext(org.drools.core.marshalling.impl.MarshallerWriteContext) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext) ProcessRuntimeImpl(org.jbpm.process.instance.ProcessRuntimeImpl)

Example 75 with InternalWorkingMemory

use of org.drools.core.common.InternalWorkingMemory in project jbpm by kiegroup.

the class ProcessTimerTest method testOnEntryTimerExecuted.

@Test
public void testOnEntryTimerExecuted() throws Exception {
    Reader source = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + "         type=\"RuleFlow\" name=\"flow\" id=\"org.drools.timer\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + "  <header>\n" + "    <globals>\n" + "      <global identifier=\"myList\" type=\"java.util.List\" />\n" + "    </globals>\n" + "  </header>\n" + "\n" + "  <nodes>\n" + "    <start id=\"1\" name=\"Start\" />\n" + "    <milestone id=\"2\" name=\"Wait\" >\n" + "      <timers>\n" + "        <timer id=\"1\" delay=\"300\" >\n" + "          <action type=\"expression\" dialect=\"java\" >myList.add(\"Executing timer\");</action>\n" + "        </timer>\n" + "      </timers>\n" + "      <constraint type=\"rule\" dialect=\"mvel\" >eval(false)</constraint>\n" + "    </milestone>\n" + "    <end id=\"3\" name=\"End\" />\n" + "  </nodes>\n" + "\n" + "  <connections>\n" + "    <connection from=\"1\" to=\"2\" />\n" + "    <connection from=\"2\" to=\"3\" />\n" + "  </connections>\n" + "\n" + "</process>");
    builder.addRuleFlow(source);
    KieSession session = createKieSession(builder.getPackages());
    List<String> myList = new ArrayList<String>();
    session.setGlobal("myList", myList);
    ProcessInstance processInstance = (ProcessInstance) session.startProcess("org.drools.timer");
    assertEquals(0, myList.size());
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    assertEquals(1, ((InternalProcessRuntime) ((InternalWorkingMemory) session).getProcessRuntime()).getTimerManager().getTimers().size());
    try {
        Thread.sleep(400);
    } catch (InterruptedException e) {
    // do nothing
    }
    assertEquals(1, myList.size());
    session.dispose();
}
Also used : InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) Reader(java.io.Reader) StringReader(java.io.StringReader) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.jbpm.process.instance.ProcessInstance) Test(org.junit.Test) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest)

Aggregations

InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)285 Test (org.junit.Test)217 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)140 KieBase (org.kie.api.KieBase)129 ArrayList (java.util.ArrayList)96 LeftInputAdapterNode (org.drools.core.reteoo.LeftInputAdapterNode)91 List (java.util.List)76 SegmentMemory (org.drools.core.reteoo.SegmentMemory)74 KieSession (org.kie.api.runtime.KieSession)71 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)69 JoinNode (org.drools.core.reteoo.JoinNode)62 BetaMemory (org.drools.core.reteoo.BetaMemory)57 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)48 PathMemory (org.drools.core.reteoo.PathMemory)48 LiaNodeMemory (org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory)45 BetaNode (org.drools.core.reteoo.BetaNode)44 FactHandle (org.kie.api.runtime.rule.FactHandle)44 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)35 AlphaNode (org.drools.core.reteoo.AlphaNode)35 ClassObjectType (org.drools.core.base.ClassObjectType)30