Search in sources :

Example 16 with WorkflowProcessInstance

use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.

the class CloseCaseCommand method execute.

@Override
public Void execute(Context context) {
    CorrelationKey correlationKey = correlationKeyFactory.newCorrelationKey(caseId);
    Collection<ProcessInstanceDesc> caseProcesses = runtimeDataService.getProcessInstancesByCorrelationKey(correlationKey, new QueryContext(0, 1000));
    if (caseProcesses.isEmpty()) {
        throw new CaseNotFoundException("Case with id " + caseId + " was not found");
    }
    final List<Long> processInstanceIds = caseProcesses.stream().filter(pi -> pi.getState().equals(ProcessInstance.STATE_ACTIVE)).sorted((ProcessInstanceDesc o1, ProcessInstanceDesc o2) -> {
        return Long.valueOf(o2.getParentId()).compareTo(Long.valueOf(o1.getParentId()));
    }).map(pi -> pi.getId()).collect(toList());
    CaseEventSupport caseEventSupport = getCaseEventSupport(context);
    KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
    CaseFileInstance caseFile = getCaseFile(ksession, caseId);
    caseEventSupport.fireBeforeCaseClosed(caseId, caseFile, comment);
    logger.debug("Process instances {} that will be completed as part of the close of the case {}", processInstanceIds, caseId);
    processService.execute(deploymentId, CaseContext.get(caseId), new ExecutableCommand<Void>() {

        private static final long serialVersionUID = 1L;

        @Override
        public Void execute(Context context) {
            KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
            for (Long processInstanceId : processInstanceIds) {
                WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
                processInstance.setState(ProcessInstance.STATE_COMPLETED, comment);
                logger.debug("Process instance {} set to state completed", processInstanceId);
            }
            return null;
        }
    });
    caseEventSupport.fireAfterCaseClosed(caseId, caseFile, comment);
    return null;
}
Also used : IdentityProvider(org.kie.internal.identity.IdentityProvider) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) RegistryContext(org.drools.core.command.impl.RegistryContext) Logger(org.slf4j.Logger) ProcessService(org.jbpm.services.api.ProcessService) CorrelationKey(org.kie.internal.process.CorrelationKey) CaseNotFoundException(org.jbpm.casemgmt.api.CaseNotFoundException) Collection(java.util.Collection) CaseFileInstance(org.jbpm.casemgmt.api.model.instance.CaseFileInstance) LoggerFactory(org.slf4j.LoggerFactory) QueryContext(org.kie.api.runtime.query.QueryContext) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) Context(org.kie.api.runtime.Context) CaseEventSupport(org.jbpm.casemgmt.impl.event.CaseEventSupport) RuntimeDataService(org.jbpm.services.api.RuntimeDataService) ProcessInstanceDesc(org.jbpm.services.api.model.ProcessInstanceDesc) KieInternalServices(org.kie.internal.KieInternalServices) KieSession(org.kie.api.runtime.KieSession) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) CaseContext(org.kie.internal.runtime.manager.context.CaseContext) RegistryContext(org.drools.core.command.impl.RegistryContext) QueryContext(org.kie.api.runtime.query.QueryContext) Context(org.kie.api.runtime.Context) CaseContext(org.kie.internal.runtime.manager.context.CaseContext) CaseEventSupport(org.jbpm.casemgmt.impl.event.CaseEventSupport) ProcessInstanceDesc(org.jbpm.services.api.model.ProcessInstanceDesc) RegistryContext(org.drools.core.command.impl.RegistryContext) QueryContext(org.kie.api.runtime.query.QueryContext) CaseNotFoundException(org.jbpm.casemgmt.api.CaseNotFoundException) CaseFileInstance(org.jbpm.casemgmt.api.model.instance.CaseFileInstance) CorrelationKey(org.kie.internal.process.CorrelationKey) KieSession(org.kie.api.runtime.KieSession) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 17 with WorkflowProcessInstance

use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.

the class DynamicUtils method internalAddDynamicSubProcess.

public static long internalAddDynamicSubProcess(final WorkflowProcessInstance processInstance, final DynamicNodeInstance dynamicContext, KieRuntime ksession, final String processId, final Map<String, Object> parameters) {
    final SubProcessNodeInstance subProcessNodeInstance = new SubProcessNodeInstance();
    subProcessNodeInstance.setNodeInstanceContainer(dynamicContext == null ? processInstance : dynamicContext);
    subProcessNodeInstance.setProcessInstance(processInstance);
    subProcessNodeInstance.setMetaData("NodeType", "SubProcessNode");
    if (ksession instanceof StatefulKnowledgeSessionImpl) {
        return executeSubProcess((StatefulKnowledgeSessionImpl) ksession, processId, parameters, processInstance, subProcessNodeInstance);
    } else if (ksession instanceof CommandBasedStatefulKnowledgeSession) {
        ExecutableRunner commandService = ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
        return commandService.execute(new ExecutableCommand<Long>() {

            private static final long serialVersionUID = 5L;

            public Long execute(Context context) {
                StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) ((RegistryContext) context).lookup(KieSession.class);
                WorkflowProcessInstance realProcessInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstance.getId());
                subProcessNodeInstance.setProcessInstance(realProcessInstance);
                if (dynamicContext == null) {
                    subProcessNodeInstance.setNodeInstanceContainer(realProcessInstance);
                } else {
                    DynamicNodeInstance realDynamicContext = findDynamicContext(realProcessInstance, dynamicContext.getUniqueId());
                    subProcessNodeInstance.setNodeInstanceContainer(realDynamicContext);
                }
                return executeSubProcess((StatefulKnowledgeSessionImpl) ksession, processId, parameters, processInstance, subProcessNodeInstance);
            }
        });
    } else {
        throw new IllegalArgumentException("Unsupported ksession: " + ksession == null ? "null" : ksession.getClass().getName());
    }
}
Also used : RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) KieSession(org.kie.api.runtime.KieSession) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) ExecutableRunner(org.kie.api.runtime.ExecutableRunner) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 18 with WorkflowProcessInstance

use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.

the class MemoryLeakTest method createKnowledgeSessionStartProcessEtc.

private void createKnowledgeSessionStartProcessEtc(KieBase kbase) {
    logger.info("session count=" + kbase.getKieSessions().size());
    StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, getKnowledgeSessionConfiguration(), env);
    addEventListenersToSession(ksession);
    /**
     * The following log line caused the memory leak.
     * The specific (reverse-ordered) stack trace is the following:
     *
     *   MemoryLeakTest.createKnowledgeSessionStartProcessEtc(KnowledgeBase) calls kbase.getKieSessions()
     *   ..
     *   KnowledgeBaseImpl.getStatefulKnowledgeSessions() line: 186
     *   StatefulKnowledgeSessionImpl.<init>(ReteooWorkingMemory, KnowledgeBase) line: 121
     *   ReteooStatefulSession(AbstractWorkingMemory).setKnowledgeRuntime(InternalKnowledgeRuntime) line: 1268
     *   ReteooStatefulSession(AbstractWorkingMemory).createProcessRuntime() line: 342
     *   ProcessRuntimeFactory.newProcessRuntime(AbstractWorkingMemory) line: 12
     *   ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 1
     *   ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 10
     *   ProcessRuntimeImpl.<init>(AbstractWorkingMemory) line: 84
     *   ProcessRuntimeImpl.initProcessEventListeners() line: 215
     *
     * And ProcessRuntimeImpl.initProcessEventListeners() is what adds a new listener
     * to AbstractRuleBase.eventSupport.listeners via this line (235):
     *   kruntime.getKnowledgeBase().addEventListener(knowledgeBaseListener);
     *
     * The StatefulKnowledgeSessionImpl instance created in this .getStatefulKnowledgeSessions()
     * method is obviously never disposed, which means that the listener is never removed.
     * The listener then contains a link to a field (signalManager) of the ProcessRuntimeImpl,
     * which contains a link to the StatefulKnowledgeSessionImpl instance created here. etc..
     */
    logger.info("session count=" + kbase.getKieSessions().size());
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    try {
        // create process instance, insert into session and start process
        Map<String, Object> processParams = new HashMap<String, Object>();
        String[] fireballVarHolder = new String[1];
        processParams.put("fireball", fireballVarHolder);
        ProcessInstance processInstance = ksession.createProcessInstance(PROCESS_NAME, processParams);
        ksession.insert(processInstance);
        ksession.startProcessInstance(processInstance.getId());
        // after the log line has been added, the DefaultProcessEventListener registered
        // in the addEventListenersToSession() method no longer works?!?
        ksession.fireAllRules();
        // test process variables
        String[] procVar = (String[]) ((WorkflowProcessInstance) processInstance).getVariable("fireball");
        assertEquals("Rule task did NOT fire or complete.", "boom!", procVar[0]);
        // complete task and process
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("chaerg", new SerializableResult("zhrini", 302l, "F", "A", "T"));
        ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), results);
        assertNull(ksession.getProcessInstance(processInstance.getId()));
    } finally {
        // This should clean up all listeners, but doesn't -> see docs above
        ksession.dispose();
    }
}
Also used : TestWorkItemHandler(org.jbpm.bpmn2.objects.TestWorkItemHandler) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) ProcessInstance(org.kie.api.runtime.process.ProcessInstance)

Example 19 with WorkflowProcessInstance

use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.

the class IdentityProviderAwareProcessListenerTest method testUserNotSet.

@Test
public void testUserNotSet() {
    final WorkflowProcessInstance processInstance = mock(WorkflowProcessInstance.class);
    final HashMap<String, Object> metaData = new HashMap<>();
    when(processInstance.getMetaData()).thenReturn(metaData);
    final ProcessStartedEvent event = new ProcessStartedEventImpl(processInstance, mock(KieRuntime.class));
    listener.beforeProcessStarted(event);
    assertTrue(metaData.isEmpty());
    verify(processInstance, never()).setVariable(anyString(), anyString());
}
Also used : HashMap(java.util.HashMap) KieRuntime(org.kie.api.runtime.KieRuntime) ProcessStartedEvent(org.kie.api.event.process.ProcessStartedEvent) ProcessStartedEventImpl(org.drools.core.event.ProcessStartedEventImpl) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) Test(org.junit.Test)

Example 20 with WorkflowProcessInstance

use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.

the class AsyncWorkItemHandlerCmdCallback method onCommandError.

@Override
public void onCommandError(CommandContext ctx, final Throwable exception) {
    final Long processInstanceId = (Long) ctx.getData("processInstanceId");
    final WorkItem workItem = (WorkItem) ctx.getData("workItem");
    // find the right runtime to do the complete
    RuntimeManager manager = getRuntimeManager(ctx);
    RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
    final ExecutionErrorHandler errorHandler = getExecutionErrorHandler(manager);
    try {
        boolean isErrorHandled = engine.getKieSession().execute(new ExecutableCommand<Boolean>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Boolean execute(Context context) {
                KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
                WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
                NodeInstance nodeInstance = getNodeInstance(workItem, processInstance);
                Throwable actualException = exception;
                if (actualException instanceof AsyncJobException) {
                    actualException = exception.getCause();
                }
                String exceptionName = actualException.getClass().getName();
                ExceptionScopeInstance exceptionScopeInstance = (ExceptionScopeInstance) ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, exceptionName);
                if (exceptionScopeInstance != null) {
                    logger.debug("Handling job error '{}' via process error handling", actualException.getMessage());
                    exceptionScopeInstance.handleException(exceptionName, actualException);
                    return true;
                } else {
                    logger.debug("No process level error handling for '{}' letting it to be handled by execution errors", exception.getMessage());
                    errorHandler.processing(nodeInstance);
                    return false;
                }
            }
        });
        if (!isErrorHandled) {
            logger.debug("Error '{}' was not handled on process level, handling it via execution errors mechanism", exception.getMessage());
            errorHandler.handle(exception);
        }
    } catch (Exception e) {
        logger.error("Error when handling callback from executor", e);
    } finally {
        manager.disposeRuntimeEngine(engine);
        closeErrorHandler(manager);
    }
}
Also used : ProcessInstanceIdContext(org.kie.internal.runtime.manager.context.ProcessInstanceIdContext) CommandContext(org.kie.api.executor.CommandContext) RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) WorkItem(org.kie.api.runtime.process.WorkItem) AsyncJobException(org.jbpm.executor.AsyncJobException) ExecutionErrorHandler(org.kie.internal.runtime.error.ExecutionErrorHandler) NoOpExecutionErrorHandler(org.jbpm.process.instance.impl.NoOpExecutionErrorHandler) AsyncJobException(org.jbpm.executor.AsyncJobException) KieSession(org.kie.api.runtime.KieSession) NodeInstance(org.kie.api.runtime.process.NodeInstance) WorkItemNodeInstance(org.jbpm.workflow.instance.node.WorkItemNodeInstance) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) ExceptionScopeInstance(org.jbpm.process.instance.context.exception.ExceptionScopeInstance)

Aggregations

WorkflowProcessInstance (org.jbpm.workflow.instance.WorkflowProcessInstance)24 HashMap (java.util.HashMap)16 Test (org.junit.Test)15 KieSession (org.kie.api.runtime.KieSession)8 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)8 Date (java.util.Date)6 RegistryContext (org.drools.core.command.impl.RegistryContext)5 Context (org.kie.api.runtime.Context)5 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)5 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 ExecutableCommand (org.drools.core.command.impl.ExecutableCommand)3 NodeInstance (org.kie.api.runtime.process.NodeInstance)3 Matcher (java.util.regex.Matcher)2 CommandBasedStatefulKnowledgeSession (org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession)2 ProcessStartedEventImpl (org.drools.core.event.ProcessStartedEventImpl)2 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)2 SignallingTaskHandlerDecorator (org.jbpm.bpmn2.handler.SignallingTaskHandlerDecorator)2 SystemOutWorkItemHandler (org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler)2 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)2