Search in sources :

Example 46 with Job

use of org.activiti.engine.runtime.Job in project Activiti by Activiti.

the class BoundaryTimerEventTest method testBoundaryTimerEvent.

@Deployment
public void testBoundaryTimerEvent() throws Exception {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyy.MM.dd hh:mm");
    Date currentTime = simpleDateFormat.parse("2015.10.01 11:01");
    processEngineConfiguration.getClock().setCurrentTime(currentTime);
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("patient", "kermit");
    runtimeService.startProcessInstanceByKey("process1", vars);
    // just wait for 2 seconds to run any job if it's the case
    try {
        waitForJobExecutorToProcessAllJobs(2000, 200);
    } catch (Exception ex) {
    //expected exception because the boundary timer event created a timer job to be executed after 10 minutes
    }
    // there should be a userTask waiting for user input
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    assertEquals("First Task", tasks.get(0).getName());
    List<Job> jobList = managementService.createJobQuery().list();
    assertEquals(1, jobList.size());
    // let's see what's happening after 2 minutes
    // nothing should change since the timer have to executed after 10 minutes
    long twoMinutes = 2L * 60L * 1000L;
    currentTime = new Date(currentTime.getTime() + twoMinutes + 1000L);
    processEngineConfiguration.getClock().setCurrentTime(currentTime);
    try {
        waitForJobExecutorToProcessAllJobs(2000, 200);
    } catch (Exception ex) {
    //expected exception because the boundary timer event created a timer job to be executed after 10 minutes
    }
    tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    assertEquals("First Task", tasks.get(0).getName());
    jobList = managementService.createJobQuery().list();
    assertEquals(1, jobList.size());
    // after another 8 minutes (the timer will have to execute because it wasa set to be executed @ 10 minutes after process start)
    long tenMinutes = 8L * 60L * 1000L;
    currentTime = new Date(currentTime.getTime() + tenMinutes);
    processEngineConfiguration.getClock().setCurrentTime(currentTime);
    try {
        waitForJobExecutorToProcessAllJobs(2000, 200);
    } catch (Exception ex) {
        ex.getCause();
    //expected exception because a new job is prepared
    }
    // there should be only one userTask and it should be the one triggered by the boundary timer event.
    // after the boundary event is triggered there should be no active job.
    tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    assertEquals("Second Task", tasks.get(0).getName());
    jobList = managementService.createJobQuery().list();
    assertEquals(0, jobList.size());
}
Also used : Task(org.activiti.engine.task.Task) HashMap(java.util.HashMap) Job(org.activiti.engine.runtime.Job) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Deployment(org.activiti.engine.test.Deployment)

Example 47 with Job

use of org.activiti.engine.runtime.Job in project Activiti by Activiti.

the class BoundaryTimerEventTest method testExpressionOnTimer.

@Deployment
public void testExpressionOnTimer() {
    // Set the clock fixed
    Date startTime = new Date();
    HashMap<String, Object> variables = new HashMap<String, Object>();
    variables.put("duration", "PT1H");
    // After process start, there should be a timer created
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("testExpressionOnTimer", variables);
    JobQuery jobQuery = managementService.createJobQuery().processInstanceId(pi.getId());
    List<Job> jobs = jobQuery.list();
    assertEquals(1, jobs.size());
    // After setting the clock to time '1 hour and 5 seconds', the second timer should fire
    processEngineConfiguration.getClock().setCurrentTime(new Date(startTime.getTime() + ((60 * 60 * 1000) + 5000)));
    waitForJobExecutorToProcessAllJobs(5000L, 25L);
    assertEquals(0L, jobQuery.count());
    // start execution listener is not executed
    assertFalse(listenerExecutedStartEvent);
    assertTrue(listenerExecutedEndEvent);
    // which means the process has ended
    assertProcessEnded(pi.getId());
}
Also used : HashMap(java.util.HashMap) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) JobQuery(org.activiti.engine.runtime.JobQuery) Job(org.activiti.engine.runtime.Job) Date(java.util.Date) Deployment(org.activiti.engine.test.Deployment)

Example 48 with Job

use of org.activiti.engine.runtime.Job in project Activiti by Activiti.

the class BoundaryTimerEventTest method testInfiniteRepeatingTimer.

@Deployment
public void testInfiniteRepeatingTimer() throws Exception {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyy.MM.dd hh:mm");
    Date currentTime = simpleDateFormat.parse("2015.10.01 11:01");
    processEngineConfiguration.getClock().setCurrentTime(currentTime);
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("timerString", "R/2015-10-01T11:00:00/PT24H");
    runtimeService.startProcessInstanceByKey("testTimerErrors", vars);
    long twentyFourHours = 24L * 60L * 60L * 1000L;
    Date previousDueDate = null;
    // Move clock, job should fire
    for (int i = 0; i < 30; i++) {
        Job job = managementService.createJobQuery().singleResult();
        // Verify due date
        if (previousDueDate != null) {
            assertTrue(job.getDuedate().getTime() - previousDueDate.getTime() >= twentyFourHours);
        }
        previousDueDate = job.getDuedate();
        currentTime = new Date(currentTime.getTime() + twentyFourHours + (60 * 1000));
        processEngineConfiguration.getClock().setCurrentTime(currentTime);
        managementService.executeJob(managementService.createJobQuery().executable().singleResult().getId());
    }
}
Also used : HashMap(java.util.HashMap) Job(org.activiti.engine.runtime.Job) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Deployment(org.activiti.engine.test.Deployment)

Example 49 with Job

use of org.activiti.engine.runtime.Job in project Activiti by Activiti.

the class DeploymentEntityManager method deleteDeployment.

public void deleteDeployment(String deploymentId, boolean cascade) {
    List<ProcessDefinition> processDefinitions = getDbSqlSession().createProcessDefinitionQuery().deploymentId(deploymentId).list();
    // Remove the deployment link from any model. 
    // The model will still exists, as a model is a source for a deployment model and has a different lifecycle
    List<Model> models = getDbSqlSession().createModelQueryImpl().deploymentId(deploymentId).list();
    for (Model model : models) {
        ModelEntity modelEntity = (ModelEntity) model;
        modelEntity.setDeploymentId(null);
        getModelManager().updateModel(modelEntity);
    }
    if (cascade) {
        // delete process instances
        for (ProcessDefinition processDefinition : processDefinitions) {
            String processDefinitionId = processDefinition.getId();
            getProcessInstanceManager().deleteProcessInstancesByProcessDefinition(processDefinitionId, "deleted deployment", cascade);
        }
    }
    for (ProcessDefinition processDefinition : processDefinitions) {
        String processDefinitionId = processDefinition.getId();
        // remove related authorization parameters in IdentityLink table
        getIdentityLinkManager().deleteIdentityLinksByProcDef(processDefinitionId);
        // event subscriptions
        List<EventSubscriptionEntity> eventSubscriptionEntities = getEventSubscriptionManager().findEventSubscriptionsByTypeAndProcessDefinitionId(null, processDefinitionId, // null type ==> all types
        processDefinition.getTenantId());
        for (EventSubscriptionEntity eventSubscriptionEntity : eventSubscriptionEntities) {
            eventSubscriptionEntity.delete();
        }
        getProcessDefinitionInfoManager().deleteProcessDefinitionInfo(processDefinitionId);
    }
    // delete process definitions from db
    getProcessDefinitionManager().deleteProcessDefinitionsByDeploymentId(deploymentId);
    for (ProcessDefinition processDefinition : processDefinitions) {
        // remove timer start events for current process definition:
        List<Job> timerStartJobs = Context.getCommandContext().getJobEntityManager().findJobsByTypeAndProcessDefinitionId(TimerStartEventJobHandler.TYPE, processDefinition.getId());
        if (timerStartJobs != null && timerStartJobs.size() > 0) {
            for (Job timerStartJob : timerStartJobs) {
                if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
                    Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, timerStartJob, null, null, processDefinition.getId()));
                }
                ((JobEntity) timerStartJob).delete();
            }
        }
        // If previous process definition version has a timer/message/signal start event, it must be added
        ProcessDefinitionEntity latestProcessDefinition = findLatestProcessDefinition(processDefinition);
        // Only if the currently deleted process definition is the latest version, we fall back to the previous start event type
        if (processDefinition.getId().equals(latestProcessDefinition.getId())) {
            // Try to find a previous version (it could be some versions are missing due to deletions)
            ProcessDefinition previousProcessDefinition = findNewLatestProcessDefinitionAfterRemovalOf(processDefinition);
            if (previousProcessDefinition != null) {
                // Need to resolve process definition to make sure it's parsed
                ProcessDefinitionEntity resolvedProcessDefinition = Context.getProcessEngineConfiguration().getDeploymentManager().resolveProcessDefinition((ProcessDefinitionEntity) previousProcessDefinition);
                // Timer start
                List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) resolvedProcessDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER);
                if (timerDeclarations != null) {
                    for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
                        TimerEntity timer = timerDeclaration.prepareTimerEntity(null);
                        timer.setProcessDefinitionId(previousProcessDefinition.getId());
                        if (previousProcessDefinition.getTenantId() != null) {
                            timer.setTenantId(previousProcessDefinition.getTenantId());
                        }
                        Context.getCommandContext().getJobEntityManager().schedule(timer);
                    }
                }
                // Signal / Message start
                List<EventSubscriptionDeclaration> signalEventDefinitions = (List<EventSubscriptionDeclaration>) resolvedProcessDefinition.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_DECLARATION);
                if (signalEventDefinitions != null) {
                    for (EventSubscriptionDeclaration eventDefinition : signalEventDefinitions) {
                        if (eventDefinition.getEventType().equals("signal") && eventDefinition.isStartEvent()) {
                            SignalEventSubscriptionEntity subscriptionEntity = new SignalEventSubscriptionEntity();
                            subscriptionEntity.setEventName(eventDefinition.getEventName());
                            subscriptionEntity.setActivityId(eventDefinition.getActivityId());
                            subscriptionEntity.setProcessDefinitionId(previousProcessDefinition.getId());
                            subscriptionEntity.setTenantId(previousProcessDefinition.getTenantId());
                            subscriptionEntity.insert();
                        } else if (eventDefinition.getEventType().equals("message") && eventDefinition.isStartEvent()) {
                            MessageEventSubscriptionEntity newSubscription = new MessageEventSubscriptionEntity();
                            newSubscription.setEventName(eventDefinition.getEventName());
                            newSubscription.setActivityId(eventDefinition.getActivityId());
                            newSubscription.setConfiguration(previousProcessDefinition.getId());
                            newSubscription.setProcessDefinitionId(previousProcessDefinition.getId());
                            newSubscription.setTenantId(previousProcessDefinition.getTenantId());
                            newSubscription.insert();
                        }
                    }
                }
            }
        }
    }
    getResourceManager().deleteResourcesByDeploymentId(deploymentId);
    getDbSqlSession().delete("deleteDeployment", deploymentId);
}
Also used : TimerDeclarationImpl(org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) Model(org.activiti.engine.repository.Model) List(java.util.List) Job(org.activiti.engine.runtime.Job) EventSubscriptionDeclaration(org.activiti.engine.impl.bpmn.parser.EventSubscriptionDeclaration)

Example 50 with Job

use of org.activiti.engine.runtime.Job in project Activiti by Activiti.

the class ErrorHandlingTest method testErrorHandledByCamel.

/**
	 * Exception caught and processed by Camel dead letter queue handler. 
	 * Process instance proceeds to ReceiveTask as expected.
	 * 
	 * @throws Exception
	 */
@Deployment(resources = { "process/errorHandling.bpmn20.xml" })
public void testErrorHandledByCamel() throws Exception {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("routing", Routing.HANDLE_ERROR);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ErrorHandling", variables);
    Job job = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(job);
    managementService.executeJob(job.getId());
    Thread.sleep(WAIT);
    assertEquals("Process instance did not reach next wait state", 1, runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).activityId(NEXT_WAIT_STATE).count());
}
Also used : HashMap(java.util.HashMap) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Job(org.activiti.engine.runtime.Job) Deployment(org.activiti.engine.test.Deployment)

Aggregations

Job (org.activiti.engine.runtime.Job)110 Deployment (org.activiti.engine.test.Deployment)76 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)55 Task (org.activiti.engine.task.Task)39 Date (java.util.Date)23 Calendar (java.util.Calendar)16 DelegateTask (org.activiti.engine.delegate.DelegateTask)11 HashMap (java.util.HashMap)10 ActivitiEvent (org.activiti.engine.delegate.event.ActivitiEvent)10 JobQuery (org.activiti.engine.runtime.JobQuery)8 ActivitiException (org.activiti.engine.ActivitiException)6 SimpleDateFormat (java.text.SimpleDateFormat)5 ArrayList (java.util.ArrayList)5 DefaultClockImpl (org.activiti.engine.impl.util.DefaultClockImpl)5 ProcessDefinition (org.activiti.engine.repository.ProcessDefinition)5 Clock (org.activiti.engine.runtime.Clock)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)4 CommandContext (org.activiti.engine.impl.interceptor.CommandContext)4