Search in sources :

Example 91 with WorkItem

use of org.kie.api.runtime.process.WorkItem in project jbpm by kiegroup.

the class ProcessHumanTaskTest method testHumanTaskCancel.

@Test
public void testHumanTaskCancel() {
    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.humantask\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + "  <header>\n" + "  </header>\n" + "\n" + "  <nodes>\n" + "    <start id=\"1\" name=\"Start\" />\n" + "    <humanTask id=\"2\" name=\"HumanTask\" >\n" + "      <work name=\"Human Task\" >\n" + "        <parameter name=\"ActorId\" >\n" + "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" + "          <value>John Doe</value>\n" + "        </parameter>\n" + "        <parameter name=\"TaskName\" >\n" + "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" + "          <value>Do something</value>\n" + "        </parameter>\n" + "        <parameter name=\"Priority\" >\n" + "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" + "        </parameter>\n" + "        <parameter name=\"Comment\" >\n" + "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" + "        </parameter>\n" + "      </work>\n" + "    </humanTask>\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 workingMemory = createKieSession(builder.getPackages());
    TestWorkItemHandler handler = new TestWorkItemHandler();
    workingMemory.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ProcessInstance processInstance = (ProcessInstance) workingMemory.startProcess("org.drools.humantask");
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    processInstance.setState(ProcessInstance.STATE_ABORTED);
    assertTrue(handler.isAborted());
}
Also used : TestWorkItemHandler(org.jbpm.integrationtests.handler.TestWorkItemHandler) StringReader(java.io.StringReader) StringReader(java.io.StringReader) Reader(java.io.Reader) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.jbpm.process.instance.ProcessInstance) WorkItem(org.kie.api.runtime.process.WorkItem) Test(org.junit.Test) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest)

Example 92 with WorkItem

use of org.kie.api.runtime.process.WorkItem in project jbpm by kiegroup.

the class SubProcessTest method testAsynchronousSubProcess.

@Test
public void testAsynchronousSubProcess() {
    RuleFlowProcess process = new RuleFlowProcess();
    process.setId("org.drools.core.process.process");
    process.setName("Process");
    StartNode startNode = new StartNode();
    startNode.setName("Start");
    startNode.setId(1);
    process.addNode(startNode);
    EndNode endNode = new EndNode();
    endNode.setName("EndNode");
    endNode.setId(2);
    process.addNode(endNode);
    SubProcessNode subProcessNode = new SubProcessNode();
    subProcessNode.setName("SubProcessNode");
    subProcessNode.setId(3);
    subProcessNode.setProcessId("org.drools.core.process.subprocess");
    process.addNode(subProcessNode);
    new ConnectionImpl(startNode, Node.CONNECTION_DEFAULT_TYPE, subProcessNode, Node.CONNECTION_DEFAULT_TYPE);
    new ConnectionImpl(subProcessNode, Node.CONNECTION_DEFAULT_TYPE, endNode, Node.CONNECTION_DEFAULT_TYPE);
    RuleFlowProcess subProcess = new RuleFlowProcess();
    subProcess.setId("org.drools.core.process.subprocess");
    subProcess.setName("SubProcess");
    startNode = new StartNode();
    startNode.setName("Start");
    startNode.setId(1);
    subProcess.addNode(startNode);
    endNode = new EndNode();
    endNode.setName("EndNode");
    endNode.setId(2);
    subProcess.addNode(endNode);
    WorkItemNode workItemNode = new WorkItemNode();
    workItemNode.setName("WorkItem");
    Work work = new WorkImpl();
    work.setName("MyWork");
    workItemNode.setWork(work);
    workItemNode.setId(4);
    subProcess.addNode(workItemNode);
    new ConnectionImpl(startNode, Node.CONNECTION_DEFAULT_TYPE, workItemNode, Node.CONNECTION_DEFAULT_TYPE);
    new ConnectionImpl(workItemNode, Node.CONNECTION_DEFAULT_TYPE, endNode, Node.CONNECTION_DEFAULT_TYPE);
    KieSession ksession = createKieSession(process, subProcess);
    ksession.getWorkItemManager().registerWorkItemHandler("MyWork", new WorkItemHandler() {

        public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
            logger.info("Executing work item");
            SubProcessTest.this.workItem = workItem;
        }

        public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
        }
    });
    ksession.startProcess("org.drools.core.process.process");
    TestProcessEventListener procEventListener = new TestProcessEventListener();
    ksession.addEventListener(procEventListener);
    assertNotNull(workItem);
    assertEquals(2, ksession.getProcessInstances().size());
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertEquals(0, ksession.getProcessInstances().size());
    verifyEventHistory(asyncEventOrder, procEventListener.getEventHistory());
}
Also used : RuleFlowProcess(org.jbpm.ruleflow.core.RuleFlowProcess) StartNode(org.jbpm.workflow.core.node.StartNode) ConnectionImpl(org.jbpm.workflow.core.impl.ConnectionImpl) WorkItem(org.kie.api.runtime.process.WorkItem) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) EndNode(org.jbpm.workflow.core.node.EndNode) SubProcessNode(org.jbpm.workflow.core.node.SubProcessNode) WorkItemNode(org.jbpm.workflow.core.node.WorkItemNode) Work(org.jbpm.process.core.Work) WorkImpl(org.jbpm.process.core.impl.WorkImpl) KieSession(org.kie.api.runtime.KieSession) WorkItemManager(org.kie.api.runtime.process.WorkItemManager) TestProcessEventListener(org.jbpm.process.test.TestProcessEventListener) Test(org.junit.Test) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest)

Example 93 with WorkItem

use of org.kie.api.runtime.process.WorkItem in project jbpm by kiegroup.

the class StartCaseWorkItemHandler method parseParameters.

protected void parseParameters(WorkItem workItem, Map<String, Object> caseFileData, Map<String, OrganizationalEntity> roleAssignments, Map<String, List<String>> accessRestrictions) {
    TaskModelFactory taskModelFactory = TaskModelProvider.getFactory();
    CaseFileInstance caseFile = getCaseFile(ksession);
    for (Entry<String, Object> entry : workItem.getParameters().entrySet()) {
        if (entry.getKey().startsWith(DATA_PREFIX)) {
            String name = entry.getKey().replaceFirst(DATA_PREFIX, "");
            caseFileData.put(name, entry.getValue());
            logger.debug("Added {} item to case file with value {}", name, entry.getValue());
        } else if (entry.getKey().startsWith(USER_ROLE_PREFIX)) {
            String name = entry.getKey().replaceFirst(USER_ROLE_PREFIX, "");
            User user = taskModelFactory.newUser((String) entry.getValue());
            if (caseFile != null) {
                try {
                    Collection<OrganizationalEntity> caseAssignments = ((CaseAssignment) caseFile).getAssignments(name);
                    user = (User) caseAssignments.stream().filter(oe -> oe instanceof User).findFirst().orElseThrow(() -> new IllegalArgumentException());
                } catch (IllegalArgumentException e) {
                    logger.debug("no such role {} or there is no user found for given role name", name);
                }
            }
            roleAssignments.put(name, user);
            logger.debug("Added user {} as assignment to the role {}", entry.getValue(), entry.getKey());
        } else if (entry.getKey().startsWith(GROUP_ROLE_PREFIX)) {
            String name = entry.getKey().replaceFirst(GROUP_ROLE_PREFIX, "");
            Group group = taskModelFactory.newGroup((String) entry.getValue());
            if (caseFile != null) {
                try {
                    Collection<OrganizationalEntity> caseAssignments = ((CaseAssignment) caseFile).getAssignments(name);
                    group = (Group) caseAssignments.stream().filter(oe -> oe instanceof Group).findFirst().orElseThrow(() -> new IllegalArgumentException());
                } catch (IllegalArgumentException e) {
                    logger.debug("no such role {} or there is no group found for given role name", name);
                }
            }
            roleAssignments.put(name, group);
            logger.debug("Added group {} as assignment to the role {}", entry.getValue(), entry.getKey());
        } else if (entry.getKey().startsWith(DATA_ACCESS_PREFIX)) {
            String name = entry.getKey().replaceFirst(DATA_ACCESS_PREFIX, "");
            String[] roles = ((String) entry.getValue()).split(",");
            List<String> restrictedTo = new ArrayList<>(Arrays.asList(roles));
            accessRestrictions.put(name, restrictedTo);
            logger.debug("Added access restriction for {} with following roles {}", name, restrictedTo);
        }
    }
}
Also used : Arrays(java.util.Arrays) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) RuntimeManagerRegistry(org.kie.internal.runtime.manager.RuntimeManagerRegistry) PerCaseRuntimeManager(org.jbpm.runtime.manager.impl.PerCaseRuntimeManager) CaseNotFoundException(org.jbpm.casemgmt.api.CaseNotFoundException) CaseFileInstance(org.jbpm.casemgmt.api.model.instance.CaseFileInstance) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) CaseAssignment(org.kie.api.runtime.process.CaseAssignment) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) ArrayList(java.util.ArrayList) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) Map(java.util.Map) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) TaskModelFactory(org.kie.internal.task.api.TaskModelFactory) KieSession(org.kie.api.runtime.KieSession) User(org.kie.api.task.model.User) WorkItemManager(org.kie.api.runtime.process.WorkItemManager) Logger(org.slf4j.Logger) WorkItem(org.kie.api.runtime.process.WorkItem) Collection(java.util.Collection) CaseService(org.jbpm.casemgmt.api.CaseService) TaskModelProvider(org.kie.internal.task.api.TaskModelProvider) ClassObjectFilter(org.drools.core.ClassObjectFilter) List(java.util.List) Group(org.kie.api.task.model.Group) Entry(java.util.Map.Entry) CaseFileInstanceImpl(org.jbpm.casemgmt.impl.model.instance.CaseFileInstanceImpl) ServiceRegistry(org.jbpm.services.api.service.ServiceRegistry) Group(org.kie.api.task.model.Group) User(org.kie.api.task.model.User) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) CaseAssignment(org.kie.api.runtime.process.CaseAssignment) CaseFileInstance(org.jbpm.casemgmt.api.model.instance.CaseFileInstance) TaskModelFactory(org.kie.internal.task.api.TaskModelFactory) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List)

Example 94 with WorkItem

use of org.kie.api.runtime.process.WorkItem in project jbpm by kiegroup.

the class AbstractAuditLogServiceTest method runTestLoggerWithCustomVariableLogLength.

public static void runTestLoggerWithCustomVariableLogLength(KieSession session, AuditLogService auditLogService) throws Exception {
    System.setProperty("org.jbpm.var.log.length", "15");
    final List<Long> workItemIds = new ArrayList<Long>();
    session.getWorkItemManager().registerWorkItemHandler("Human Task", new WorkItemHandler() {

        public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
            workItemIds.add(workItem.getId());
        }

        public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
        }
    });
    // record the initial count to compare to later
    List<ProcessInstanceLog> processInstances = auditLogService.findProcessInstances("com.sample.ruleflow");
    int initialProcessInstanceSize = processInstances.size();
    processInstances = auditLogService.findActiveProcessInstances();
    int initialActiveProcessInstanceSize = processInstances.size();
    // prepare variable value
    String variableValue = "very short value that should be trimmed by custom variable log length";
    // start process instance
    Map<String, Object> params = new HashMap<String, Object>();
    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    params.put("list", list);
    params.put("s", variableValue);
    long processInstanceId = session.startProcess("com.sample.ruleflow3", params).getId();
    int numActiveProcesses = auditLogService.findActiveProcessInstances().size();
    Assertions.assertThat(numActiveProcesses).isEqualTo(initialActiveProcessInstanceSize + 1).withFailMessage("find active processes did not work");
    // Test findVariableInstancesByName* methods: check for variables (only) in active processes
    List<VariableInstanceLog> varLogs = auditLogService.findVariableInstancesByName("s", true);
    varLogs = varLogs.stream().sorted((o1, o2) -> Long.compare(o1.getId(), o2.getId())).collect(Collectors.toList());
    Assertions.assertThat(varLogs).isNotEmpty();
    Assertions.assertThat(varLogs.size()).isEqualTo(2);
    Assertions.assertThat(varLogs).flatExtracting(VariableInstanceLog::getValue).containsExactly("InitialValue", variableValue.substring(0, 15));
    for (Long workItemId : workItemIds) {
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("Result", "ResultValue");
        session.getWorkItemManager().completeWorkItem(workItemId, results);
    }
    logger.debug("Checking process instances for process 'com.sample.ruleflow3'");
    processInstances = auditLogService.findProcessInstances("com.sample.ruleflow3");
    Assertions.assertThat(processInstances.size()).isEqualTo(initialProcessInstanceSize + 1);
    ProcessInstanceLog processInstance = processInstances.get(initialProcessInstanceSize);
    logger.debug("{} -> {} - {}", processInstance.toString(), processInstance.getStart(), processInstance.getEnd());
    Assertions.assertThat(processInstance.getStart()).isNotNull();
    Assertions.assertThat(processInstance.getEnd()).isNotNull().withFailMessage("ProcessInstanceLog does not contain end date.");
    Assertions.assertThat(processInstance.getProcessInstanceId().longValue()).isEqualTo(processInstanceId);
    Assertions.assertThat(processInstance.getProcessId()).isEqualTo("com.sample.ruleflow3");
    List<VariableInstanceLog> variableInstances = auditLogService.findVariableInstances(processInstanceId);
    Assertions.assertThat(variableInstances.size()).isEqualTo(12);
    for (VariableInstanceLog variableInstance : variableInstances) {
        logger.debug(variableInstance.toString());
        Assertions.assertThat(processInstance.getProcessInstanceId().longValue()).isEqualTo(processInstanceId);
        Assertions.assertThat(processInstance.getProcessId()).isEqualTo("com.sample.ruleflow3");
        Assertions.assertThat(variableInstance.getDate()).isNotNull();
    }
    // Test findVariableInstancesByName* methods
    List<VariableInstanceLog> emptyVarLogs = auditLogService.findVariableInstancesByName("s", true);
    Assertions.assertThat(emptyVarLogs).isEmpty();
    for (VariableInstanceLog origVarLog : variableInstances) {
        varLogs = auditLogService.findVariableInstancesByName(origVarLog.getVariableId(), false);
        for (VariableInstanceLog varLog : varLogs) {
            Assertions.assertThat(varLog.getVariableId()).isEqualTo(origVarLog.getVariableId());
        }
    }
    emptyVarLogs = auditLogService.findVariableInstancesByNameAndValue("s", "InitialValue", true);
    Assertions.assertThat(emptyVarLogs).isEmpty();
    String varId = "s";
    String varValue = "ResultValue";
    variableInstances = auditLogService.findVariableInstancesByNameAndValue(varId, varValue, false);
    Assertions.assertThat(variableInstances.size()).isEqualTo(3);
    VariableInstanceLog varLog = variableInstances.get(0);
    Assertions.assertThat(varLog.getVariableId()).isEqualTo(varId);
    Assertions.assertThat(varLog.getValue()).isEqualTo(varValue);
    auditLogService.clear();
    processInstances = auditLogService.findProcessInstances("com.sample.ruleflow3");
    Assertions.assertThat(processInstances).isEmpty();
}
Also used : WorkItem(org.kie.api.runtime.process.WorkItem) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) SystemOutWorkItemHandler(org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler) WorkItemManager(org.kie.api.runtime.process.WorkItemManager)

Example 95 with WorkItem

use of org.kie.api.runtime.process.WorkItem in project jbpm by kiegroup.

the class ProcessTest method main.

public static final void main(String[] args) {
    try {
        // load up the knowledge base
        final KieSession ksession = getKieSession();
        UIWorkItemHandler handler = new UIWorkItemHandler();
        ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
        handler.setVisible(true);
        ksession.getWorkItemManager().registerWorkItemHandler("Email", new WorkItemHandler() {

            public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
                System.out.println("Sending email ...");
                manager.completeWorkItem(workItem.getId(), null);
            }

            public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
            }
        });
        KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newFileLogger(ksession, "test");
        // start a new process instance
        Person person = new Person("john", "John Doe");
        person.setAge(20);
        Request request = new Request("12345");
        request.setPersonId("john");
        request.setAmount(1000L);
        ksession.insert(person);
        ksession.insert(request);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("request", request);
        WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("com.sample.requestHandling", params);
        ksession.insert(processInstance);
        ksession.fireAllRules();
        // signaling to select tasks in the ad-hoc sub-process
        ksession.signalEvent("Investigate", null, processInstance.getId());
        // dynamically adding a new sub-process
        DynamicNodeInstance dynamicNodeInstance = (DynamicNodeInstance) processInstance.getNodeInstances().iterator().next();
        DynamicUtils.addDynamicSubProcess(dynamicNodeInstance, ksession, "com.sample.contactCustomer", null);
        // event processing to detect too much processes being started
        ksession.addEventListener(new DefaultProcessEventListener() {

            public void beforeProcessStarted(ProcessStartedEvent event) {
                ksession.insert(event);
            }
        });
        Request request2 = new Request("12346");
        request2.setPersonId("john");
        request2.setAmount(1000L);
        params = new HashMap<String, Object>();
        params.put("request", request2);
        ksession.startProcess("com.sample.requestHandling", params);
        ksession.fireAllRules();
        Request request3 = new Request("12347");
        request3.setPersonId("john");
        request3.setAmount(1000L);
        params = new HashMap<String, Object>();
        params.put("request", request);
        ksession.startProcess("com.sample.requestHandling", params);
        ksession.fireAllRules();
        Request request4 = new Request("12348");
        request4.setPersonId("john");
        request4.setAmount(1000L);
        params = new HashMap<String, Object>();
        params.put("request", request4);
        ksession.startProcess("com.sample.requestHandling", params);
        ksession.fireAllRules();
        Request request5 = new Request("12349");
        request5.setPersonId("john");
        request5.setAmount(1000L);
        params = new HashMap<String, Object>();
        params.put("request", request5);
        ksession.startProcess("com.sample.requestHandling", params);
        ksession.fireAllRules();
        Request request6 = new Request("12350");
        request6.setPersonId("john");
        request6.setAmount(1000L);
        params = new HashMap<String, Object>();
        params.put("request", request6);
        processInstance = (WorkflowProcessInstance) ksession.startProcess("com.sample.requestHandling", params);
        FactHandle handle = ksession.insert(request6);
        ksession.insert(processInstance);
        ksession.fireAllRules();
        // exception handling when canceling request
        request6.setCanceled(true);
        ksession.update(handle, request6);
        ksession.fireAllRules();
        logger.close();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : DynamicNodeInstance(org.jbpm.workflow.instance.node.DynamicNodeInstance) HashMap(java.util.HashMap) FactHandle(org.kie.api.runtime.rule.FactHandle) ProcessStartedEvent(org.kie.api.event.process.ProcessStartedEvent) WorkItem(org.kie.api.runtime.process.WorkItem) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) KieRuntimeLogger(org.kie.api.logger.KieRuntimeLogger) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) KieSession(org.kie.api.runtime.KieSession) WorkItemManager(org.kie.api.runtime.process.WorkItemManager) WorkflowProcessInstance(org.kie.api.runtime.process.WorkflowProcessInstance)

Aggregations

WorkItem (org.kie.api.runtime.process.WorkItem)174 Test (org.junit.Test)139 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)127 KieBase (org.kie.api.KieBase)110 TestWorkItemHandler (org.jbpm.bpmn2.objects.TestWorkItemHandler)91 WorkflowProcessInstance (org.kie.api.runtime.process.WorkflowProcessInstance)87 HashMap (java.util.HashMap)72 KieSession (org.kie.api.runtime.KieSession)48 WorkItemManager (org.kie.api.runtime.process.WorkItemManager)33 ArrayList (java.util.ArrayList)29 DefaultProcessEventListener (org.kie.api.event.process.DefaultProcessEventListener)27 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)26 WorkItemHandler (org.kie.api.runtime.process.WorkItemHandler)22 SystemOutWorkItemHandler (org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler)20 NodeLeftCountDownProcessEventListener (org.jbpm.test.listener.NodeLeftCountDownProcessEventListener)14 TestWorkItemHandler (org.jbpm.persistence.session.objects.TestWorkItemHandler)13 ProcessEventListener (org.kie.api.event.process.ProcessEventListener)13 Map (java.util.Map)11 StringReader (java.io.StringReader)10 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)10