package org.ohdsi.webapi;

import org.ohdsi.webapi.executionengine.entity.ExecutionEngineAnalysisStatus;
import org.springframework.batch.admin.service.SearchableJobExecutionDao;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import java.util.Calendar;

@Component
@DependsOn("flyway")
public class JobInvalidator {

    public static final String INVALIDATED_BY_SYSTEM_EXIT_MESSAGE = "Invalidated by system";

    private final JobRepository jobRepository;
    private final TransactionTemplate transactionTemplateRequiresNew;
    private final SearchableJobExecutionDao jobExecutionDao;

    @Autowired
    public JobInvalidator(JobRepository repository, TransactionTemplate transactionTemplateRequiresNew,
                          SearchableJobExecutionDao jobExecutionDao) {
        this.jobRepository = repository;
        this.transactionTemplateRequiresNew = transactionTemplateRequiresNew;
        this.jobExecutionDao = jobExecutionDao;
    }

    @PostConstruct
    private void invalidateGenerations() {
        transactionTemplateRequiresNew.execute(s -> {
            jobExecutionDao.getRunningJobExecutions().forEach(this::invalidationJobExecution);
            return null;
        });
    }

    public void invalidateJobExecutionById(ExecutionEngineAnalysisStatus executionEngineAnalysisStatus) {
        JobExecution job = jobExecutionDao.getJobExecution(executionEngineAnalysisStatus.getExecutionEngineGeneration().getId());
        invalidationJobExecution(job);
    }

    public void invalidationJobExecution(JobExecution job) {
        job.setStatus(BatchStatus.FAILED);
        job.setExitStatus(new ExitStatus(ExitStatus.FAILED.getExitCode(), INVALIDATED_BY_SYSTEM_EXIT_MESSAGE));
        job.setEndTime(Calendar.getInstance().getTime());
        jobRepository.update(job);
    }
}

@@ -90,32 +90,89 @@
 AnalysisStatus;%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A
 import org.sprin
@@ -814,16 +814,102 @@
 ator %7B%0A%0A
+    private static final Logger log = LoggerFactory.getLogger(JobInvalidator.class);%0A%0A
     publ
@@ -2024,24 +2024,262 @@
 ).getId());%0A
+        if (job == null %7C%7C job.getJobId() == null) %7B%0A            log.error(%22Cannot invalidate job. There is no job for execution-engine-analysis-status with id = %7B%7D%22, executionEngineAnalysisStatus.getId());%0A            return;%0A        %7D%0A%0A
         inva
@@ -2301,24 +2301,25 @@
 ution(job);%0A
+%0A
     %7D%0A%0A    p

Fix validate job does not find (#1489) (#1602)