org.camunda.bpm.engine.runtime.Job Java Examples

The following examples show how to use org.camunda.bpm.engine.runtime.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: UpdateJobAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = {
    "org/camunda/bpm/engine/test/api/authorization/timerBoundaryEventProcess.bpmn20.xml" })
public void shouldActivateJobByProcessDefinitionId() {
  // given
  ProcessInstance processInstance = runtimeService
      .startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY);

  // when
  authRule
  .init(scenario)
  .withUser("userId")
  .bindResource("processInstanceId", "*")
  .bindResource("someProcessInstanceId", processInstance.getId())
  .start();

  managementService.activateJobByProcessDefinitionId(processInstance.getProcessDefinitionId());

  // then
  if (authRule.assertScenario(scenario)) {
    Job job = selectJobByProcessInstanceId(processInstance.getId());
    assertThat(job.isSuspended()).isFalse();
  }
}
 
Example #2
Source File: JobDefinitionAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public void testActivateIncludingJobsByProcessDefinitionKeyWithUpdateInstancePermissionOnAnyProcessDefinition() {
  // given
  String processInstanceId = startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY).getId();
  suspendJobDefinitionIncludingJobsByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY);

  createGrantAuthorization(PROCESS_DEFINITION, TIMER_BOUNDARY_PROCESS_KEY, userId, UPDATE);
  createGrantAuthorization(PROCESS_DEFINITION, ANY, userId, UPDATE_INSTANCE);

  // when
  managementService.activateJobDefinitionByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY, true);

  // then
  JobDefinition jobDefinition = selectJobDefinitionByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY);
  assertNotNull(jobDefinition);
  assertFalse(jobDefinition.isSuspended());

  Job job = selectJobByProcessInstanceId(processInstanceId);
  assertNotNull(job);
  assertFalse(job.isSuspended());
}
 
Example #3
Source File: MultiTenancyJobDefinitionSuspensionStateTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void delayedSuspendJobDefinitionsForAllTenants() {
  // given activated job definitions

  engineRule.getManagementService()
    .updateJobDefinitionSuspensionState()
    .byProcessDefinitionKey(PROCESS_DEFINITION_KEY)
    .executionDate(tomorrow())
    .suspend();

  JobDefinitionQuery query = engineRule.getManagementService().createJobDefinitionQuery();
  assertThat(query.active().count(), is(3L));
  assertThat(query.suspended().count(), is(0L));

  // when execute the job to suspend the job definitions
  Job job = engineRule.getManagementService().createJobQuery().timers().singleResult();
  assertThat(job, is(notNullValue()));
  assertThat(getDeploymentIds(query.active()), hasItem(job.getDeploymentId()));

  engineRule.getManagementService().executeJob(job.getId());

  assertThat(query.active().count(), is(0L));
  assertThat(query.suspended().count(), is(3L));
}
 
Example #4
Source File: HistoryCleanupOnEngineBootstrapTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testHistoryCleanupJobScheduled() throws ParseException {

  final ProcessEngineConfigurationImpl standaloneInMemProcessEngineConfiguration = (ProcessEngineConfigurationImpl)ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
  standaloneInMemProcessEngineConfiguration.setHistoryCleanupBatchWindowStartTime("23:00");
  standaloneInMemProcessEngineConfiguration.setHistoryCleanupBatchWindowEndTime("01:00");
  standaloneInMemProcessEngineConfiguration.setJdbcUrl("jdbc:h2:mem:camunda" + getClass().getSimpleName() + "testHistoryCleanupJobScheduled");

  ProcessEngine engine = standaloneInMemProcessEngineConfiguration
    .buildProcessEngine();

  try {
    final List<Job> historyCleanupJobs = engine.getHistoryService().findHistoryCleanupJobs();
    assertFalse(historyCleanupJobs.isEmpty());
    final ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) engine.getProcessEngineConfiguration();
    for (Job historyCleanupJob : historyCleanupJobs) {
      assertEquals(processEngineConfiguration.getBatchWindowManager().getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), processEngineConfiguration).getStart(), historyCleanupJob.getDuedate());
    }
  } finally {
    closeProcessEngine(engine);
  }
}
 
Example #5
Source File: JobDefinitionAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public void testSuspendIncludingJobsByIdWithUpdatePermissionOnAnyProcessInstance() {
  // given
  String jobDefinitionId = selectJobDefinitionByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY).getId();
  String processInstanceId = startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY).getId();

  createGrantAuthorization(PROCESS_DEFINITION, TIMER_BOUNDARY_PROCESS_KEY, userId, UPDATE);
  createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, UPDATE);

  // when
  managementService.suspendJobDefinitionById(jobDefinitionId, true);

  // then
  JobDefinition jobDefinition = selectJobDefinitionByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY);
  assertNotNull(jobDefinition);
  assertTrue(jobDefinition.isSuspended());

  Job job = selectJobByProcessInstanceId(processInstanceId);
  assertNotNull(job);
  assertTrue(job.isSuspended());
}
 
Example #6
Source File: JobDefinitionAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public void testActivateIncludingJobsByProcessDefinitionIdWithUpdatePermissionOnAnyProcessInstance() {
  // given
  String processDefinitionId = selectProcessDefinitionByKey(TIMER_BOUNDARY_PROCESS_KEY).getId();
  String processInstanceId = startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY).getId();
  suspendJobDefinitionIncludingJobsByProcessDefinitionId(processDefinitionId);

  createGrantAuthorization(PROCESS_DEFINITION, TIMER_BOUNDARY_PROCESS_KEY, userId, UPDATE);
  createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, UPDATE);

  // when
  managementService.activateJobDefinitionByProcessDefinitionId(processDefinitionId, true);

  // then
  JobDefinition jobDefinition = selectJobDefinitionByProcessDefinitionKey(TIMER_BOUNDARY_PROCESS_KEY);
  assertNotNull(jobDefinition);
  assertFalse(jobDefinition.isSuspended());

  Job job = selectJobByProcessInstanceId(processInstanceId);
  assertNotNull(job);
  assertFalse(job.isSuspended());
}
 
Example #7
Source File: FoxJobRetryCmdTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testRetryOnTimerStartEventInEventSubProcess() {
  runtimeService.startProcessInstanceByKey("process").getId();

  Job job = managementService.createJobQuery().singleResult();

  assertEquals(3, job.getRetries());

  try {
    managementService.executeJob(job.getId());
    fail();
  } catch (Exception e) {
    // expected
  }

  job = managementService.createJobQuery().singleResult();

  assertEquals(4, job.getRetries());
}
 
Example #8
Source File: UpdateJobAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = {
    "org/camunda/bpm/engine/test/api/authorization/timerBoundaryEventProcess.bpmn20.xml" })
public void shouldActivateJobById() {
  // given
  String processInstanceId = runtimeService
      .startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY)
      .getId();
  String jobId = selectJobByProcessInstanceId(processInstanceId).getId();

  // when
  authRule
    .init(scenario)
    .withUser("userId")
    .bindResource("processInstanceId", processInstanceId)
    .bindResource("someProcessInstanceId", "unexisting")
    .start();

  managementService.activateJobById(jobId);

  // then
  if (authRule.assertScenario(scenario)) {
    Job job = selectJobById(jobId);
    assertThat(job.isSuspended()).isFalse();
  }
}
 
Example #9
Source File: MultiInstanceTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testSequentialSubProcessWithTimer() {
  String procId = runtimeService.startProcessInstanceByKey("miSequentialSubprocessWithTimer").getId();

  // Complete one subprocess
  List<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.createJobQuery().singleResult();
  managementService.executeJob(timer.getId());

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

  assertProcessEnded(procId);
}
 
Example #10
Source File: BatchMigrationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchWithFailedMonitorJobDeletionWithCascade() {
  Batch batch = helper.migrateProcessInstancesAsync(2);
  helper.completeSeedJobs(batch);

  // create incident
  Job monitorJob = helper.getMonitorJob(batch);
  managementService.setJobRetries(monitorJob.getId(), 0);

  // when
  managementService.deleteBatch(batch.getId(), true);

  // then the no historic incidents exists
  long historicIncidents = historyService.createHistoricIncidentQuery().count();
  assertEquals(0, historicIncidents);
}
 
Example #11
Source File: UpdateJobAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = {
    "org/camunda/bpm/engine/test/api/authorization/timerBoundaryEventProcess.bpmn20.xml" })
public void shouldSuspendJobById() {
  // given
  String processInstanceId = runtimeService
      .startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY)
      .getId();
  String jobId = selectJobByProcessInstanceId(processInstanceId).getId();

  // when
  authRule
    .init(scenario)
    .withUser("userId")
    .bindResource("processInstanceId", processInstanceId)
    .bindResource("someProcessInstanceId", "unexisting")
    .start();

  managementService.suspendJobById(jobId);

  // then
  if (authRule.assertScenario(scenario)) {
    Job job = selectJobById(jobId);
    assertThat(job.isSuspended()).isTrue();
  }
}
 
Example #12
Source File: JobPrioritizationBpmnConstantValueTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = "org/camunda/bpm/engine/test/bpmn/job/jobPrioProcess.bpmn20.xml")
public void testActivityPrioritizationAsyncAfter() {
  // given
  runtimeService
    .createProcessInstanceByKey("jobPrioProcess")
    .startBeforeActivity("task2")
    .execute();

  // when
  managementService.executeJob(managementService.createJobQuery().singleResult().getId());

  // then
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  assertEquals(5, job.getPriority());
}
 
Example #13
Source File: BatchMigrationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMonitorJobCreation() {
  Batch batch = helper.migrateProcessInstancesAsync(10);

  // when
  helper.completeSeedJobs(batch);

  // then the seed job definition still exists but the seed job is removed
  JobDefinition seedJobDefinition = helper.getSeedJobDefinition(batch);
  assertNotNull(seedJobDefinition);

  Job seedJob = helper.getSeedJob(batch);
  assertNull(seedJob);

  // and a monitor job definition and job exists
  JobDefinition monitorJobDefinition = helper.getMonitorJobDefinition(batch);
  assertNotNull(monitorJobDefinition);

  Job monitorJob = helper.getMonitorJob(batch);
  assertNotNull(monitorJob);
}
 
Example #14
Source File: JobDto.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public static JobDto fromJob(Job job) {
  JobDto dto = new JobDto();
  dto.id = job.getId();
  dto.jobDefinitionId = job.getJobDefinitionId();
  dto.processInstanceId = job.getProcessInstanceId();
  dto.processDefinitionId = job.getProcessDefinitionId();
  dto.processDefinitionKey = job.getProcessDefinitionKey();
  dto.executionId = job.getExecutionId();
  dto.exceptionMessage = job.getExceptionMessage();
  dto.failedActivityId = job.getFailedActivityId();
  dto.retries = job.getRetries();
  dto.dueDate = job.getDuedate();
  dto.suspended = job.isSuspended();
  dto.priority = job.getPriority();
  dto.tenantId = job.getTenantId();
  dto.createTime = job.getCreateTime();

  return dto;
}
 
Example #15
Source File: MigrationTimerBoundryEventTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMigrationNonInterruptingTimerEvent() {
  // given
  BpmnModelInstance model = createModel(false, DUE_DATE_IN_THE_PAST);
  ProcessDefinition sourceProcessDefinition = testHelper.deployAndGetDefinition(model);
  ProcessDefinition targetProcessDefinition = testHelper.deployAndGetDefinition(model);

  ProcessInstance processInstance = rule.getRuntimeService().startProcessInstanceById(sourceProcessDefinition.getId());

  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  managementService.executeJob(job.getId());

  MigrationPlan migrationPlan = runtimeService.createMigrationPlan(sourceProcessDefinition.getId(), targetProcessDefinition.getId())
    .mapEqualActivities()
    .build();

  // when
  testHelper.migrateProcessInstance(migrationPlan, processInstance);

  // then
  List<Job> list = managementService.createJobQuery().list();
  assertTrue(list.isEmpty());
  assertEquals(1, taskService.createTaskQuery().taskDefinitionKey("afterTimer").count());
  assertEquals(1, taskService.createTaskQuery().taskDefinitionKey("userTask").count());
}
 
Example #16
Source File: ConcurrentJobExecutorTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompetingJobExecutionDeleteJobDuringExecution() {
  //given a simple process with a async service task
  testRule.deploy(Bpmn
          .createExecutableProcess("process")
            .startEvent()
            .serviceTask("task")
              .camundaAsyncBefore()
              .camundaExpression("${true}")
            .endEvent()
          .done());
  runtimeService.startProcessInstanceByKey("process");
  Job currentJob = managementService.createJobQuery().singleResult();

  // when a job is executed
  JobExecutionThread threadOne = new JobExecutionThread(currentJob.getId());
  threadOne.startAndWaitUntilControlIsReturned();
  //and deleted in parallel
  managementService.deleteJob(currentJob.getId());

  // then the job fails with a OLE and the failed job listener throws no NPE
  LOG.debug("test thread notifies thread 1");
  threadOne.proceedAndWaitTillDone();
  assertTrue(threadOne.exception instanceof OptimisticLockingException);
}
 
Example #17
Source File: BatchSuspensionTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSuspendExecutionJobsAndDefinition() {
  // given
  Batch batch = helper.migrateProcessInstancesAsync(1);
  helper.executeSeedJob(batch);

  // when
  managementService.suspendBatchById(batch.getId());

  // then
  JobDefinition migrationJobDefinition = helper.getExecutionJobDefinition(batch);
  assertTrue(migrationJobDefinition.isSuspended());

  Job migrationJob = helper.getExecutionJobs(batch).get(0);
  assertTrue(migrationJob.isSuspended());
}
 
Example #18
Source File: MultiInstanceTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/camunda/bpm/engine/test/bpmn/multiinstance/MultiInstanceTest.testSequentialCallActivityWithTimer.bpmn20.xml",
    "org/camunda/bpm/engine/test/bpmn/multiinstance/MultiInstanceTest.externalSubProcess.bpmn20.xml" })
public void testSequentialCallActivityWithTimer() {
  String procId = runtimeService.startProcessInstanceByKey("miSequentialCallActivityWithTimer").getId();

  // Complete first subprocess
  List<Task> tasks = taskService.createTaskQuery().orderByTaskName().asc().list();
  assertEquals(2, tasks.size());
  assertEquals("task one", tasks.get(0).getName());
  assertEquals("task two", tasks.get(1).getName());
  taskService.complete(tasks.get(0).getId());
  taskService.complete(tasks.get(1).getId());

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

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

  assertProcessEnded(procId);
}
 
Example #19
Source File: UpdateJobAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = {
    "org/camunda/bpm/engine/test/api/authorization/timerBoundaryEventProcess.bpmn20.xml" })
public void shouldActivateJobByProcessInstanceId() {
  // given
  String processInstanceId = runtimeService
      .startProcessInstanceByKey(TIMER_BOUNDARY_PROCESS_KEY)
      .getId();
  String jobId = selectJobByProcessInstanceId(processInstanceId).getId();

  // when
  authRule
  .init(scenario)
  .withUser("userId")
  .bindResource("processInstanceId", processInstanceId)
  .bindResource("someProcessInstanceId", "unexisting")
  .start();

  managementService.activateJobByProcessInstanceId(processInstanceId);

  // then
  if (authRule.assertScenario(scenario)) {
    Job job = selectJobById(jobId);
    assertThat(job.isSuspended()).isFalse();
  }
}
 
Example #20
Source File: BoundaryTimerNonInterruptingEventTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment
@Test
public void testTimerOnConcurrentTasks() {
  String procId = runtimeService.startProcessInstanceByKey("nonInterruptingOnConcurrentTasks").getId();
  assertEquals(2, taskService.createTaskQuery().count());

  Job timer = managementService.createJobQuery().singleResult();
  managementService.executeJob(timer.getId());
  assertEquals(3, taskService.createTaskQuery().count());

  // Complete task that was reached by non interrupting timer
  Task task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask").singleResult();
  taskService.complete(task.getId());
  assertEquals(2, taskService.createTaskQuery().count());

  // Complete other tasks
  for (Task t : taskService.createTaskQuery().list()) {
    taskService.complete(t.getId());
  }
  testHelper.assertProcessEnded(procId);
}
 
Example #21
Source File: MigrationTimerBoundryEventTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMigrationNonTriggeredInterruptingTimerEvent() {
  // given
  Date futureDueDate = DateUtils.addYears(ClockUtil.getCurrentTime(), 1);
  BpmnModelInstance model = createModel(true, sdf.format(futureDueDate));
  ProcessDefinition sourceProcessDefinition = testHelper.deployAndGetDefinition(model);
  ProcessDefinition targetProcessDefinition = testHelper.deployAndGetDefinition(model);

  ProcessInstance processInstance = runtimeService.startProcessInstanceById(sourceProcessDefinition.getId());

  MigrationPlan migrationPlan = runtimeService.createMigrationPlan(sourceProcessDefinition.getId(), targetProcessDefinition.getId())
    .mapEqualActivities()
    .build();

  // when
  testHelper.migrateProcessInstance(migrationPlan, processInstance);

  // then
  List<Job> list = managementService.createJobQuery().list();
  assertEquals(1, list.size());
  assertEquals(0, taskService.createTaskQuery().taskDefinitionKey("afterTimer").count());
  assertEquals(1, taskService.createTaskQuery().taskDefinitionKey("userTask").count());
}
 
Example #22
Source File: AsyncAfterTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testAsyncAfterIntermediateThrowEvent() {
  // start process instance
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("testIntermediateThrowEvent");

  // listeners should be fired by now
  assertListenerStartInvoked(pi);
  assertListenerEndInvoked(pi);

  // the process should wait *after* the throw event
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);

  // if the waiting job is executed, the process instance should end
  managementService.executeJob(job.getId());
  assertProcessEnded(pi.getId());
}
 
Example #23
Source File: BatchModificationHistoryTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testHistoricSeedJobIncidentDeletion() {
  // given
  ProcessDefinition processDefinition = testRule.deployAndGetDefinition(instance);
  Batch batch = helper.startBeforeAsync("process1", 1, "user2", processDefinition.getId());

  Job seedJob = helper.getSeedJob(batch);
  rule.getManagementService().setJobRetries(seedJob.getId(), 0);

  rule.getManagementService().deleteBatch(batch.getId(), false);

  // when
  rule.getHistoryService().deleteHistoricBatch(batch.getId());

  // then the historic incident was deleted
  long historicIncidents = rule.getHistoryService().createHistoricIncidentQuery().count();
  assertEquals(0, historicIncidents);
}
 
Example #24
Source File: JobPrioritizationFailureJavaSerializationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@OperateOnDeployment("dummy-client")
public void testGracefulDegradationOnMissingClassJava() {
  // given
  byte[] serializedPriorityBean = readByteArrayFromClasspath(PRIORITY_BEAN_INSTANCE_FILE);
  String encodedPriorityBean = StringUtil.fromBytes(Base64.encodeBase64(serializedPriorityBean), processEngine);

  Map<String, Object> variables = Variables.createVariables().putValue(
      "priorityBean",
      Variables.serializedObjectValue(encodedPriorityBean)
        .serializationDataFormat(SerializationDataFormats.JAVA)
        .objectTypeName(VARIABLE_CLASS_NAME)
        .create());

  // when
  processInstance = engine1.getRuntimeService().startProcessInstanceByKey("priorityProcess", variables);

  // then the job was created successfully and has the default priority although
  // the bean could not be resolved due to a missing class
  Job job = engine1.getManagementService().createJobQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
  Assert.assertEquals(DefaultJobPriorityProvider.DEFAULT_PRIORITY_ON_RESOLUTION_FAILURE, job.getPriority());
}
 
Example #25
Source File: HistoryCleanupRemovalTimeTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void assumeWhenThenParallelizedCleanup(List<Job> jobs, Supplier<Long> supplier,
                                                 long initialInstanceCount) {
  // assume
  assertThat(jobs.size(), is(3));
  assertThat(supplier.get(), is(initialInstanceCount));

  long expectedInstanceCount = initialInstanceCount-(initialInstanceCount/3);

  for (Job job : jobs) {
    String jobId = job.getId();
    jobIds.add(jobId);

    // when
    managementService.executeJob(jobId);

    // then
    assertThat(supplier.get(), is(expectedInstanceCount));

    expectedInstanceCount = expectedInstanceCount - (initialInstanceCount / 3);
  }
}
 
Example #26
Source File: JobExecutorCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@After
public void resetDatabase() {
  engineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(new Command<Void>() {
    public Void execute(CommandContext commandContext) {
      String handlerType = "history-cleanup";
      List<Job> jobsByHandlerType = commandContext.getJobManager()
          .findJobsByHandlerType(handlerType);

      for (Job job : jobsByHandlerType) {
        commandContext.getJobManager()
            .deleteJob((JobEntity) job);
      }

      commandContext.getHistoricJobLogManager()
          .deleteHistoricJobLogsByHandlerType(handlerType);

      commandContext.getMeterLogManager().deleteAll();

      return null;
    }
  });
}
 
Example #27
Source File: HistoryCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testManualRunDoesNotRespectBatchWindow() {
  //given
  //we have something to cleanup
  int processInstanceCount = 40;
  prepareData(processInstanceCount);

  //we call history cleanup outside batch window
  Date now = new Date();
  ClockUtil.setCurrentTime(now);
  processEngineConfiguration.setHistoryCleanupBatchWindowStartTime(new SimpleDateFormat("HH:mm").format(DateUtils.addHours(now, 1))); //now + 1 hour
  processEngineConfiguration.setHistoryCleanupBatchWindowEndTime(new SimpleDateFormat("HH:mm").format(DateUtils.addHours(now, HISTORY_TIME_TO_LIVE)));   //now + 5 hours
  processEngineConfiguration.initHistoryCleanup();

  //when
  //job is executed before batch window start
  runHistoryCleanup(true);

  //the job is called for the second time after batch window end
  ClockUtil.setCurrentTime(DateUtils.addHours(now, 6)); //now + 6 hours
  for (Job job : historyService.findHistoryCleanupJobs()) {
    managementService.executeJob(job.getId());
  }

  //then
  assertResult(0);
}
 
Example #28
Source File: JobDefinitionRedeploymentTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testJobDefinitionsAfterRedeploment() {

  // initially there are no job definitions:
  assertEquals(0, managementService.createJobDefinitionQuery().count());

  // initial deployment
  String deploymentId = repositoryService.createDeployment()
                          .addClasspathResource(processDefinitionResource)
                          .deploy()
                          .getId();

  ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
  assertNotNull(processDefinition);

  // this parses the process and created the Job definitions:
  List<JobDefinition> jobDefinitions = managementService.createJobDefinitionQuery().list();
  Set<String> jobDefinitionIds = getJobDefinitionIds(jobDefinitions);

  // now clear the cache:
  processEngineConfiguration.getDeploymentCache().discardProcessDefinitionCache();

  // if we start an instance of the process, the process will be parsed again:
  runtimeService.startProcessInstanceByKey(processDefinition.getKey());

  // no new definitions were created
  assertEquals(jobDefinitions.size(), managementService.createJobDefinitionQuery().count());

  // the job has the correct definitionId set:
  List<Job> jobs = managementService.createJobQuery().list();
  for (Job job : jobs) {
    assertTrue(jobDefinitionIds.contains(job.getJobDefinitionId()));
  }

  // delete the deployment
  repositoryService.deleteDeployment(deploymentId, true);
}
 
Example #29
Source File: BoundaryTimerEventTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = "org/camunda/bpm/engine/test/bpmn/event/timer/BoundaryTimerEventTest.testRecalculateUnchangedExpressionOnTimerCurrentDateBased.bpmn20.xml")
public void testRecalculateChangedExpressionOnTimerCurrentDateBased(){
  // Set the clock fixed
  Date startTime = new Date();

  HashMap<String, Object> variables = new HashMap<String, Object>();
  variables.put("duedate", "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());
  Job job = jobs.get(0);
  Date oldDate = job.getDuedate();
  ClockUtil.offset(2000L);

  // After recalculation of the timer, the job's duedate should be changed
  managementService.recalculateJobDuedate(job.getId(), false);
  Job jobUpdated = jobQuery.singleResult();
  assertEquals(job.getId(), jobUpdated.getId());
  assertNotEquals(oldDate, jobUpdated.getDuedate());
  assertTrue(oldDate.before(jobUpdated.getDuedate()));

  // After setting the clock to time '16 minutes', the timer should fire
  ClockUtil.setCurrentTime(new Date(startTime.getTime() + TimeUnit.HOURS.toMillis(2L)));
  waitForJobExecutorToProcessAllJobs(5000L);
  assertEquals(0L, jobQuery.count());

  // which means the process has ended
  assertProcessEnded(pi.getId());
}
 
Example #30
Source File: SuspendJobDefinitionTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/SuspensionTest.testBase.bpmn"})
public void testSuspensionByProcessDefinitionKeyAndSuspendJobsFlag_shouldSuspendJobs() {
  // given
  // a deployed process definition with asynchronous continuation
  ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();

  // a running process instance with a failed job
  Map<String, Object> params = new HashMap<>();
  params.put("fail", Boolean.TRUE);
  runtimeService.startProcessInstanceByKey("suspensionProcess", params);

  // a job definition (which was created for the asynchronous continuation)
  JobDefinition jobDefinition = managementService.createJobDefinitionQuery().singleResult();

  // when
  // suspend the job definition
  managementService.suspendJobDefinitionByProcessDefinitionKey(processDefinition.getKey(), true);

  // then
  // there exists a suspended job definition...
  JobDefinitionQuery jobDefinitionQuery = managementService.createJobDefinitionQuery().suspended();

  assertEquals(1, jobDefinitionQuery.count());

  JobDefinition suspendedJobDefinition = jobDefinitionQuery.singleResult();

  assertEquals(jobDefinition.getId(), suspendedJobDefinition.getId());
  assertTrue(suspendedJobDefinition.isSuspended());

  // ...and a suspended job of the provided job definition
  JobQuery jobQuery = managementService.createJobQuery().suspended();

  assertEquals(1, jobQuery.count());

  Job suspendedJob = jobQuery.singleResult();
  assertEquals(jobDefinition.getId(), suspendedJob.getJobDefinitionId());
  assertTrue(suspendedJob.isSuspended());
}