Search in sources :

Example 91 with RuntimeEnvironment

use of org.kie.api.runtime.manager.RuntimeEnvironment in project jbpm by kiegroup.

the class GlobalQuartzDBTimerServiceTest method testAbortGlobalTestService.

/**
 * Test that illustrates that jobs are persisted and survives server restart
 * and as soon as GlobalTimerService is active jobs are fired and it loads and aborts the
 * process instance to illustrate jobs are properly removed when isntance is aborted
 * NOTE: this test is disabled by default as it requires real db (not in memory)
 * and test to be executed separately each with new jvm process
 */
@Test
@Ignore
public void testAbortGlobalTestService() throws Exception {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycle3.bpmn2"), ResourceType.BPMN2).addConfiguration("drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate").get();
    RuntimeManager manger = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    // build GlobalTimerService instance
    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener = new DefaultProcessEventListener() {

        @Override
        public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
                timerExporations.add(event.getProcessInstance().getId());
            }
        }
    };
    long id = -1;
    Thread.sleep(5000);
    RuntimeEngine runtime = manger.getRuntimeEngine(ProcessInstanceIdContext.get());
    KieSession ksession = runtime.getKieSession();
    ksession.addEventListener(listener);
    ksession.abortProcessInstance(id);
    ProcessInstance processInstance = ksession.getProcessInstance(id);
    assertNull(processInstance);
    // let's wait to ensure no more timers are expired and triggered
    Thread.sleep(3000);
    ksession.dispose();
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) ArrayList(java.util.ArrayList) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) ProcessNodeLeftEvent(org.kie.api.event.process.ProcessNodeLeftEvent) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 92 with RuntimeEnvironment

use of org.kie.api.runtime.manager.RuntimeEnvironment in project jbpm by kiegroup.

the class GlobalTimerServiceVolumeTest method setup.

@Before
public void setup() {
    Properties properties = new Properties();
    properties.setProperty("mary", "HR");
    properties.setProperty("john", "HR");
    userGroupCallback = new JBossUserGroupCallbackImpl(properties);
    System.setProperty("org.quartz.properties", "quartz-db.properties");
    testCreateQuartzSchema();
    globalScheduler = new QuartzSchedulerService();
    emf = Persistence.createEntityManagerFactory("org.jbpm.test.persistence");
    countDownListener = new NodeLeftCountDownProcessEventListener("timer", numberOfProcesses);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener = new DefaultProcessEventListener() {

        @Override
        public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
                timerExporations.add(event.getProcessInstance().getId());
            }
        }
    };
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycleWithHT3.bpmn2"), ResourceType.BPMN2).schedulerService(globalScheduler).registerableItemsFactory(new TestRegisterableItemsFactory(listener, countDownListener)).get();
    if ("processinstance".equals(strategy)) {
        manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment, "first");
    } else if ("request".equals(strategy)) {
        manager = RuntimeManagerFactory.Factory.get().newPerRequestRuntimeManager(environment, "first");
    } else if ("case".equals(strategy)) {
        manager = RuntimeManagerFactory.Factory.get().newPerCaseRuntimeManager(environment, "first");
    } else {
        throw new RuntimeException("Unknow type of runtime strategy");
    }
}
Also used : RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) QuartzSchedulerService(org.jbpm.process.core.timer.impl.QuartzSchedulerService) JBossUserGroupCallbackImpl(org.jbpm.services.task.identity.JBossUserGroupCallbackImpl) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ArrayList(java.util.ArrayList) Properties(java.util.Properties) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ProcessNodeLeftEvent(org.kie.api.event.process.ProcessNodeLeftEvent) Before(org.junit.Before)

Example 93 with RuntimeEnvironment

use of org.kie.api.runtime.manager.RuntimeEnvironment in project jbpm by kiegroup.

the class PessimisticLockTasksServiceTest method testPessimisticLockingOnTask.

@Test
public void testPessimisticLockingOnTask() throws Exception {
    final List<Exception> exceptions = new ArrayList<Exception>();
    addEnvironmentEntry(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
    createRuntimeManager("org/jbpm/test/functional/task/Evaluation2.bpmn");
    RuntimeEngine runtimeEngine = getRuntimeEngine();
    final KieSession ksession = runtimeEngine.getKieSession();
    final TaskService taskService = runtimeEngine.getTaskService();
    // setup another instance of task service to allow not synchronized access to cause pessimistic lock exception
    RuntimeEnvironment runtimeEnv = ((InternalRuntimeManager) manager).getEnvironment();
    HumanTaskConfigurator configurator = HumanTaskServiceFactory.newTaskServiceConfigurator().environment(runtimeEnv.getEnvironment()).entityManagerFactory((EntityManagerFactory) runtimeEnv.getEnvironment().get(EnvironmentName.ENTITY_MANAGER_FACTORY)).userGroupCallback(runtimeEnv.getUserGroupCallback());
    // register task listeners if any
    RegisterableItemsFactory itemsFactory = runtimeEnv.getRegisterableItemsFactory();
    for (TaskLifeCycleEventListener taskListener : itemsFactory.getTaskListeners()) {
        configurator.listener(taskListener);
    }
    final TaskService internalTaskService = configurator.getTaskService();
    logger.info("### Starting process ###");
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("employee", "salaboy");
    ProcessInstance process = ksession.startProcess("com.sample.evaluation", parameters);
    // The process is in the first Human Task waiting for its completion
    assertEquals(ProcessInstance.STATE_ACTIVE, process.getState());
    // gets salaboy's tasks
    List<TaskSummary> salaboysTasks = taskService.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    assertEquals(1, salaboysTasks.size());
    final long taskId = salaboysTasks.get(0).getId();
    final CountDownLatch t2StartLockedTask = new CountDownLatch(1);
    final CountDownLatch t1Continue = new CountDownLatch(1);
    Thread t1 = new Thread() {

        @Override
        public void run() {
            try {
                UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
                try {
                    ut.begin();
                    logger.info("Attempting to lock task instance");
                    taskService.start(taskId, "salaboy");
                    t2StartLockedTask.countDown();
                    t1Continue.await();
                } finally {
                    ut.rollback();
                }
            } catch (Exception e) {
                logger.error("Error on thread ", e);
            }
        }
    };
    Thread t2 = new Thread() {

        @Override
        public void run() {
            try {
                UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
                try {
                    ut.begin();
                    t2StartLockedTask.await();
                    logger.info("Trying to start locked task instance");
                    try {
                        internalTaskService.start(taskId, "salaboy");
                    } catch (Exception e) {
                        logger.info("Abort failed with error {}", e.getMessage());
                        exceptions.add(e);
                    } finally {
                        t1Continue.countDown();
                    }
                } finally {
                    ut.rollback();
                }
            } catch (Exception e) {
                logger.error("Error on thread ", e);
            }
        }
    };
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    assertEquals(1, exceptions.size());
    assertEquals(PessimisticLockException.class.getName(), exceptions.get(0).getClass().getName());
    taskService.start(salaboysTasks.get(0).getId(), "salaboy");
    // complete task within user transaction to make sure no deadlock happens as both task service and ksession are under tx lock
    UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
    try {
        ut.begin();
        taskService.complete(salaboysTasks.get(0).getId(), "salaboy", null);
        ut.commit();
    } catch (Exception ex) {
        ut.rollback();
        throw ex;
    }
    List<TaskSummary> pmsTasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, pmsTasks.size());
    List<TaskSummary> hrsTasks = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(1, hrsTasks.size());
    ksession.abortProcessInstance(process.getId());
    assertProcessInstanceAborted(process.getId());
}
Also used : UserTransaction(javax.transaction.UserTransaction) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) InternalRuntimeManager(org.kie.internal.runtime.manager.InternalRuntimeManager) HumanTaskConfigurator(org.jbpm.services.task.HumanTaskConfigurator) HashMap(java.util.HashMap) TaskService(org.kie.api.task.TaskService) ArrayList(java.util.ArrayList) RegisterableItemsFactory(org.kie.api.runtime.manager.RegisterableItemsFactory) CountDownLatch(java.util.concurrent.CountDownLatch) PessimisticLockException(javax.persistence.PessimisticLockException) PessimisticLockException(javax.persistence.PessimisticLockException) EntityManagerFactory(javax.persistence.EntityManagerFactory) TaskSummary(org.kie.api.task.model.TaskSummary) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) TaskLifeCycleEventListener(org.kie.api.task.TaskLifeCycleEventListener) Test(org.junit.Test)

Example 94 with RuntimeEnvironment

use of org.kie.api.runtime.manager.RuntimeEnvironment in project jbpm by kiegroup.

the class EjbTimerServiceIntegrationTest method testProcessWithTimerOverEJBTimerService.

public void testProcessWithTimerOverEJBTimerService(String delay) throws InterruptedException {
    cleanupSingletonSessionId();
    final List<String> timerExecution = new ArrayList<String>();
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-TimerTask.bpmn2"), ResourceType.BPMN2).schedulerService(new EjbSchedulerService()).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

        @Override
        public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
            List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
            listeners.add(new DefaultProcessEventListener() {

                @Override
                public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
                    if (event.getNodeInstance().getNodeName().equals("Event")) {
                        timerExecution.add(event.getNodeInstance().getNodeName());
                    }
                }
            });
            return listeners;
        }
    }).get();
    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);
    RuntimeEngine runtime = manager.getRuntimeEngine(EmptyContext.get());
    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("x", delay);
    ProcessInstance instance = ksession.startProcess("IntermediateCatchEvent", parameters);
    assertNotNull(instance);
    Thread.sleep(3000);
    instance = ksession.getProcessInstance(instance.getId());
    assertNull(instance);
    assertEquals(1, timerExecution.size());
    manager.disposeRuntimeEngine(runtime);
    // close manager which will close session maintained by the manager
    manager.close();
}
Also used : DefaultRegisterableItemsFactory(org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) EjbSchedulerService(org.jbpm.services.ejb.timer.EjbSchedulerService) HashMap(java.util.HashMap) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ArrayList(java.util.ArrayList) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ProcessNodeTriggeredEvent(org.kie.api.event.process.ProcessNodeTriggeredEvent) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance)

Example 95 with RuntimeEnvironment

use of org.kie.api.runtime.manager.RuntimeEnvironment in project jbpm by kiegroup.

the class EjbTimerServiceIntegrationTest method testProcessWithHTDeadlineTimerOverEJBTimerService.

@Test
public void testProcessWithHTDeadlineTimerOverEJBTimerService() throws InterruptedException {
    cleanupSingletonSessionId();
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("HumanTaskWithDeadlines.bpmn"), ResourceType.BPMN2).schedulerService(new EjbSchedulerService()).get();
    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);
    RuntimeEngine runtime = manager.getRuntimeEngine(EmptyContext.get());
    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);
    ProcessInstance processInstance = ksession.startProcess("htdeadlinetest");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);
    List<TaskSummary> krisTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("krisv", "en-UK");
    assertEquals(1, krisTasks.size());
    List<TaskSummary> johnTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(0, johnTasks.size());
    List<TaskSummary> maryTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(0, maryTasks.size());
    // now wait for 2 seconds for first reassignment
    Thread.sleep(3000);
    krisTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("krisv", "en-UK");
    assertEquals(0, krisTasks.size());
    johnTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, johnTasks.size());
    maryTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(0, maryTasks.size());
    runtime.getTaskService().start(johnTasks.get(0).getId(), "john");
    // now wait for 2 more seconds for second reassignment
    Thread.sleep(2000);
    krisTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("krisv", "en-UK");
    assertEquals(0, krisTasks.size());
    johnTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, johnTasks.size());
    maryTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(0, maryTasks.size());
    // now wait for 1 seconds to make sure that reassignment did not happen any more since task was already started
    Thread.sleep(3000);
    krisTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("krisv", "en-UK");
    assertEquals(0, krisTasks.size());
    johnTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(0, johnTasks.size());
    maryTasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(1, maryTasks.size());
    runtime.getTaskService().start(maryTasks.get(0).getId(), "mary");
    runtime.getTaskService().complete(maryTasks.get(0).getId(), "mary", null);
    // now wait for 2 seconds to make sure that reassignment did not happen any more since task was completed
    Thread.sleep(2000);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
    // close manager which will close session maintained by the manager
    manager.close();
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) EjbSchedulerService(org.jbpm.services.ejb.timer.EjbSchedulerService) TaskSummary(org.kie.api.task.model.TaskSummary) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) Test(org.junit.Test)

Aggregations

RuntimeEnvironment (org.kie.api.runtime.manager.RuntimeEnvironment)177 Test (org.junit.Test)163 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)148 KieSession (org.kie.api.runtime.KieSession)127 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)107 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)101 NodeLeftCountDownProcessEventListener (org.jbpm.test.listener.NodeLeftCountDownProcessEventListener)51 AbstractExecutorBaseTest (org.jbpm.test.util.AbstractExecutorBaseTest)49 ProcessEventListener (org.kie.api.event.process.ProcessEventListener)48 HashMap (java.util.HashMap)47 DefaultRegisterableItemsFactory (org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory)42 WorkItemHandler (org.kie.api.runtime.process.WorkItemHandler)38 ArrayList (java.util.ArrayList)21 TaskSummary (org.kie.api.task.model.TaskSummary)21 NodeTriggeredCountDownProcessEventListener (org.jbpm.test.listener.NodeTriggeredCountDownProcessEventListener)20 AuditService (org.kie.api.runtime.manager.audit.AuditService)20 CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)19 SystemOutWorkItemHandler (org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler)19 DefaultProcessEventListener (org.kie.api.event.process.DefaultProcessEventListener)19 InternalRuntimeManager (org.kie.internal.runtime.manager.InternalRuntimeManager)17