org.camunda.bpm.engine.impl.persistence.entity.JobEntity Java Examples

The following examples show how to use org.camunda.bpm.engine.impl.persistence.entity.JobEntity. 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: JobEntityHandler.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Statement
public List<JobEntity> selectJobsByConfiguration(OPersistenceSession session, ListQueryParameterObject query) {
	Map<String, Object> params = (Map<String, Object>) query.getParameter(); 
    String config = (String) params.get("handlerConfiguration");
    String followUpConfig = (String) params.get("handlerConfigurationWithFollowUpJobCreatedProperty");
    String type = (String) params.get("handlerType");
    List<String> args = new ArrayList<>();
    Query q = new Query().from(getSchemaClass());
    q.where(Clause.clause("jobHandlerType", Operator.EQ, Parameter.PARAMETER));
    args.add(type);
    Clause eqConfig = Clause.clause("JobHandlerConfigurationRaw", Operator.EQ, Parameter.PARAMETER);
    if(Strings.isEmpty(followUpConfig)) {
    	q.where(eqConfig);
    	args.add(config);
    } else {
    	q.where(Clause.or(eqConfig, eqConfig));
    	args.add(config); 
    	args.add(followUpConfig);
    }
    return queryList(session, q.toString(), args.toArray());
}
 
Example #2
Source File: DeleteJobCmd.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public Object execute(CommandContext commandContext) {
  ensureNotNull("jobId", jobId);

  JobEntity job = commandContext.getJobManager().findJobById(jobId);
  ensureNotNull("No job found with id '" + jobId + "'", "job", job);

  for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
    checker.checkUpdateJob(job);
  }
  // We need to check if the job was locked, ie acquired by the job acquisition thread
  // This happens if the the job was already acquired, but not yet executed.
  // In that case, we can't allow to delete the job.
  if (job.getLockOwner() != null || job.getLockExpirationTime() != null) {
    throw new ProcessEngineException("Cannot delete job when the job is being executed. Try again later.");
  }

  commandContext.getOperationLogManager().logJobOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, jobId, 
      job.getJobDefinitionId(), job.getProcessInstanceId(), job.getProcessDefinitionId(), 
      job.getProcessDefinitionKey(), PropertyChange.EMPTY_CHANGE);
  
  job.delete();
  return null;
}
 
Example #3
Source File: AcquirableJobCacheTest.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/mgmt/metrics/asyncServiceTaskProcess.bpmn20.xml")
public void testFetchJobEntityWhenAcquirableJobIsCached() {
  // given
  runtimeService.startProcessInstanceByKey("asyncServiceTaskProcess");

  try {
    // when
    fetchJobAfterCachedAcquirableJob();
    fail("expected exception");
  } catch (Exception e) {
    // then
    assertThat(e).isInstanceOf(ProcessEngineException.class);
    assertThat(e.getMessage())
        .contains("Could not lookup entity of type")
        .contains(AcquirableJobEntity.class.getSimpleName())
        .contains(JobEntity.class.getSimpleName());
  }
}
 
Example #4
Source File: HostnameProviderTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void closeProcessEngine() {
  final HistoryService historyService = engine.getHistoryService();
  configuration.getCommandExecutorTxRequired().execute((Command<Void>) commandContext -> {

    List<Job> jobs = historyService.findHistoryCleanupJobs();
    for (Job job: jobs) {
      commandContext.getJobManager().deleteJob((JobEntity) job);
      commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(job.getId());
    }

    //cleanup "detached" historic job logs
    final List<HistoricJobLog> list = historyService.createHistoricJobLogQuery().list();
    for (HistoricJobLog jobLog: list) {
      commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(jobLog.getJobId());
    }

    commandContext.getMeterLogManager().deleteAll();

    return null;
  });

  engine.close();
  engine = null;
}
 
Example #5
Source File: HistoryCleanupOnEngineBootstrapTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void closeProcessEngine(ProcessEngine processEngine) {
  ProcessEngineConfigurationImpl configuration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
  final HistoryService historyService = processEngine.getHistoryService();
  configuration.getCommandExecutorTxRequired().execute((Command<Void>) commandContext -> {

    List<Job> jobs = historyService.findHistoryCleanupJobs();
    for (Job job: jobs) {
      commandContext.getJobManager().deleteJob((JobEntity) job);
      commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(job.getId());
    }

    //cleanup "detached" historic job logs
    final List<HistoricJobLog> list = historyService.createHistoricJobLogQuery().list();
    for (HistoricJobLog jobLog: list) {
      commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(jobLog.getJobId());
    }

    commandContext.getMeterLogManager().deleteAll();

    return null;
  });

  processEngine.close();
}
 
Example #6
Source File: DefaultJobRetryCmd.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public Object execute(CommandContext commandContext) {
  JobEntity job = getJob();

  ActivityImpl activity = getCurrentActivity(commandContext, job);

  if (activity == null) {
    LOG.debugFallbackToDefaultRetryStrategy();
    executeStandardStrategy(commandContext);

  } else {
    try {
      executeCustomStrategy(commandContext, job, activity);

    } catch (Exception e) {
      LOG.debugFallbackToDefaultRetryStrategy();
      executeStandardStrategy(commandContext);
    }
  }

  return null;
}
 
Example #7
Source File: DbEntityCacheKeyMapping.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public static DbEntityCacheKeyMapping defaultEntityCacheKeyMapping() {
  DbEntityCacheKeyMapping mapping = new DbEntityCacheKeyMapping();

  mapping.registerEntityCacheKey(JobEntity.class, AcquirableJobEntity.class);
  // subclasses of JobEntity
  mapping.registerEntityCacheKey(MessageEntity.class, AcquirableJobEntity.class);
  mapping.registerEntityCacheKey(TimerEntity.class, AcquirableJobEntity.class);

  // subclasses of HistoricDetailEventEntity
  mapping.registerEntityCacheKey(HistoricFormPropertyEntity.class, HistoricDetailEventEntity.class);
  mapping.registerEntityCacheKey(HistoricFormPropertyEventEntity.class, HistoricDetailEventEntity.class);
  mapping.registerEntityCacheKey(HistoricVariableUpdateEventEntity.class, HistoricDetailEventEntity.class);
  mapping.registerEntityCacheKey(HistoricDetailVariableInstanceUpdateEntity.class, HistoricDetailEventEntity.class);

  return mapping;
}
 
Example #8
Source File: HistoryCleanupCmd.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void suspendJobs(List<Job> jobs) {
  for (Job job: jobs) {
    JobEntity jobInstance = (JobEntity) job;
    jobInstance.setSuspensionState(SuspensionState.SUSPENDED.getStateCode());
    jobInstance.setDuedate(null);
  }
}
 
Example #9
Source File: ProcessEngineBootstrapRule.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private void deleteHistoryCleanupJob() {
  final List<Job> jobs = processEngine.getHistoryService().findHistoryCleanupJobs();
  for (final Job job: jobs) {
    ((ProcessEngineConfigurationImpl)processEngine.getProcessEngineConfiguration()).getCommandExecutorTxRequired().execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {
        commandContext.getJobManager().deleteJob((JobEntity) job);
        commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(job.getId());
        return null;
      }
    });
  }
}
 
Example #10
Source File: SetProcessDefinitionVersionCmd.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void switchVersionOfJob(JobEntity jobEntity, ProcessDefinitionEntity newProcessDefinition, Map<String, String> jobDefinitionMapping) {
  jobEntity.setProcessDefinitionId(newProcessDefinition.getId());
  jobEntity.setDeploymentId(newProcessDefinition.getDeploymentId());

  String newJobDefinitionId = jobDefinitionMapping.get(jobEntity.getJobDefinitionId());
  jobEntity.setJobDefinitionId(newJobDefinitionId);
}
 
Example #11
Source File: HistoryCleanupSchedulerCmd.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void rescheduleRegularCall(CommandContext commandContext, JobEntity jobEntity) {
  final BatchWindow nextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager()
    .getNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration());
  if (nextBatchWindow != null) {
    commandContext.getJobManager().reschedule(jobEntity, nextBatchWindow.getStart());
  } else {
    LOG.warnHistoryCleanupBatchWindowNotFound();
    suspendJob(jobEntity);
  }
}
 
Example #12
Source File: ExclusiveTaskTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testExclusiveService() {
  // start process
  runtimeService.startProcessInstanceByKey("exclusive");
  // now there should be 1 exclusive job in the database:
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  assertTrue(((JobEntity)job).isExclusive());

  waitForJobExecutorToProcessAllJobs(6000L);

  // all the jobs are done
  assertEquals(0, managementService.createJobQuery().count());
}
 
Example #13
Source File: ExclusiveCatchEventTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testNonExclusiveCatchEvent() {
  // start process 
  runtimeService.startProcessInstanceByKey("exclusive");
  // now there should be 1 non-exclusive job in the database:
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  assertFalse(((JobEntity)job).isExclusive());
             
  waitForJobExecutorToProcessAllJobs(6000L);
  
  // all the jobs are done
  assertEquals(0, managementService.createJobQuery().count());      
}
 
Example #14
Source File: FailedJobListenerWithRetriesTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
@org.camunda.bpm.engine.test.Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/IncidentTest.testShouldCreateOneIncident.bpmn"})
public void testFailedJobListenerRetries() {
  //given
  runtimeService.startProcessInstanceByKey("failingProcess");

  //when the job is run several times till the incident creation
  Job job = getJob();
  while (job.getRetries() > 0 && ((JobEntity)job).getLockOwner() == null ) {
    try {
      lockTheJob(job.getId());
      engineRule.getManagementService().executeJob(job.getId());
    } catch (Exception ex) {
    }
    job = getJob();
  }

  //then
  JobEntity jobFinalState = (JobEntity)engineRule.getManagementService().createJobQuery().jobId(job.getId()).list().get(0);
  assertEquals(jobRetries, jobFinalState.getRetries());
  if (jobLocked) {
    assertNotNull(jobFinalState.getLockOwner());
    assertNotNull(jobFinalState.getLockExpirationTime());
  } else {
    assertNull(jobFinalState.getLockOwner());
    assertNull(jobFinalState.getLockExpirationTime());
  }
}
 
Example #15
Source File: AcquirableJobCacheTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected JobEntity fetchJobAfterCachedAcquirableJob() {
  return processEngineConfiguration.getCommandExecutorTxRequiresNew().execute(new Command<JobEntity>() {
    public JobEntity execute(CommandContext commandContext) {
      JobManager jobManager = commandContext.getJobManager();
      List<AcquirableJobEntity> acquirableJobs = jobManager.findNextJobsToExecute(new Page(0, 100));
      JobEntity job = jobManager.findJobById(acquirableJobs.get(0).getId());
      return job;
    }
  });
}
 
Example #16
Source File: ActivityInstanceHandler.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected List<JobEntity> collectActivityInstanceJobs(MigratingActivityInstance migratingInstance) {
  if (migratingInstance.getSourceScope().isScope()) {
    return migratingInstance.resolveRepresentativeExecution().getJobs();
  }
  else {
    return Collections.emptyList();
  }
}
 
Example #17
Source File: CustomHistoryLevelIncidentTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteHistoricIncidentByJobDefinitionId() {
  // given
  BatchEntity batch = (BatchEntity) createFailingMigrationBatch();

  migrationHelper.completeSeedJobs(batch);

  List<Job> list = managementService.createJobQuery().list();
  for (Job job : list) {
    if (((JobEntity) job).getJobHandlerType().equals("instance-migration")) {
      managementService.setJobRetries(job.getId(), 1);
    }
  }
  migrationHelper.executeJobs(batch);

  // assume
  if (eventTypes != null) {
    HistoricIncident historicIncident = historyService.createHistoricIncidentQuery().singleResult();
    assertNotNull(historicIncident);
  }

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

  // then
  List<HistoricIncident> incidents = historyService.createHistoricIncidentQuery().list();
  assertEquals(0, incidents.size());
}
 
Example #18
Source File: BatchEntity.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void deleteSeedJob() {
  List<JobEntity> seedJobs = Context.getCommandContext()
    .getJobManager()
    .findJobsByJobDefinitionId(seedJobDefinitionId);

  for (JobEntity job : seedJobs) {
    job.delete();
  }
}
 
Example #19
Source File: ConcurrentJobExecutorTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@After
public void deleteJobs() {
  for(final Job job : managementService.createJobQuery().list()) {

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      public Void execute(CommandContext commandContext) {
        ((JobEntity) job).delete();
        return null;
      }
    });
  }
}
 
Example #20
Source File: ConcurrentHistoryCleanupReconfigureTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void makeEverLivingJobFail(final String jobId) {
  processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {
    @Override
    public Void execute(CommandContext commandContext) {

      JobEntity job = commandContext.getJobManager().findJobById(jobId);

      job.setExceptionStacktrace("foo");

      return null;
    }
  });
}
 
Example #21
Source File: JobTimestampsTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@ScenarioUnderTest("initJobTimestamps.1")
@Test
public void testLockExpirationTimeConversion() {

  JobEntity job = (JobEntity) managementService.createJobQuery()
    .processDefinitionKey(PROCESS_DEFINITION_KEY)
    .singleResult();

  // assume
  assertNotNull(job);

  // then
  assertThat(job.getLockExpirationTime(), is(LOCK_EXP_TIME));
}
 
Example #22
Source File: ControllableJobExecutor.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void rethrowOptimisticLockingException(CommandContext commandContext) {
  commandContext.getDbEntityManager().registerOptimisticLockingListener(new OptimisticLockingListener() {

    public Class<? extends DbEntity> getEntityType() {
      return JobEntity.class;
    }

    public void failedOperation(DbOperation operation) {
      oleThrown = true;
    }

  });
}
 
Example #23
Source File: Executable.java    From camunda-bpm-assert-scenario with Apache License 2.0 5 votes vote down vote up
static JobExecutable newInstance(ProcessRunnerImpl runner, Job job) {
  JobEntity entity = (JobEntity) job;
  String type = entity.getJobHandlerType();
  if (types.containsKey(type)) {
    try {
      return (JobExecutable) Class.forName(ContinuationExecutable.class.getPackage().getName() + "." + types.get(type)).getConstructor(ProcessRunnerImpl.class, Job.class).newInstance(runner, job);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
  return null;
}
 
Example #24
Source File: MigrationBatchJobHandler.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void postProcessJob(MigrationBatchConfiguration configuration, JobEntity job) {
  if (job.getDeploymentId() == null) {
    CommandContext commandContext = Context.getCommandContext();
    String sourceProcessDefinitionId = configuration.getMigrationPlan().getSourceProcessDefinitionId();

    ProcessDefinitionEntity processDefinition = getProcessDefinition(commandContext, sourceProcessDefinitionId);
    job.setDeploymentId(processDefinition.getDeploymentId());
  }
}
 
Example #25
Source File: MigratingTimerJobInstance.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected ScopeImpl determineTimerTriggerTargetScope(JobEntity jobEntity, ScopeImpl targetScope) {
  if (TimerStartEventSubprocessJobHandler.TYPE.equals(jobEntity.getJobHandlerType())) {
    // for event subprocess start jobs, the job handler configuration references the subprocess while
    // the job references the start event
    return targetScope.getFlowScope();
  }
  else {
    return targetScope;
  }
}
 
Example #26
Source File: MigratingTimerJobInstance.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public MigratingTimerJobInstance(JobEntity jobEntity,
    JobDefinitionEntity jobDefinitionEntity,
    ScopeImpl targetScope,
    boolean updateEvent,
    TimerDeclarationImpl targetTimerDeclaration) {
  super(jobEntity, jobDefinitionEntity, targetScope);
  timerTriggerTargetScope = determineTimerTriggerTargetScope(jobEntity, targetScope);
  this.updateEvent = updateEvent;
  this.targetJobDeclaration = targetTimerDeclaration;
}
 
Example #27
Source File: JobTimestampsUpdateTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@ScenarioUnderTest("initJobTimestamps.1")
@Test
public void testLockExpirationTimeConversion() {

  JobEntity job = (JobEntity) rule.jobQuery().singleResult();

  // assume
  assertNotNull(job);

  // then
  assertThat(job.getLockExpirationTime(), is(LOCK_EXP_TIME));
}
 
Example #28
Source File: ConcurrentJobExecutorTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testCompetingJobExecutionFoxRetryStrategy() {
  // given an MI subprocess with two instances
  runtimeService.startProcessInstanceByKey("miParallelSubprocess");

  List<Job> currentJobs = managementService.createJobQuery().list();
  assertEquals(2, currentJobs.size());

  // when the jobs are executed in parallel
  JobExecutionThread threadOne = new JobExecutionThread(currentJobs.get(0).getId());
  threadOne.startAndWaitUntilControlIsReturned();

  JobExecutionThread threadTwo = new JobExecutionThread(currentJobs.get(1).getId());
  threadTwo.startAndWaitUntilControlIsReturned();

  // then the first committing thread succeeds
  LOG.debug("test thread notifies thread 1");
  threadOne.proceedAndWaitTillDone();
  assertNull(threadOne.exception);

  // then the second committing thread fails with an OptimisticLockingException
  // and the job retries have not been decremented
  LOG.debug("test thread notifies thread 2");
  threadTwo.proceedAndWaitTillDone();
  assertNotNull(threadTwo.exception);

  Job remainingJob = managementService.createJobQuery().singleResult();
  // retries are configured as R5/PT5M, so no decrement means 5 retries left
  assertEquals(5, remainingJob.getRetries());

  assertNotNull(remainingJob.getExceptionMessage());

  JobEntity jobEntity = (JobEntity) remainingJob;
  assertNull(jobEntity.getLockOwner());

  // and there is a due date time set
  assertNotNull(jobEntity.getDuedate());
}
 
Example #29
Source File: ExclusiveStartEventTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testExclusiveStartEvent() {
  // start process 
  runtimeService.startProcessInstanceByKey("exclusive");
  // now there should be 1 exclusive job in the database:
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  assertTrue(((JobEntity)job).isExclusive());
             
  waitForJobExecutorToProcessAllJobs(6000L);
  
  // all the jobs are done
  assertEquals(0, managementService.createJobQuery().count());      
}
 
Example #30
Source File: ExclusiveTaskTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testNonExclusiveService() {
  // start process
  runtimeService.startProcessInstanceByKey("exclusive");
  // now there should be 1 non-exclusive job in the database:
  Job job = managementService.createJobQuery().singleResult();
  assertNotNull(job);
  assertFalse(((JobEntity)job).isExclusive());

  waitForJobExecutorToProcessAllJobs(6000L);

  // all the jobs are done
  assertEquals(0, managementService.createJobQuery().count());
}