Search in sources :

Example 31 with Job

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

the class JobResourceTest method testGetJob.

/**
   * Test getting a single job. 
   */
@Deployment(resources = { "org/activiti/rest/service/api/management/JobResourceTest.testTimerProcess.bpmn20.xml" })
public void testGetJob() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("timerProcess");
    Job timerJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(timerJob);
    Calendar now = Calendar.getInstance();
    now.set(Calendar.MILLISECOND, 0);
    processEngineConfiguration.getClock().setCurrentTime(now.getTime());
    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB, timerJob.getId())), HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(timerJob.getId(), responseNode.get("id").textValue());
    assertEquals(timerJob.getExceptionMessage(), responseNode.get("exceptionMessage").textValue());
    assertEquals(timerJob.getExecutionId(), responseNode.get("executionId").textValue());
    assertEquals(timerJob.getProcessDefinitionId(), responseNode.get("processDefinitionId").textValue());
    assertEquals(timerJob.getProcessInstanceId(), responseNode.get("processInstanceId").textValue());
    assertEquals(timerJob.getRetries(), responseNode.get("retries").intValue());
    assertEquals(timerJob.getDuedate(), getDateFromISOString(responseNode.get("dueDate").textValue()));
    assertEquals("", responseNode.get("tenantId").textValue());
    // Set tenant on deployment
    managementService.executeCommand(new ChangeDeploymentTenantIdCmd(deploymentId, "myTenant"));
    response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB, timerJob.getId())), HttpStatus.SC_OK);
    responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("myTenant", responseNode.get("tenantId").textValue());
}
Also used : ChangeDeploymentTenantIdCmd(org.activiti.engine.impl.cmd.ChangeDeploymentTenantIdCmd) Calendar(java.util.Calendar) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) JsonNode(com.fasterxml.jackson.databind.JsonNode) Job(org.activiti.engine.runtime.Job) Deployment(org.activiti.engine.test.Deployment)

Example 32 with Job

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

the class JobEventsTest method testJobEntityEvents.

/**
	 * Test create, update and delete events of jobs entities.
	 */
@Deployment
public void testJobEntityEvents() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testJobEvents");
    Job theJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(theJob);
    // Check if create-event has been dispatched
    assertEquals(2, listener.getEventsReceived().size());
    ActivitiEvent event = listener.getEventsReceived().get(0);
    assertEquals(ActivitiEventType.ENTITY_CREATED, event.getType());
    checkEventContext(event, theJob, false);
    event = listener.getEventsReceived().get(1);
    assertEquals(ActivitiEventType.ENTITY_INITIALIZED, event.getType());
    checkEventContext(event, theJob, false);
    listener.clearEventsReceived();
    // Update the job-entity. Check if update event is dispatched with update job entity
    managementService.setJobRetries(theJob.getId(), 5);
    assertEquals(1, listener.getEventsReceived().size());
    event = listener.getEventsReceived().get(0);
    assertEquals(ActivitiEventType.ENTITY_UPDATED, event.getType());
    Job updatedJob = (Job) ((ActivitiEntityEvent) event).getEntity();
    assertEquals(5, updatedJob.getRetries());
    checkEventContext(event, theJob, true);
    listener.clearEventsReceived();
    // Force timer to fire
    Calendar tomorrow = Calendar.getInstance();
    tomorrow.add(Calendar.DAY_OF_YEAR, 1);
    processEngineConfiguration.getClock().setCurrentTime(tomorrow.getTime());
    waitForJobExecutorToProcessAllJobs(2000, 100);
    // Check delete-event has been dispatched
    assertEquals(3, listener.getEventsReceived().size());
    // First, a timer fired event has been dispatched
    event = listener.getEventsReceived().get(0);
    assertEquals(ActivitiEventType.TIMER_FIRED, event.getType());
    checkEventContext(event, theJob, true);
    // Next, a delete event has been dispatched
    event = listener.getEventsReceived().get(1);
    assertEquals(ActivitiEventType.ENTITY_DELETED, event.getType());
    checkEventContext(event, theJob, true);
    // Finally, a complete event has been dispatched
    event = listener.getEventsReceived().get(2);
    assertEquals(ActivitiEventType.JOB_EXECUTION_SUCCESS, event.getType());
    checkEventContext(event, theJob, true);
}
Also used : Calendar(java.util.Calendar) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) ActivitiEvent(org.activiti.engine.delegate.event.ActivitiEvent) Job(org.activiti.engine.runtime.Job) Deployment(org.activiti.engine.test.Deployment)

Example 33 with Job

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

the class HistoricProcessInstanceQueryAndWithExceptionTest method startProcessInstanceWithFailingJob.

private ProcessInstance startProcessInstanceWithFailingJob(String processInstanceByKey) {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processInstanceByKey);
    List<Job> jobList = managementService.createJobQuery().processInstanceId(processInstance.getId()).list();
    for (Job job : jobList) {
        try {
            managementService.executeJob(job.getId());
            fail("RuntimeException");
        } catch (RuntimeException re) {
        }
    }
    return processInstance;
}
Also used : ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Job(org.activiti.engine.runtime.Job)

Example 34 with Job

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

the class StartTimerEventRepeatWithoutEndDateTest method testCycleDateStartTimerEvent.

/**
   * Timer repetition
   */
public void testCycleDateStartTimerEvent() throws Exception {
    Clock previousClock = processEngineConfiguration.getClock();
    Clock testClock = new DefaultClockImpl();
    processEngineConfiguration.setClock(testClock);
    Calendar calendar = Calendar.getInstance();
    calendar.set(2025, Calendar.DECEMBER, 10, 0, 0, 0);
    testClock.setCurrentTime(calendar.getTime());
    //deploy the process
    repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/bpmn/event/timer/StartTimerEventRepeatWithoutEndDateTest.testCycleDateStartTimerEvent.bpmn20.xml").deploy();
    assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
    //AFTER DEPLOYMENT
    //when the process is deployed there will be created a timerStartEvent job which will wait to be executed.
    List<Job> jobs = managementService.createJobQuery().list();
    assertEquals(1, jobs.size());
    //dueDate should be after 24 hours from the process deployment
    Calendar dueDateCalendar = Calendar.getInstance();
    dueDateCalendar.set(2025, Calendar.DECEMBER, 11, 0, 0, 0);
    //check the due date is inside the 2 seconds range
    assertEquals(true, Math.abs(dueDateCalendar.getTime().getTime() - jobs.get(0).getDuedate().getTime()) < 2000);
    //No process instances
    List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
    assertEquals(0, processInstances.size());
    //No tasks
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(0, tasks.size());
    // ADVANCE THE CLOCK
    // advance the clock after 9 days from starting the process ->
    // the system will execute the pending job and will create a new one (day by day)
    moveByMinutes(9 * 60 * 24);
    try {
        waitForJobExecutorToProcessAllJobs(10000, 200);
        fail("there must be a pending job because the endDate is not reached yet");
    } catch (Exception e) {
    //expected failure
    }
    // After time advanced 9 days  there should be 9 process instance started
    processInstances = runtimeService.createProcessInstanceQuery().list();
    assertEquals(9, processInstances.size());
    // 9 task to be executed (the userTask "Task A")
    tasks = taskService.createTaskQuery().list();
    assertEquals(9, tasks.size());
    // one new job will be created (and the old one will be deleted after execution)
    jobs = managementService.createJobQuery().list();
    assertEquals(1, jobs.size());
    //check if the last job to be executed has the dueDate set correctly
    // (10'th repeat after 10 dec. => dueDate must have DueDate = 20 dec.)
    dueDateCalendar = Calendar.getInstance();
    dueDateCalendar.set(2025, Calendar.DECEMBER, 20, 0, 0, 0);
    assertEquals(true, Math.abs(dueDateCalendar.getTime().getTime() - jobs.get(0).getDuedate().getTime()) < 2000);
    // ADVANCE THE CLOCK SO that all 10 repeats to be executed
    // (last execution)
    moveByMinutes(60 * 24);
    try {
        waitForJobExecutorToProcessAllJobs(2000, 200);
    } catch (Exception e) {
        fail("Because the maximum number of repeats is reached it will not be executed other jobs");
    }
    // After the 10nth startEvent Execution should have 10 process instances started
    // (since the first one was not completed)
    processInstances = runtimeService.createProcessInstanceQuery().list();
    assertEquals(10, processInstances.size());
    // the current job will be deleted after execution and a new one will not be created. (all 10 has already executed)
    jobs = managementService.createJobQuery().list();
    assertEquals(0, jobs.size());
    // 10 tasks to be executed (the userTask "Task A")
    // one task for each process instance
    tasks = taskService.createTaskQuery().list();
    assertEquals(10, tasks.size());
    //FINAL CHECK
    // count "timer fired" events
    int timerFiredCount = 0;
    List<ActivitiEvent> eventsReceived = listener.getEventsReceived();
    for (ActivitiEvent eventReceived : eventsReceived) {
        if (ActivitiEventType.TIMER_FIRED.equals(eventReceived.getType())) {
            timerFiredCount++;
        }
    }
    //count "entity created" events
    int eventCreatedCount = 0;
    for (ActivitiEvent eventReceived : eventsReceived) {
        if (ActivitiEventType.ENTITY_CREATED.equals(eventReceived.getType())) {
            eventCreatedCount++;
        }
    }
    // count "entity deleted" events
    int eventDeletedCount = 0;
    for (ActivitiEvent eventReceived : eventsReceived) {
        if (ActivitiEventType.ENTITY_DELETED.equals(eventReceived.getType())) {
            eventDeletedCount++;
        }
    }
    //10 timers fired
    assertEquals(10, timerFiredCount);
    //10 jobs created
    assertEquals(10, eventCreatedCount);
    //10 jobs deleted
    assertEquals(10, eventDeletedCount);
    // let's complete the userTasks where the process is hanging in order to complete the processes.
    for (ProcessInstance processInstance : processInstances) {
        tasks = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).list();
        Task task = tasks.get(0);
        assertEquals("Task A", task.getName());
        assertEquals(1, tasks.size());
        taskService.complete(task.getId());
    }
    //now All the process instances should be completed
    processInstances = runtimeService.createProcessInstanceQuery().list();
    assertEquals(0, processInstances.size());
    //no jobs
    jobs = managementService.createJobQuery().list();
    assertEquals(0, jobs.size());
    //no tasks
    tasks = taskService.createTaskQuery().list();
    assertEquals(0, tasks.size());
    listener.clearEventsReceived();
    processEngineConfiguration.setClock(previousClock);
    repositoryService.deleteDeployment(repositoryService.createDeploymentQuery().singleResult().getId(), true);
}
Also used : Task(org.activiti.engine.task.Task) Calendar(java.util.Calendar) Clock(org.activiti.engine.runtime.Clock) DefaultClockImpl(org.activiti.engine.impl.util.DefaultClockImpl) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) ActivitiEvent(org.activiti.engine.delegate.event.ActivitiEvent) Job(org.activiti.engine.runtime.Job)

Example 35 with Job

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

the class IntermediateTimerEventRepeatCompatibilityTest method testRepeatWithEnd.

@Deployment
public void testRepeatWithEnd() throws Throwable {
    Calendar calendar = Calendar.getInstance();
    Date baseTime = calendar.getTime();
    //expect to stop boundary jobs after 20 minutes
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    calendar.setTime(baseTime);
    calendar.add(Calendar.HOUR, 2);
    //expect to wait after completing task A for 1 hour even I set the end date for 2 hours (the expression will trigger the execution)
    DateTime dt = new DateTime(calendar.getTime());
    String endDateForIntermediate1 = fmt.print(dt);
    calendar.setTime(baseTime);
    calendar.add(Calendar.HOUR, 1);
    calendar.add(Calendar.MINUTE, 30);
    //expect to wait after completing task B for 1 hour and 30 minutes (the end date will be reached, the expression will not be considered)
    dt = new DateTime(calendar.getTime());
    String endDateForIntermediate2 = fmt.print(dt);
    //reset the timer
    Calendar nextTimeCal = Calendar.getInstance();
    nextTimeCal.setTime(baseTime);
    processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime());
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("repeatWithEnd");
    runtimeService.setVariable(processInstance.getId(), "EndDateForCatch1", endDateForIntermediate1);
    runtimeService.setVariable(processInstance.getId(), "EndDateForCatch2", endDateForIntermediate2);
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    Task task = tasks.get(0);
    assertEquals("Task A", task.getName());
    //Test Timer Catch Intermediate Events after completing Task B (endDate not reached but it will be executed according to the expression)
    taskService.complete(task.getId());
    try {
        waitForJobExecutorToProcessAllJobs(2000, 500);
        fail("Expected that job isn't executed because the timer is in t0");
    } catch (Exception e) {
    // expected
    }
    //after 1 hour the event must be triggered and the flow will go to the next step
    nextTimeCal.add(Calendar.HOUR, 1);
    processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime());
    waitForJobExecutorToProcessAllJobs(2000, 500);
    //expect to execute because the time is reached.
    List<Job> jobs = managementService.createJobQuery().list();
    assertEquals(0, jobs.size());
    tasks = taskService.createTaskQuery().list();
    assertEquals(1, tasks.size());
    task = tasks.get(0);
    assertEquals("Task C", task.getName());
    //Test Timer Catch Intermediate Events after completing Task C
    taskService.complete(task.getId());
    //after 1H 40 minutes from process start, the timer will trigger because of the endDate
    nextTimeCal.add(Calendar.HOUR, 1);
    processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime());
    waitForJobExecutorToProcessAllJobs(2000, 500);
    if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
        HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(historicInstance.getEndTime());
    }
    //now All the process instances should be completed
    List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
    assertEquals(0, processInstances.size());
    //no jobs
    jobs = managementService.createJobQuery().list();
    assertEquals(0, jobs.size());
    //no tasks
    tasks = taskService.createTaskQuery().list();
    assertEquals(0, tasks.size());
}
Also used : Task(org.activiti.engine.task.Task) Calendar(java.util.Calendar) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) Date(java.util.Date) DateTime(org.joda.time.DateTime) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Job(org.activiti.engine.runtime.Job) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) 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