Search in sources :

Example 1 with CorrelationKeyFactory

use of org.kie.internal.process.CorrelationKeyFactory in project droolsjbpm-knowledge by kiegroup.

the class CorrelationKeyXmlAdapter method unmarshalCorrelationKey.

/**
 * This method has been made "static"ally available so that
 * non-JAXB code does not have to (unnecesarily) instantiate
 * an instance fo this class.
 *
 * @param key A {@link CorrelationKey}
 * @return A {@link String} equivalent of the key
 */
public static CorrelationKey unmarshalCorrelationKey(String key) {
    CorrelationKeyFactory factory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
    if (key == null || key.isEmpty()) {
        return factory.newCorrelationKey(Collections.EMPTY_LIST);
    }
    List<String> keys = new ArrayList<String>();
    for (String k : key.split(":")) {
        keys.add(k);
    }
    return KieInternalServices.Factory.get().newCorrelationKeyFactory().newCorrelationKey(keys);
}
Also used : CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) ArrayList(java.util.ArrayList)

Example 2 with CorrelationKeyFactory

use of org.kie.internal.process.CorrelationKeyFactory in project jbpm by kiegroup.

the class CorrelationPersistenceTest method before.

@Before
public void before() throws Exception {
    context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
    CorrelationKeyFactory factory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
    // populate table with test data
    EntityManagerFactory emf = (EntityManagerFactory) context.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
    UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
    ut.begin();
    try {
        EntityManager em = emf.createEntityManager();
        em.persist(factory.newCorrelationKey("test123"));
        List<String> props = new ArrayList<String>();
        props.add("test123");
        props.add("123test");
        em.persist(factory.newCorrelationKey(props));
        ut.commit();
    } catch (Exception ex) {
        ut.rollback();
        Assert.fail("Exception thrown while trying to prepare correlation data.");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) EntityManagerFactory(javax.persistence.EntityManagerFactory) ArrayList(java.util.ArrayList) Before(org.junit.Before)

Example 3 with CorrelationKeyFactory

use of org.kie.internal.process.CorrelationKeyFactory in project jbpm by kiegroup.

the class PerProcessInstanceRuntimeManagerTest method testCreationOfSessionWithPersistenceByCorrelationKey.

@Test
public void testCreationOfSessionWithPersistenceByCorrelationKey() {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-ScriptTask.bpmn2"), ResourceType.BPMN2).addAsset(ResourceFactory.newClassPathResource("BPMN2-UserTask.bpmn2"), ResourceType.BPMN2).get();
    CorrelationKeyFactory keyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
    manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);
    assertNotNull(manager);
    // ksession for process instance #1
    // since there is no process instance yet we need to get new session
    CorrelationKey key = keyFactory.newCorrelationKey("first");
    RuntimeEngine runtime = manager.getRuntimeEngine(CorrelationKeyContext.get());
    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);
    long ksession1Id = ksession.getIdentifier();
    assertTrue(ksession1Id == 2);
    // ksession for process instance #2
    // since there is no process instance yet we need to get new session
    CorrelationKey key2 = keyFactory.newCorrelationKey("second");
    RuntimeEngine runtime2 = manager.getRuntimeEngine(CorrelationKeyContext.get());
    KieSession ksession2 = runtime2.getKieSession();
    assertNotNull(ksession2);
    long ksession2Id = ksession2.getIdentifier();
    assertTrue(ksession2Id == 3);
    ProcessInstance pi1 = ((CorrelationAwareProcessRuntime) ksession).startProcess("UserTask", key, null);
    ProcessInstance pi2 = ((CorrelationAwareProcessRuntime) ksession2).startProcess("UserTask", key2, null);
    // both processes started
    assertEquals(ProcessInstance.STATE_ACTIVE, pi1.getState());
    assertEquals(ProcessInstance.STATE_ACTIVE, pi2.getState());
    runtime = manager.getRuntimeEngine(CorrelationKeyContext.get(key));
    ksession = runtime.getKieSession();
    assertEquals(ksession1Id, ksession.getIdentifier());
    ksession.getWorkItemManager().completeWorkItem(1, null);
    // since process is completed now session should not be there any more
    try {
        manager.getRuntimeEngine(CorrelationKeyContext.get(key)).getKieSession();
        fail("Session for this (" + pi1.getId() + ") process instance is no more accessible");
    } catch (RuntimeException e) {
    }
    runtime2 = manager.getRuntimeEngine(CorrelationKeyContext.get(key2));
    ksession2 = runtime2.getKieSession();
    assertEquals(ksession2Id, ksession2.getIdentifier());
    ksession2.getWorkItemManager().completeWorkItem(2, null);
    // since process is completed now session should not be there any more
    try {
        manager.getRuntimeEngine(CorrelationKeyContext.get(key2)).getKieSession();
        fail("Session for this (" + pi2.getId() + ") process instance is no more accessible");
    } catch (RuntimeException e) {
    }
    manager.close();
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) CorrelationAwareProcessRuntime(org.kie.internal.process.CorrelationAwareProcessRuntime) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) CorrelationKey(org.kie.internal.process.CorrelationKey) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest) Test(org.junit.Test)

Example 4 with CorrelationKeyFactory

use of org.kie.internal.process.CorrelationKeyFactory in project jbpm by kiegroup.

the class SubProcessNodeInstance method internalTrigger.

public void internalTrigger(final NodeInstance from, String type) {
    super.internalTrigger(from, type);
    // if node instance was cancelled, abort
    if (getNodeInstanceContainer().getNodeInstance(getId()) == null) {
        return;
    }
    if (!org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
        throw new IllegalArgumentException("A SubProcess node only accepts default incoming connections!");
    }
    Map<String, Object> parameters = new HashMap<String, Object>();
    for (Iterator<DataAssociation> iterator = getSubProcessNode().getInAssociations().iterator(); iterator.hasNext(); ) {
        DataAssociation mapping = iterator.next();
        Object parameterValue = null;
        if (mapping.getTransformation() != null) {
            Transformation transformation = mapping.getTransformation();
            DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
            if (transformer != null) {
                parameterValue = transformer.transform(transformation.getCompiledExpression(), getSourceParameters(mapping));
            }
        } else {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, mapping.getSources().get(0));
            if (variableScopeInstance != null) {
                parameterValue = variableScopeInstance.getVariable(mapping.getSources().get(0));
            } else {
                try {
                    parameterValue = MVELSafeHelper.getEvaluator().eval(mapping.getSources().get(0), new NodeInstanceResolverFactory(this));
                } catch (Throwable t) {
                    parameterValue = VariableUtil.resolveVariable(mapping.getSources().get(0), this);
                    if (parameterValue != null) {
                        parameters.put(mapping.getTarget(), parameterValue);
                    } else {
                        logger.error("Could not find variable scope for variable {}", mapping.getSources().get(0));
                        logger.error("when trying to execute SubProcess node {}", getSubProcessNode().getName());
                        logger.error("Continuing without setting parameter.");
                    }
                }
            }
        }
        if (parameterValue != null) {
            parameters.put(mapping.getTarget(), parameterValue);
        }
    }
    String processId = getSubProcessNode().getProcessId();
    if (processId == null) {
        // if process id is not given try with process name
        processId = getSubProcessNode().getProcessName();
    }
    // resolve processId if necessary
    Map<String, String> replacements = new HashMap<String, String>();
    Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(processId);
    while (matcher.find()) {
        String paramName = matcher.group(1);
        if (replacements.get(paramName) == null) {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
            if (variableScopeInstance != null) {
                Object variableValue = variableScopeInstance.getVariable(paramName);
                String variableValueString = variableValue == null ? "" : variableValue.toString();
                replacements.put(paramName, variableValueString);
            } else {
                try {
                    Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
                    String variableValueString = variableValue == null ? "" : variableValue.toString();
                    replacements.put(paramName, variableValueString);
                } catch (Throwable t) {
                    logger.error("Could not find variable scope for variable {}", paramName);
                    logger.error("when trying to replace variable in processId for sub process {}", getNodeName());
                    logger.error("Continuing without setting process id.");
                }
            }
        }
    }
    for (Map.Entry<String, String> replacement : replacements.entrySet()) {
        processId = processId.replace("#{" + replacement.getKey() + "}", replacement.getValue());
    }
    KieBase kbase = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getKieBase();
    // start process instance
    Process process = kbase.getProcess(processId);
    if (process == null) {
        // try to find it by name
        String latestProcessId = StartProcessHelper.findLatestProcessByName(kbase, processId);
        if (latestProcessId != null) {
            processId = latestProcessId;
            process = kbase.getProcess(processId);
        }
    }
    if (process == null) {
        logger.error("Could not find process {}", processId);
        logger.error("Aborting process");
        ((ProcessInstance) getProcessInstance()).setState(ProcessInstance.STATE_ABORTED);
        throw new RuntimeException("Could not find process " + processId);
    } else {
        KieRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
        RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
        if (manager != null) {
            org.kie.api.runtime.manager.Context<?> context = ProcessInstanceIdContext.get();
            String caseId = (String) kruntime.getEnvironment().get(EnvironmentName.CASE_ID);
            if (caseId != null) {
                context = CaseContext.get(caseId);
            }
            RuntimeEngine runtime = manager.getRuntimeEngine(context);
            kruntime = (KieRuntime) runtime.getKieSession();
        }
        if (getSubProcessNode().getMetaData("MICollectionInput") != null) {
            // remove foreach input variable to avoid problems when running in variable strict mode
            parameters.remove(getSubProcessNode().getMetaData("MICollectionInput"));
        }
        ProcessInstance processInstance = null;
        if (((WorkflowProcessInstanceImpl) getProcessInstance()).getCorrelationKey() != null) {
            // in case there is correlation key on parent instance pass it along to child so it can be easily correlated
            // since correlation key must be unique for active instances it appends processId and timestamp
            List<String> businessKeys = new ArrayList<String>();
            businessKeys.add(((WorkflowProcessInstanceImpl) getProcessInstance()).getCorrelationKey());
            businessKeys.add(processId);
            businessKeys.add(String.valueOf(System.currentTimeMillis()));
            CorrelationKeyFactory correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
            CorrelationKey subProcessCorrelationKey = correlationKeyFactory.newCorrelationKey(businessKeys);
            processInstance = (ProcessInstance) ((CorrelationAwareProcessRuntime) kruntime).createProcessInstance(processId, subProcessCorrelationKey, parameters);
        } else {
            processInstance = (ProcessInstance) kruntime.createProcessInstance(processId, parameters);
        }
        this.processInstanceId = processInstance.getId();
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentProcessInstanceId", getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeInstanceId", getUniqueId());
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeId", getSubProcessNode().getUniqueId());
        ((ProcessInstanceImpl) processInstance).setParentProcessInstanceId(getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setSignalCompletion(getSubProcessNode().isWaitForCompletion());
        kruntime.startProcessInstance(processInstance.getId());
        if (!getSubProcessNode().isWaitForCompletion()) {
            triggerCompleted();
        } else if (processInstance.getState() == ProcessInstance.STATE_COMPLETED || processInstance.getState() == ProcessInstance.STATE_ABORTED) {
            processInstanceCompleted(processInstance);
        } else {
            addProcessListener();
        }
    }
}
Also used : Transformation(org.jbpm.workflow.core.node.Transformation) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Process(org.kie.api.definition.process.Process) DataTransformer(org.kie.api.runtime.process.DataTransformer) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) CorrelationKey(org.kie.internal.process.CorrelationKey) KieBase(org.kie.api.KieBase) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) CorrelationAwareProcessRuntime(org.kie.internal.process.CorrelationAwareProcessRuntime) DataAssociation(org.jbpm.workflow.core.node.DataAssociation) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) ProcessInstanceImpl(org.jbpm.process.instance.impl.ProcessInstanceImpl) KieRuntime(org.kie.api.runtime.KieRuntime) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory) ProcessInstance(org.jbpm.process.instance.ProcessInstance) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with CorrelationKeyFactory

use of org.kie.internal.process.CorrelationKeyFactory in project jbpm by kiegroup.

the class DynamicUtils method executeSubProcess.

private static long executeSubProcess(StatefulKnowledgeSessionImpl ksession, String processId, Map<String, Object> parameters, ProcessInstance processInstance, SubProcessNodeInstance subProcessNodeInstance) {
    Process process = ksession.getKieBase().getProcess(processId);
    if (process == null) {
        logger.error("Could not find process {}", processId);
        throw new IllegalArgumentException("No process definition found with id: " + processId);
    } else {
        ProcessEventSupport eventSupport = ((InternalProcessRuntime) ((InternalKnowledgeRuntime) ksession).getProcessRuntime()).getProcessEventSupport();
        eventSupport.fireBeforeNodeTriggered(subProcessNodeInstance, ksession);
        ProcessInstance subProcessInstance = null;
        if (((WorkflowProcessInstanceImpl) processInstance).getCorrelationKey() != null) {
            List<String> businessKeys = new ArrayList<String>();
            businessKeys.add(((WorkflowProcessInstanceImpl) processInstance).getCorrelationKey());
            businessKeys.add(processId);
            businessKeys.add(String.valueOf(System.currentTimeMillis()));
            CorrelationKeyFactory correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
            CorrelationKey subProcessCorrelationKey = correlationKeyFactory.newCorrelationKey(businessKeys);
            subProcessInstance = (ProcessInstance) ((CorrelationAwareProcessRuntime) ksession).createProcessInstance(processId, subProcessCorrelationKey, parameters);
        } else {
            subProcessInstance = (ProcessInstance) ksession.createProcessInstance(processId, parameters);
        }
        ((ProcessInstanceImpl) subProcessInstance).setMetaData("ParentProcessInstanceId", processInstance.getId());
        ((ProcessInstanceImpl) subProcessInstance).setParentProcessInstanceId(processInstance.getId());
        subProcessInstance = (ProcessInstance) ksession.startProcessInstance(subProcessInstance.getId());
        subProcessNodeInstance.internalSetProcessInstanceId(subProcessInstance.getId());
        eventSupport.fireAfterNodeTriggered(subProcessNodeInstance, ksession);
        if (subProcessInstance.getState() == ProcessInstance.STATE_COMPLETED) {
            subProcessNodeInstance.triggerCompleted();
        } else {
            subProcessNodeInstance.addEventListeners();
        }
        return subProcessInstance.getId();
    }
}
Also used : ProcessEventSupport(org.drools.core.event.ProcessEventSupport) CorrelationAwareProcessRuntime(org.kie.internal.process.CorrelationAwareProcessRuntime) CorrelationKey(org.kie.internal.process.CorrelationKey) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) ProcessInstanceImpl(org.jbpm.process.instance.impl.ProcessInstanceImpl) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) ArrayList(java.util.ArrayList) Process(org.kie.api.definition.process.Process) InternalProcessRuntime(org.jbpm.process.instance.InternalProcessRuntime) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) ProcessInstance(org.jbpm.process.instance.ProcessInstance)

Aggregations

CorrelationKeyFactory (org.kie.internal.process.CorrelationKeyFactory)5 ArrayList (java.util.ArrayList)4 CorrelationAwareProcessRuntime (org.kie.internal.process.CorrelationAwareProcessRuntime)3 CorrelationKey (org.kie.internal.process.CorrelationKey)3 ProcessInstance (org.jbpm.process.instance.ProcessInstance)2 ProcessInstanceImpl (org.jbpm.process.instance.impl.ProcessInstanceImpl)2 WorkflowProcessInstanceImpl (org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl)2 Process (org.kie.api.definition.process.Process)2 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Matcher (java.util.regex.Matcher)1 EntityManager (javax.persistence.EntityManager)1 EntityManagerFactory (javax.persistence.EntityManagerFactory)1 UserTransaction (javax.transaction.UserTransaction)1 ProcessEventSupport (org.drools.core.event.ProcessEventSupport)1 InternalProcessRuntime (org.jbpm.process.instance.InternalProcessRuntime)1 VariableScopeInstance (org.jbpm.process.instance.context.variable.VariableScopeInstance)1 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)1 DataAssociation (org.jbpm.workflow.core.node.DataAssociation)1