org.flowable.job.api.Job Java Examples

The following examples show how to use org.flowable.job.api.Job. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiInstanceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testParallelUserTasksWithTimer() {
    String procId = runtimeService.startProcessInstanceByKey("miParallelUserTasksWithTimer").getId();

    List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
    taskService.complete(tasks.get(0).getId());

    // Fire timer
    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());

    org.flowable.task.api.Task taskAfterTimer = taskService.createTaskQuery().singleResult();
    assertEquals("taskAfterTimer", taskAfterTimer.getTaskDefinitionKey());
    taskService.complete(taskAfterTimer.getId());
    assertProcessEnded(procId);
}
 
Example #2
Source File: HistoricProcessInstanceQueryAndWithExceptionTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: JavaServiceTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testAsyncServiceTaskWithSkipExpression() {
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("input", "test");
  
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("asyncServiceTask", vars);
  Job job = managementService.createJobQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
  assertNotNull(job);
  
  vars = new HashMap<String, Object>();
  vars.put("_ACTIVITI_SKIP_EXPRESSION_ENABLED", true);
  vars.put("skip", true);
  runtimeService.setVariables(pi.getProcessInstanceId(), vars);
  
  managementService.executeJob(job.getId());
  
  Execution waitExecution = runtimeService.createExecutionQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
  assertNotNull(waitExecution);
  assertEquals("waitState", waitExecution.getActivityId());
}
 
Example #4
Source File: DefaultInternalJobCompatibilityManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void executeV5JobWithLockAndRetry(final Job job) {

    // Retrieving the compatibility handler needs to be done outside of the executeJobWithLockAndRetry call,
    // as it shouldn't be wrapped in a transaction.
    Flowable5CompatibilityHandler compatibilityHandler = processEngineConfiguration.getCommandExecutor().execute(new Command<Flowable5CompatibilityHandler>() {

        @Override
        public Flowable5CompatibilityHandler execute(CommandContext commandContext) {
            return CommandContextUtil.getProcessEngineConfiguration(commandContext).getFlowable5CompatibilityHandler();
        }
    });

    // Note: no transaction (on purpose)
    compatibilityHandler.executeJobWithLockAndRetry(job);
}
 
Example #5
Source File: MoveDeadLetterJobToExecutableJobCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Job execute(CommandContext commandContext) {

    if (jobId == null) {
        throw new FlowableIllegalArgumentException("jobId and job is null");
    }

    DeadLetterJobEntity job = CommandContextUtil.getDeadLetterJobEntityManager(commandContext).findById(jobId);
    if (job == null) {
        throw new JobNotFoundException(jobId);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Moving deadletter job to executable job table {}", job.getId());
    }

    return CommandContextUtil.getJobManager(commandContext).moveDeadLetterJobToExecutableJob(job, retries);
}
 
Example #6
Source File: DefaultInternalJobManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleJobDeleteInternal(Job job) {
    if (job.getExecutionId() != null && CountingEntityUtil.isExecutionRelatedEntityCountEnabledGlobally()) {
        ExecutionEntity executionEntity = getExecutionEntityManager().findById(job.getExecutionId());
        if (CountingEntityUtil.isExecutionRelatedEntityCountEnabled(executionEntity)) {
            CountingExecutionEntity countingExecutionEntity = (CountingExecutionEntity) executionEntity;
            if (job instanceof JobEntity) {
                executionEntity.getJobs().remove(job);
                countingExecutionEntity.setJobCount(countingExecutionEntity.getJobCount() - 1);
            
            } else if (job instanceof TimerJobEntity) {
                executionEntity.getTimerJobs().remove(job);
                countingExecutionEntity.setTimerJobCount(countingExecutionEntity.getTimerJobCount() - 1);
            
            } else if (job instanceof SuspendedJobEntity) {
                countingExecutionEntity.setSuspendedJobCount(countingExecutionEntity.getSuspendedJobCount() - 1);
            
            } else if (job instanceof DeadLetterJobEntity) {
                countingExecutionEntity.setDeadLetterJobCount(countingExecutionEntity.getDeadLetterJobCount() - 1);
            } else if (job instanceof ExternalWorkerJobEntity) {
                countingExecutionEntity.setExternalWorkerJobCount(countingExecutionEntity.getExternalWorkerJobCount() - 1);
            }
        }
    }
}
 
Example #7
Source File: MultiInstanceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testParallelUserTasksWithTimer() {
    String procId = runtimeService.startProcessInstanceByKey("miParallelUserTasksWithTimer").getId();

    List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
    taskService.complete(tasks.get(0).getId());

    // Fire timer
    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());

    org.flowable.task.api.Task taskAfterTimer = taskService.createTaskQuery().singleResult();
    assertEquals("taskAfterTimer", taskAfterTimer.getTaskDefinitionKey());
    taskService.complete(taskAfterTimer.getId());
    assertProcessEnded(procId);
}
 
Example #8
Source File: AsyncTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@CmmnDeployment
public void testAsyncServiceTaskWithCategoryExpression() {
    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
            .caseDefinitionKey("testAsyncServiceTask")
            .variable("categoryValue", "testValue")
            .start();
    Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    cmmnTaskService.complete(task.getId());

    Job job = cmmnManagementService.createJobQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(job.getCategory()).isEqualTo("testValue");

    waitForJobExecutorToProcessAllJobs();

    task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task after service task");
    assertThat(cmmnRuntimeService.getVariable(caseInstance.getId(), "javaDelegate")).isEqualTo("executed");
}
 
Example #9
Source File: MultiInstanceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testNestedParallelSubProcessWithTimer() {
    String procId = runtimeService.startProcessInstanceByKey("miNestedParallelSubProcess").getId();
    List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
    assertEquals(12, tasks.size());

    for (int i = 0; i < 3; i++) {
        taskService.complete(tasks.get(i).getId());
    }

    // Fire timer
    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());

    org.flowable.task.api.Task taskAfterTimer = taskService.createTaskQuery().singleResult();
    assertEquals("taskAfterTimer", taskAfterTimer.getTaskDefinitionKey());
    taskService.complete(taskAfterTimer.getId());

    assertProcessEnded(procId);
}
 
Example #10
Source File: JobExceptionStacktraceResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Get the exception stacktrace for a deadletter job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."),
        @ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.")
})
@GetMapping("/management/deadletter-jobs/{jobId}/exception-stacktrace")
public String getDeadLetterJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) {
    Job job = getDeadLetterJobById(jobId);

    String stackTrace = managementService.getDeadLetterJobExceptionStacktrace(job.getId());

    if (stackTrace == null) {
        throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' does not have an exception stacktrace.", String.class);
    }

    response.setContentType("text/plain");
    return stackTrace;
}
 
Example #11
Source File: AsyncTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@CmmnDeployment
public void testAsyncServiceTaskWithCategory() {
    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testAsyncServiceTask").start();
    Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    cmmnTaskService.complete(task.getId());

    Job job = cmmnManagementService.createJobQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(job.getCategory()).isEqualTo("cmmnCategory");

    waitForJobExecutorToProcessAllJobs();

    task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task after service task");
    assertThat(cmmnRuntimeService.getVariable(caseInstance.getId(), "javaDelegate")).isEqualTo("executed");
}
 
Example #12
Source File: MultiTenantSendEventTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
private void validateEventSent(ProcessInstance processInstance, String property) throws JsonProcessingException {
    assertThat(outboundEventChannelAdapter.receivedEvents).isEmpty();
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());

    Job job = managementService.createJobQuery().jobTenantId(processInstance.getTenantId()).singleResult();
    assertThat(job.getTenantId()).isEqualTo(processInstance.getTenantId());
    assertThat(job.getJobHandlerType()).isEqualTo(AsyncSendEventJobHandler.TYPE);
    assertThat(job.getElementId()).isEqualTo("sendEventTask");

    assertThat(outboundEventChannelAdapter.receivedEvents).isEmpty();
    JobTestHelper.waitForJobExecutorToProcessAllJobs(processEngineConfiguration, managementService, 5000, 200);
    assertThat(outboundEventChannelAdapter.receivedEvents).hasSize(1);

    JsonNode jsonNode = processEngineConfiguration.getObjectMapper().readTree(outboundEventChannelAdapter.receivedEvents.get(0));
    assertThat(jsonNode).hasSize(1);
    assertThat(jsonNode.get(property).asText()).isEqualTo("test");
    outboundEventChannelAdapter.receivedEvents.clear();
}
 
Example #13
Source File: ProcessInstanceSuspensionTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = "org/flowable/engine/test/api/runtime/ProcessInstanceSuspensionTest.testJobNotExecutedAfterProcessInstanceSuspend.bpmn20.xml")
public void testJobActivationAfterProcessInstanceSuspend() {

    Date now = new Date();
    processEngineConfiguration.getClock().setCurrentTime(now);

    // Suspending the process instance should also stop the execution of jobs for that process instance
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
    assertThat(managementService.createTimerJobQuery().count()).isEqualTo(1);
    runtimeService.suspendProcessInstanceById(processInstance.getId());
    assertThat(managementService.createSuspendedJobQuery().count()).isEqualTo(1);

    Job job = managementService.createTimerJobQuery().executable().singleResult();
    assertThat(job).isNull();

    Job suspendedJob = managementService.createSuspendedJobQuery().singleResult();
    assertThat(suspendedJob).isNotNull();

    // Activation of the suspended job instance should throw exception because parent is suspended
    assertThatThrownBy(() -> managementService.moveSuspendedJobToExecutableJob(suspendedJob.getId()))
            .as("FlowableIllegalArgumentException expected. Cannot activate job with suspended parent")
            .isExactlyInstanceOf(FlowableIllegalArgumentException.class)
            .hasMessageContaining("Can not activate job " + suspendedJob.getId() + ". Parent is suspended.");
}
 
Example #14
Source File: BoundaryTimerNonInterruptingEventTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/engine/test/bpmn/event/timer/BoundaryTimerNonInterruptingEventTest.testTimerOnConcurrentTasks.bpmn20.xml" })
public void testTimerOnConcurrentTasks2() {
    String procId = runtimeService.startProcessInstanceByKey("nonInterruptingOnConcurrentTasks").getId();
    assertThat(taskService.createTaskQuery().count()).isEqualTo(2);

    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());
    assertThat(taskService.createTaskQuery().count()).isEqualTo(3);

    // Complete 2 tasks that will trigger the join
    org.flowable.task.api.Task task = taskService.createTaskQuery().taskDefinitionKey("firstTask").singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().taskDefinitionKey("secondTask").singleResult();
    taskService.complete(task.getId());
    assertThat(taskService.createTaskQuery().count()).isEqualTo(1);

    // Finally, complete the task that was created due to the timer
    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask").singleResult();
    taskService.complete(task.getId());

    assertProcessEnded(procId);
}
 
Example #15
Source File: AsyncTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@CmmnDeployment
public void testAsyncServiceTaskWithManagementService() {
    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testAsyncServiceTask").start();
    Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task before service task");
    cmmnTaskService.complete(task.getId());

    // There should be an async job created now
    Job job = cmmnManagementService.createJobQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(job).isNotNull();
    assertThat(job.getScopeId()).isEqualTo(caseInstance.getId());
    assertThat(job.getScopeDefinitionId()).isEqualTo(caseInstance.getCaseDefinitionId());
    assertThat(job.getSubScopeId()).isNotNull();
    assertThat(job.getScopeType()).isEqualTo(ScopeTypes.CMMN);

    cmmnManagementService.executeJob(job.getId());
    task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task after service task");
    assertThat(cmmnRuntimeService.getVariable(caseInstance.getId(), "javaDelegate")).isEqualTo("executed");
}
 
Example #16
Source File: MultiInstanceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testSequentialSubProcessWithTimer() {
    String procId = runtimeService.startProcessInstanceByKey("miSequentialSubprocessWithTimer").getId();

    // Complete one subprocess
    List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
    assertEquals(2, tasks.size());
    taskService.complete(tasks.get(0).getId());
    taskService.complete(tasks.get(1).getId());
    tasks = taskService.createTaskQuery().list();
    assertEquals(2, tasks.size());

    // Fire timer
    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());

    org.flowable.task.api.Task taskAfterTimer = taskService.createTaskQuery().singleResult();
    assertEquals("taskAfterTimer", taskAfterTimer.getTaskDefinitionKey());
    taskService.complete(taskAfterTimer.getId());

    assertProcessEnded(procId);
}
 
Example #17
Source File: IntermediateTimerEventTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testLoop() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testLoop");

    // After looping 3 times, the process should end
    for (int i = 0; i < 3; i++) {
        Job timer = managementService.createTimerJobQuery().singleResult();
        managementService.moveTimerToExecutableJob(timer.getId());
        managementService.executeJob(timer.getId());
    }

    assertProcessEnded(processInstance.getId());
}
 
Example #18
Source File: JobResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Get a single timer job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates the timer job exists and is returned."),
        @ApiResponse(code = 404, message = "Indicates the requested job does not exist.")
})
@GetMapping(value = "/management/timer-jobs/{jobId}", produces = "application/json")
public JobResponse getTimerJob(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletRequest request) {
    Job job = getTimerJobById(jobId);
    return restResponseFactory.createJobResponse(job);
}
 
Example #19
Source File: BoundaryTimerNonInterruptingEventTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testReceiveTaskWithBoundaryTimer() {
    // Set the clock fixed
    HashMap<String, Object> variables = new HashMap<String, Object>();
    variables.put("timeCycle", "R/PT1H");

    // After process start, there should be a timer created
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("nonInterruptingCycle", variables);

    TimerJobQuery jobQuery = managementService.createTimerJobQuery().processInstanceId(pi.getId());
    List<Job> jobs = jobQuery.list();
    assertEquals(1, jobs.size());

    // The Execution Query should work normally and find executions in state "task"
    List<Execution> executions = runtimeService.createExecutionQuery()
            .activityId("task")
            .list();
    assertEquals(1, executions.size());
    List<String> activeActivityIds = runtimeService.getActiveActivityIds(executions.get(0).getId());
    assertEquals(1, activeActivityIds.size());
    assertEquals("task", activeActivityIds.get(0));

    runtimeService.trigger(executions.get(0).getId());

    // // 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(7000L, 25L);
    // assertEquals(0L, jobQuery.count());

    // which means the process has ended
    assertProcessEnded(pi.getId());
}
 
Example #20
Source File: JobQueryTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void verifyFailedJob(TimerJobQuery query, ProcessInstance processInstance) {
    verifyQueryResults(query, 1);

    Job failedJob = query.singleResult();
    assertThat(failedJob).isNotNull();
    assertThat(failedJob.getProcessInstanceId()).isEqualTo(processInstance.getId());
    assertThat(failedJob.getExceptionMessage()).isNotNull();
    assertTextPresent(EXCEPTION_MESSAGE, failedJob.getExceptionMessage());
}
 
Example #21
Source File: ProcessInstanceSuspensionTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testJobNotExecutedAfterProcessInstanceSuspend() {

    Date now = new Date();
    processEngineConfiguration.getClock().setCurrentTime(now);

    // Suspending the process instance should also stop the execution of jobs for that process instance
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
    Job job = managementService.createTimerJobQuery().singleResult();
    assertThat(job).isNotNull();
    assertThat(job.getCorrelationId()).isNotNull();
    assertThat(managementService.createTimerJobQuery().count()).isEqualTo(1);

    String correlationId = job.getCorrelationId();
    runtimeService.suspendProcessInstanceById(processInstance.getId());
    assertThat(managementService.createSuspendedJobQuery().count()).isEqualTo(1);

    // The jobs should not be executed now
    processEngineConfiguration.getClock().setCurrentTime(new Date(now.getTime() + (60 * 60 * 1000))); // Timer is set to fire on 5 minutes
    job = managementService.createTimerJobQuery().executable().singleResult();
    assertThat(job).isNull();

    assertThat(managementService.createSuspendedJobQuery().count()).isEqualTo(1);
    Job suspendedJob = managementService.createSuspendedJobQuery().correlationId(correlationId).singleResult();
    assertThat(suspendedJob).isNotNull();
    assertThat(suspendedJob.getCorrelationId()).isEqualTo(correlationId);

    // Activation of the process instance should now allow for job execution
    runtimeService.activateProcessInstanceById(processInstance.getId());
    waitForJobExecutorToProcessAllJobs(1000L, 100L);
    assertThat(managementService.createJobQuery().count()).isZero();
    assertThat(managementService.createTimerJobQuery().count()).isZero();
    assertThat(managementService.createSuspendedJobQuery().count()).isZero();
    assertThat(runtimeService.createProcessInstanceQuery().count()).isZero();
}
 
Example #22
Source File: RestResponseFactory.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public List<JobResponse> createJobResponseList(List<Job> jobs) {
    RestUrlBuilder urlBuilder = createUrlBuilder();
    List<JobResponse> responseList = new ArrayList<>(jobs.size());
    for (Job instance : jobs) {
        responseList.add(createJobResponse(instance, urlBuilder));
    }
    return responseList;
}
 
Example #23
Source File: BoundaryTimerNonInterruptingEventTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testTimerOnConcurrentSubprocess() {
    String procId = runtimeService.startProcessInstanceByKey("testTimerOnConcurrentSubprocess").getId();
    assertEquals(4, taskService.createTaskQuery().count());

    Job timer = managementService.createTimerJobQuery().singleResult();
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());
    assertEquals(5, taskService.createTaskQuery().count());

    // Complete 4 tasks that will trigger the join
    org.flowable.task.api.Task task = taskService.createTaskQuery().taskDefinitionKey("sub1task1").singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().taskDefinitionKey("sub1task2").singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().taskDefinitionKey("sub2task1").singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().taskDefinitionKey("sub2task2").singleResult();
    taskService.complete(task.getId());
    assertEquals(1, taskService.createTaskQuery().count());

    // Finally, complete the task that was created due to the timer
    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask").singleResult();
    taskService.complete(task.getId());

    assertProcessEnded(procId);
}
 
Example #24
Source File: ManagementServiceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testGetJobExceptionStacktrace() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundary
    // timer event which we will execute manual for testing purposes.
    final Job timerJob = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).singleResult();

    assertThat(timerJob).as("No job found for process instance").isNotNull();

    assertThatThrownBy(() -> {
        managementService.moveTimerToExecutableJob(timerJob.getId());
        managementService.executeJob(timerJob.getId());
    })
            .isExactlyInstanceOf(FlowableException.class)
            .hasMessageContaining("This is an exception thrown from scriptTask");

    // Fetch the task to see that the exception that occurred is persisted
    Job timerJob2 = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).singleResult();

    assertThat(timerJob2).isNotNull();
    assertThat(timerJob2.getExceptionMessage()).isNotNull();
    assertThat(timerJob2.getExceptionMessage())
            .contains("This is an exception thrown from scriptTask");

    // Get the full stacktrace using the managementService
    String exceptionStack = managementService.getTimerJobExceptionStacktrace(timerJob2.getId());
    assertThat(exceptionStack).isNotNull();
    assertThat(exceptionStack)
            .contains("This is an exception thrown from scriptTask");
}
 
Example #25
Source File: ManagementServiceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void testSetJobRetriesUnexistingJobId() {
    try {
        managementService.setJobRetries("unexistingjob", 5);
        fail("ActivitiException expected");
    } catch (FlowableObjectNotFoundException re) {
        assertTextPresent("No job found with id 'unexistingjob'.", re.getMessage());
        assertEquals(Job.class, re.getObjectClass());
    }
}
 
Example #26
Source File: TimerEventSubprocessTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment(resources="org/flowable/engine/test/bpmn/event/timer/TimerEventSubprocessTest.testStartingAdditionalTasks.bpmn20.xml")
public void testStartingAdditionalTasksNoNestedEventSubProcess() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startingAdditionalTasks");
    assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(3);

    Job job = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(job).isNotNull();

    assertThat(taskService.createTaskQuery().count()).isEqualTo(1);

    // now let's first complete the task in the main flow:
    org.flowable.task.api.Task task = taskService.createTaskQuery().taskDefinitionKey("task1").singleResult();
    taskService.complete(task.getId());

    List<Job> jobs = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).list();
    assertThat(jobs).hasSize(2);
    
    assertThat(taskService.createTaskQuery().count()).isEqualTo(1);
    
    task = taskService.createTaskQuery().taskDefinitionKey("subTask1").singleResult();
    taskService.complete(task.getId());
    
    jobs = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).list();
    assertThat(jobs).hasSize(1);
    assertThat(taskService.createTaskQuery().count()).isEqualTo(1);
    
    task = taskService.createTaskQuery().taskDefinitionKey("task2").singleResult();
    taskService.complete(task.getId());

    // done!
    assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isZero();
}
 
Example #27
Source File: ScopeAwareInternalJobManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected InternalJobManager findInternalJobManager(Job job) {
    if (internalJobManagerByScopeType == null || internalJobManagerByScopeType.isEmpty()) {
        return null;
    }

    String scopeType = job.getScopeType();
    if (scopeType == null && job.getProcessInstanceId() != null) {
        scopeType = ScopeTypes.BPMN;
    }

    return internalJobManagerByScopeType.get(scopeType);
}
 
Example #28
Source File: EventSubscriptionEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void scheduleEventAsync(Object payload) {

        final CommandContext commandContext = Context.getCommandContext();

        JobEntity message = new JobEntity();
        message.setJobType(Job.JOB_TYPE_MESSAGE);
        message.setRevision(1);
        message.setJobHandlerType(ProcessEventJobHandler.TYPE);
        message.setJobHandlerConfiguration(id);
        message.setTenantId(getTenantId());
        message.setProcessDefinitionId(getProcessDefinitionId());
        message.setExecutionId(getExecutionId());
        message.setProcessInstanceId(getProcessInstanceId());

        if (Context.getProcessEngineConfiguration().getAsyncExecutor().isActive()) {
            GregorianCalendar expireCal = new GregorianCalendar();
            ProcessEngineConfiguration processEngineConfig = Context.getCommandContext().getProcessEngineConfiguration();
            expireCal.setTime(processEngineConfig.getClock().getCurrentTime());
            expireCal.add(Calendar.SECOND, processEngineConfig.getLockTimeAsyncJobWaitTime());
            message.setLockExpirationTime(expireCal.getTime());
        }

        // TODO: support payload
        // if(payload != null) {
        // message.setEventPayload(payload);
        // }

        commandContext.getJobEntityManager().send(message);
    }
 
Example #29
Source File: JobResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Get a single suspended job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates the suspended job exists and is returned."),
        @ApiResponse(code = 404, message = "Indicates the requested job does not exist.")
})
@GetMapping(value = "/management/suspended-jobs/{jobId}", produces = "application/json")
public JobResponse getSuspendedJob(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletRequest request) {
    Job job = getSuspendedJobById(jobId);
    return restResponseFactory.createJobResponse(job);
}
 
Example #30
Source File: TriggerableServiceTaskTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testAsyncJobs() {
    String processId = runtimeService.startProcessInstanceByKey("process").getProcessInstanceId();
    
    List<Job> jobs = managementService.createJobQuery().processInstanceId(processId).list();
    assertEquals(1, jobs.size());
    assertEquals(AsyncContinuationJobHandler.TYPE, jobs.get(0).getJobHandlerType());
    
    waitForJobExecutorToProcessAllJobs(7000L, 250L);

    Execution execution = runtimeService.createExecutionQuery().processInstanceId(processId).activityId("service1").singleResult();
    assertNotNull(execution);
    int count = (int) runtimeService.getVariable(processId, "count");
    assertEquals(1, count);

    Map<String,Object> processVariables = new HashMap<>();
    processVariables.put("count", ++count);
    runtimeService.triggerAsync(execution.getId(), processVariables);
    
    jobs = managementService.createJobQuery().processInstanceId(processId).list();
    assertEquals(1, jobs.size());
    assertEquals(AsyncTriggerJobHandler.TYPE, jobs.get(0).getJobHandlerType());
    
    waitForJobExecutorToProcessAllJobs(7000L, 250L);

    execution = runtimeService.createExecutionQuery().processInstanceId(processId).activityId("usertask1").singleResult();
    assertNotNull(execution);
    assertEquals(3, runtimeService.getVariable(processId, "count"));
}