<commit_before>/*
 * Copyright 2007 The Kuali Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kfs.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.core.KualiModule;
import org.kuali.core.service.DateTimeService;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.service.KualiModuleService;
import org.kuali.core.service.MailService;
import org.kuali.core.util.spring.NamedOrderedListBean;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.batch.BatchJobStatus;
import org.kuali.kfs.batch.Job;
import org.kuali.kfs.batch.JobDescriptor;
import org.kuali.kfs.batch.JobListener;
import org.kuali.kfs.batch.SimpleTriggerDescriptor;
import org.kuali.kfs.batch.Step;
import org.kuali.kfs.service.SchedulerService;
import org.kuali.kfs.util.SpringServiceLocator;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.ObjectAlreadyExistsException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.UnableToInterruptJobException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class SchedulerServiceImpl implements SchedulerService {
    private static final Logger LOG = Logger.getLogger(SchedulerServiceImpl.class);
    private static final String SCHEDULE_JOB_NAME = "scheduleJob";
    private static final String JOB_STATUS_PARAMETER = "status";
    private static final String SOFT_DEPENDENCY_CODE = "softDependency";
    private static final String HARD_DEPENDENCY_CODE = "hardDependency";

    private Scheduler scheduler;
    private JobListener jobListener;
    private KualiModuleService moduleService;
    private KualiConfigurationService configurationService;
    private DateTimeService dateTimeService;
    private MailService mailService;

    protected static final List<String> jobStatuses = new ArrayList<String>();

    static {
        jobStatuses.add(SCHEDULED_JOB_STATUS_CODE);
        jobStatuses.add(SUCCEEDED_JOB_STATUS_CODE);
        jobStatuses.add(CANCELLED_JOB_STATUS_CODE);
        jobStatuses.add(RUNNING_JOB_STATUS_CODE);
        jobStatuses.add(FAILED_JOB_STATUS_CODE);
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#initialize()
     */
    public void initialize() {
        LOG.info("Initializing the schedule");
        jobListener.setSchedulerService(this);
        try {
            scheduler.addGlobalJobListener(jobListener);
        }
        catch (SchedulerException e) {
            throw new RuntimeException("SchedulerServiceImpl encountered an exception when trying to register the global job listener", e);
        }
        for (NamedOrderedListBean namedOrderedListBean : SpringServiceLocator.getNamedOrderedListBeans(KFSConstants.JOB_NAMES_LIST_NAME)) {
            for (String jobName : namedOrderedListBean.getList()) {
                try {
                    loadJob(SpringServiceLocator.getJobDescriptor(jobName));
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find job bean definition for job: " + ex.getBeanName(), ex);
                }
            }
        }
        for (NamedOrderedListBean namedOrderedListBean : SpringServiceLocator.getNamedOrderedListBeans(KFSConstants.TRIGGER_NAMES_LIST_NAME)) {
            for (String triggerName : namedOrderedListBean.getList()) {
                try {
                    addTrigger(SpringServiceLocator.getTriggerDescriptor(triggerName).getTrigger());
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find trigger definition: " + ex.getBeanName(), ex);
                }
            }
        }
        for (KualiModule module : moduleService.getInstalledModules()) {
            LOG.info("Loading scheduled jobs for: " + module.getModuleId());
            for (String jobName : module.getJobNames()) {
                try {
                    loadJob(SpringServiceLocator.getJobDescriptor(jobName));
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find job bean definition for job: " + ex.getBeanName(), ex);
                }
            }
            for (String triggerName : module.getTriggerNames()) {
                try {
                    addTrigger(SpringServiceLocator.getTriggerDescriptor(triggerName).getTrigger());
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find trigger definition: " + ex.getBeanName(), ex);
                }
            }
        }
    }

    private void loadJob(JobDescriptor jobDescriptor) {
        JobDetail jobDetail = jobDescriptor.getJobDetail();
        addJob(jobDetail);
        if (SCHEDULED_GROUP.equals(jobDetail.getGroup())) {
            jobDetail.setGroup(UNSCHEDULED_GROUP);
            addJob(jobDetail);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#initializeJob(java.lang.String,org.kuali.kfs.batch.Job)
     */
    public void initializeJob(String jobName, Job job) {
        job.setSchedulerService(this);
        job.setConfigurationService(configurationService);
        job.setSteps((SpringServiceLocator.getJobDescriptor(jobName)).getSteps());
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#hasIncompleteJob()
     */
    public boolean hasIncompleteJob() {
        try {
            for (String scheduledJobName : scheduler.getJobNames(SCHEDULED_GROUP)) {
                JobDetail scheduledJobDetail = getScheduledJobDetail(scheduledJobName);
                if (!SCHEDULE_JOB_NAME.equals(scheduledJobDetail.getName()) && (isPending(scheduledJobDetail) || isScheduled(scheduledJobDetail))) {
                    return true;
                }
            }
            return false;
        }
        catch (SchedulerException e) {
            throw new RuntimeException("Caught exception while checking for incomplete jobs", e);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#isPastScheduleCutoffTime()
     */
    public boolean isPastScheduleCutoffTime() {
        try {
            Calendar scheduleCutoffTime = dateTimeService.getCalendar(scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0].getStartTime());
            String[] scheduleStepCutoffTime = StringUtils.split(configurationService.getApplicationParameterValue(KFSConstants.ParameterGroups.SYSTEM, KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME), ":");
            scheduleCutoffTime.set(GregorianCalendar.HOUR, Integer.parseInt(scheduleStepCutoffTime[0]));
            scheduleCutoffTime.set(GregorianCalendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
            scheduleCutoffTime.set(GregorianCalendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
            if (configurationService.getApplicationParameterIndicator(KFSConstants.ParameterGroups.SYSTEM, KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
                scheduleCutoffTime.add(GregorianCalendar.DAY_OF_YEAR, 1);
            }
            return dateTimeService.getCurrentCalendar().after(scheduleCutoffTime);
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("Caught exception while checking whether we've exceeded the schedule cutoff time", e);
        }
        catch (SchedulerException e) {
            throw new RuntimeException("Caught exception while checking whether we've exceeded the schedule cutoff time", e);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#processWaitingJobs()
     */
    public void processWaitingJobs() {
        try {<commit_msg>*** empty log message ***<commit_after>/*
 * Copyright 2007 The Kuali Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kfs.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.core.KualiModule;
import org.kuali.core.service.DateTimeService;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.service.KualiModuleService;
import org.kuali.core.service.MailService;
import org.kuali.core.util.spring.NamedOrderedListBean;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.batch.BatchJobStatus;
import org.kuali.kfs.batch.Job;
import org.kuali.kfs.batch.JobDescriptor;
import org.kuali.kfs.batch.JobListener;
import org.kuali.kfs.batch.SimpleTriggerDescriptor;
import org.kuali.kfs.batch.Step;
import org.kuali.kfs.service.SchedulerService;
import org.kuali.kfs.util.SpringServiceLocator;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.ObjectAlreadyExistsException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.UnableToInterruptJobException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class SchedulerServiceImpl implements SchedulerService {
    private static final Logger LOG = Logger.getLogger(SchedulerServiceImpl.class);
    private static final String SCHEDULE_JOB_NAME = "scheduleJob";
    private static final String JOB_STATUS_PARAMETER = "status";
    private static final String SOFT_DEPENDENCY_CODE = "softDependency";
    private static final String HARD_DEPENDENCY_CODE = "hardDependency";

    private Scheduler scheduler;
    private JobListener jobListener;
    private KualiModuleService moduleService;
    private KualiConfigurationService configurationService;
    private DateTimeService dateTimeService;
    private MailService mailService;

    protected static final List<String> jobStatuses = new ArrayList<String>();

    static {
        jobStatuses.add(SCHEDULED_JOB_STATUS_CODE);
        jobStatuses.add(SUCCEEDED_JOB_STATUS_CODE);
        jobStatuses.add(CANCELLED_JOB_STATUS_CODE);
        jobStatuses.add(RUNNING_JOB_STATUS_CODE);
        jobStatuses.add(FAILED_JOB_STATUS_CODE);
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#initialize()
     */
    public void initialize() {
        LOG.info("Initializing the schedule");
        jobListener.setSchedulerService(this);
        try {
            scheduler.addGlobalJobListener(jobListener);
        }
        catch (SchedulerException e) {
            throw new RuntimeException("SchedulerServiceImpl encountered an exception when trying to register the global job listener", e);
        }
        for (NamedOrderedListBean namedOrderedListBean : SpringServiceLocator.getNamedOrderedListBeans(KFSConstants.JOB_NAMES_LIST_NAME)) {
            for (String jobName : namedOrderedListBean.getList()) {
                try {
                    loadJob(SpringServiceLocator.getJobDescriptor(jobName));
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find job bean definition for job: " + ex.getBeanName(), ex);
                }
            }
        }
        for (NamedOrderedListBean namedOrderedListBean : SpringServiceLocator.getNamedOrderedListBeans(KFSConstants.TRIGGER_NAMES_LIST_NAME)) {
            for (String triggerName : namedOrderedListBean.getList()) {
                try {
                    addTrigger(SpringServiceLocator.getTriggerDescriptor(triggerName).getTrigger());
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find trigger definition: " + ex.getBeanName(), ex);
                }
            }
        }
        for (KualiModule module : moduleService.getInstalledModules()) {
            LOG.info("Loading scheduled jobs for: " + module.getModuleId());
            for (String jobName : module.getJobNames()) {
                try {
                    loadJob(SpringServiceLocator.getJobDescriptor(jobName));
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find job bean definition for job: " + ex.getBeanName(), ex);
                }
            }
            for (String triggerName : module.getTriggerNames()) {
                try {
                    addTrigger(SpringServiceLocator.getTriggerDescriptor(triggerName).getTrigger());
                }
                catch (NoSuchBeanDefinitionException ex) {
                    LOG.error("unable to find trigger definition: " + ex.getBeanName(), ex);
                }
            }
        }
    }

    private void loadJob(JobDescriptor jobDescriptor) {
        JobDetail jobDetail = jobDescriptor.getJobDetail();
        addJob(jobDetail);
        if (SCHEDULED_GROUP.equals(jobDetail.getGroup())) {
            jobDetail.setGroup(UNSCHEDULED_GROUP);
            addJob(jobDetail);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#initializeJob(java.lang.String,org.kuali.kfs.batch.Job)
     */
    public void initializeJob(String jobName, Job job) {
        job.setSchedulerService(this);
        job.setConfigurationService(configurationService);
        job.setSteps((SpringServiceLocator.getJobDescriptor(jobName)).getSteps());
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#hasIncompleteJob()
     */
    public boolean hasIncompleteJob() {
        try {
            for (String scheduledJobName : scheduler.getJobNames(SCHEDULED_GROUP)) {
                JobDetail scheduledJobDetail = getScheduledJobDetail(scheduledJobName);
                if (!SCHEDULE_JOB_NAME.equals(scheduledJobDetail.getName()) && (isPending(scheduledJobDetail) || isScheduled(scheduledJobDetail))) {
                    return true;
                }
            }
            return false;
        }
        catch (SchedulerException e) {
            throw new RuntimeException("Caught exception while checking for incomplete jobs", e);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#isPastScheduleCutoffTime()
     */
    public boolean isPastScheduleCutoffTime() {
        try {
            Calendar scheduleCutoffTime = dateTimeService.getCalendar(scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0].getPreviousFireTime());
            String[] scheduleStepCutoffTime = StringUtils.split(configurationService.getApplicationParameterValue(KFSConstants.ParameterGroups.SYSTEM, KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME), ":");
            scheduleCutoffTime.set(GregorianCalendar.HOUR, Integer.parseInt(scheduleStepCutoffTime[0]));
            scheduleCutoffTime.set(GregorianCalendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
            scheduleCutoffTime.set(GregorianCalendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
            if (configurationService.getApplicationParameterIndicator(KFSConstants.ParameterGroups.SYSTEM, KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
                scheduleCutoffTime.add(GregorianCalendar.DAY_OF_YEAR, 1);
            }
            return dateTimeService.getCurrentCalendar().after(scheduleCutoffTime);
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("Caught exception while checking whether we've exceeded the schedule cutoff time", e);
        }
        catch (SchedulerException e) {
            throw new RuntimeException("Caught exception while checking whether we've exceeded the schedule cutoff time", e);
        }
    }

    /**
     * @see org.kuali.kfs.service.SchedulerService#processWaitingJobs()
     */
    public void processWaitingJobs() {
        try {
{'fraction_non_alphanumeric': 0.08697660987583021, 'fraction_numerical': 0.0015015882183078257, 'mean_word_length': 3.0810747112891823, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3635012', 'n_tokens_mistral': 4792, 'n_tokens_neox': 4677, 'n_words': 924}