<commit_before>/*
 * Copyright (c) 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */



import grails.plugins.quartz.GrailsJobClass
import grails.plugins.quartz.GrailsJobClassConstants as Constants
import grails.plugins.quartz.GrailsJobFactory
import grails.plugins.quartz.JobArtefactHandler
import grails.plugins.quartz.JobDetailFactoryBean
import grails.plugins.quartz.listeners.ExceptionPrinterJobListener
import grails.plugins.quartz.listeners.SessionBinderJobListener
import grails.util.Environment
import org.quartz.*
import org.quartz.spi.MutableTrigger
import org.springframework.beans.factory.config.MethodInvokingFactoryBean
import org.springframework.context.ApplicationContext
import org.springframework.scheduling.quartz.SchedulerFactoryBean

import static grails.plugins.quartz.TriggerUtils.*

/**
 * A plug-in that configures Quartz job support for Grails.
 *
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 */
class QuartzGrailsPlugin {

    def version = "1.0-SNAPSHOT"
    def grailsVersion = "2.0 > *"

    def author = "<NAME>, <NAME>, <NAME>"
    def authorEmail = "<EMAIL>"
    def title = "Quartz plugin for Grails"
    def description = '''\
This plugin adds Quartz job scheduling features to Grails application.
'''
    def documentation = "http://grails.org/plugin/quartz"
    def pluginExcludes = ['grails-app/jobs/**']

    def license = "APACHE"
    def issueManagement = [system: "GitHub Issues", url: "http://jira.grails.org/browse/GPQUARTZ"]
    def scm = [url: "http://github.com/grails-plugins/grails-quartz"]

    def loadAfter = ['core', 'hibernate', 'datasources']
    def watchedResources = [
            "file:./grails-app/jobs/**/*Job.groovy",
            "file:./plugins/*/grails-app/jobs/**/*Job.groovy"
    ]

    def artefacts = [new JobArtefactHandler()]

    /**
     * Configures The Spring context.
     */
    def doWithSpring = { context ->
        def config = loadQuartzConfig(application.config)

        application.jobClasses.each { jobClass ->
            configureJobBeans.delegate = delegate
            configureJobBeans(jobClass, manager.hasGrailsPlugin("hibernate"))
        }

        if (manager?.hasGrailsPlugin("hibernate")) {
            // register SessionBinderJobListener to bind Hibernate Session to each Job's thread
            "${SessionBinderJobListener.NAME}"(SessionBinderJobListener) { bean ->
                bean.autowire = "byName"
            }
        }

        // register global ExceptionPrinterJobListener which will log exceptions occured
        // during job's execution
        "${ExceptionPrinterJobListener.NAME}"(ExceptionPrinterJobListener)

        quartzJobFactory(GrailsJobFactory)

        quartzScheduler(SchedulerFactoryBean) {
            quartzProperties = config._properties

            // Use the instanceName property to set the name of the scheduler
            if (quartzProperties['org.quartz.scheduler.instanceName']) {
                schedulerName = quartzProperties['org.quartz.scheduler.instanceName']
            }

            // delay scheduler startup to after-bootstrap stage
            autoStartup = false
            if (config.jdbcStore) {
                dataSource = ref('dataSource')
                transactionManager = ref('transactionManager')
            }
            waitForJobsToCompleteOnShutdown = config.waitForJobsToCompleteOnShutdown
            exposeSchedulerInRepository = config.exposeSchedulerInRepository
            jobFactory = quartzJobFactory
            if (manager?.hasGrailsPlugin("hibernate")) {
                globalJobListeners = [ref("${SessionBinderJobListener.NAME}"), ref("${ExceptionPrinterJobListener.NAME}")]
            } else {
                globalJobListeners = [ref("${ExceptionPrinterJobListener.NAME}")]
            }
        }

    }

    /**
     * Adds schedule methods for job classes.
     */
    private void addMethods(tc, ctx) {
        Scheduler quartzScheduler = ctx.getBean('quartzScheduler')
        def mc = tc.metaClass
        String jobName = tc.getFullName()
        String jobGroup = tc.getGroup()

        def scheduleTrigger = { Trigger trigger, Map params = null ->
            if (params) {
                trigger.jobDataMap.putAll(params)
            }
            quartzScheduler.scheduleJob(trigger)
        }

        // Schedule with job with cron trigger
        mc.'static'.schedule = { String cronExpression, Map params = null ->
            scheduleTrigger(buildCronTrigger(jobName, jobGroup, cronExpression), params)
        }

        // Schedule the job with simple trigger
        mc.'static'.schedule = {
            Long repeatInterval, Integer repeatCount = SimpleTrigger.REPEAT_INDEFINITELY, Map params = null ->
                scheduleTrigger(buildSimpleTrigger(jobName, jobGroup, repeatInterval, repeatCount), params)
        }

        // Schedule the job at specified time
        mc.'static'.schedule = { Date scheduleDate, Map params = null ->
            scheduleTrigger(buildDateTrigger(jobName, jobGroup, scheduleDate), params)
        }

        // Schedule the job with trigger
        mc.'static'.schedule = { Trigger trigger, Map params = null ->
            JobKey jobKey = new JobKey(jobName, jobGroup)
            if(trigger.jobKey != jobKey && trigger instanceof MutableTrigger){
                trigger.setJobKey(jobKey)
            } else {
                throw new IllegalArgumentException(
                        "The trigger job key is not equals the job key and trigger is immutable."
                )
            }
            if (params) {
                trigger.jobDataMap.putAll(params)
            }
            quartzScheduler.scheduleJob(trigger)
        }

        mc.'static'.triggerNow = { Map params = null ->
            quartzScheduler.triggerJob(new JobKey(jobName, jobGroup), params ? new JobDataMap(params) : null)
        }

        mc.'static'.removeJob = {
            quartzScheduler.deleteJob(new JobKey(jobName, jobGroup))
        }

        mc.'static'.reschedule = { Trigger trigger, Map params = null ->
            if (params) trigger.jobDataMap.putAll(params)
            quartzScheduler.rescheduleJob(trigger.key, trigger)
        }

        mc.'static'.unschedule = { String triggerName, String triggerGroup = Constants.DEFAULT_TRIGGERS_GROUP ->
            quartzScheduler.unscheduleJob(TriggerKey.triggerKey(triggerName, triggerGroup))
        }
    }

    def doWithDynamicMethods = { ctx ->
        application.jobClasses.each { GrailsJobClass tc ->
            addMethods(tc, ctx)
        }
    }

    def doWithApplicationContext = { applicationContext ->
        application.jobClasses.each { jobClass ->
            scheduleJob.delegate = delegate
            scheduleJob(jobClass, applicationContext)
        }
        log.debug("Scheduled Job Classes Count:" + application.jobClasses.size())
    }

    def onChange = { event ->
        if (application.isArtefactOfType(JobArtefactHandler.TYPE, event.source)) {
            log.debug("Job ${event.source} changed. Reloading...")
            def context = event.ctx
            def scheduler = context?.getBean("quartzScheduler")

            def jobClass = application.getJobClass(event.source?.name)

            if (context && jobClass) {
                addMethods(jobClass, context)
            }

            // get quartz scheduler
            if (context && scheduler) {
                // if job already exists, delete it from scheduler                
                if (jobClass) {
                    def jobKey = new JobKey(jobClass.fullName, jobClass.group)
                    scheduler.deleteJob(jobKey)
                    log.debug("Job ${jobClass.fullName} deleted from the scheduler")
                }
<commit_msg>QuartzGrailsPlugin types<commit_after>/*
 * Copyright (c) 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */



import grails.plugins.quartz.GrailsJobClass
import grails.plugins.quartz.GrailsJobClassConstants as Constants
import grails.plugins.quartz.GrailsJobFactory
import grails.plugins.quartz.JobArtefactHandler
import grails.plugins.quartz.JobDetailFactoryBean
import grails.plugins.quartz.listeners.ExceptionPrinterJobListener
import grails.plugins.quartz.listeners.SessionBinderJobListener
import grails.util.Environment
import org.quartz.*
import org.quartz.spi.MutableTrigger
import org.springframework.beans.factory.config.MethodInvokingFactoryBean
import org.springframework.context.ApplicationContext
import org.springframework.scheduling.quartz.SchedulerFactoryBean

import static grails.plugins.quartz.TriggerUtils.*

/**
 * A plug-in that configures Quartz job support for Grails.
 *
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 */
class QuartzGrailsPlugin {

    def version = "1.0-SNAPSHOT"
    def grailsVersion = "2.0 > *"

    def author = "<NAME>, <NAME>, <NAME>"
    def authorEmail = "<EMAIL>"
    def title = "Quartz plugin for Grails"
    def description = '''\
This plugin adds Quartz job scheduling features to Grails application.
'''
    def documentation = "http://grails.org/plugin/quartz"
    def pluginExcludes = ['grails-app/jobs/**']

    def license = "APACHE"
    def issueManagement = [system: "GitHub Issues", url: "http://jira.grails.org/browse/GPQUARTZ"]
    def scm = [url: "http://github.com/grails-plugins/grails-quartz"]

    def loadAfter = ['core', 'hibernate', 'datasources']
    def watchedResources = [
            "file:./grails-app/jobs/**/*Job.groovy",
            "file:./plugins/*/grails-app/jobs/**/*Job.groovy"
    ]

    def artefacts = [new JobArtefactHandler()]

    /**
     * Configures The Spring context.
     */
    def doWithSpring = { context ->
        def config = loadQuartzConfig(application.config)

        application.jobClasses.each { GrailsJobClass jobClass ->
            configureJobBeans.delegate = delegate
            configureJobBeans(jobClass, manager.hasGrailsPlugin("hibernate"))
        }

        if (manager?.hasGrailsPlugin("hibernate")) {
            // register SessionBinderJobListener to bind Hibernate Session to each Job's thread
            "${SessionBinderJobListener.NAME}"(SessionBinderJobListener) { bean ->
                bean.autowire = "byName"
            }
        }

        // register global ExceptionPrinterJobListener which will log exceptions occured
        // during job's execution
        "${ExceptionPrinterJobListener.NAME}"(ExceptionPrinterJobListener)

        quartzJobFactory(GrailsJobFactory)

        quartzScheduler(SchedulerFactoryBean) {
            quartzProperties = config._properties

            // Use the instanceName property to set the name of the scheduler
            if (quartzProperties['org.quartz.scheduler.instanceName']) {
                schedulerName = quartzProperties['org.quartz.scheduler.instanceName']
            }

            // delay scheduler startup to after-bootstrap stage
            autoStartup = false
            if (config.jdbcStore) {
                dataSource = ref('dataSource')
                transactionManager = ref('transactionManager')
            }
            waitForJobsToCompleteOnShutdown = config.waitForJobsToCompleteOnShutdown
            exposeSchedulerInRepository = config.exposeSchedulerInRepository
            jobFactory = quartzJobFactory
            if (manager?.hasGrailsPlugin("hibernate")) {
                globalJobListeners = [ref("${SessionBinderJobListener.NAME}"), ref("${ExceptionPrinterJobListener.NAME}")]
            } else {
                globalJobListeners = [ref("${ExceptionPrinterJobListener.NAME}")]
            }
        }

    }

    /**
     * Adds schedule methods for job classes.
     */
    private void addMethods(tc, ctx) {
        Scheduler quartzScheduler = ctx.getBean('quartzScheduler')
        def mc = tc.metaClass
        String jobName = tc.getFullName()
        String jobGroup = tc.getGroup()

        def scheduleTrigger = { Trigger trigger, Map params = null ->
            if (params) {
                trigger.jobDataMap.putAll(params)
            }
            quartzScheduler.scheduleJob(trigger)
        }

        // Schedule with job with cron trigger
        mc.'static'.schedule = { String cronExpression, Map params = null ->
            scheduleTrigger(buildCronTrigger(jobName, jobGroup, cronExpression), params)
        }

        // Schedule the job with simple trigger
        mc.'static'.schedule = {
            Long repeatInterval, Integer repeatCount = SimpleTrigger.REPEAT_INDEFINITELY, Map params = null ->
                scheduleTrigger(buildSimpleTrigger(jobName, jobGroup, repeatInterval, repeatCount), params)
        }

        // Schedule the job at specified time
        mc.'static'.schedule = { Date scheduleDate, Map params = null ->
            scheduleTrigger(buildDateTrigger(jobName, jobGroup, scheduleDate), params)
        }

        // Schedule the job with trigger
        mc.'static'.schedule = { Trigger trigger, Map params = null ->
            JobKey jobKey = new JobKey(jobName, jobGroup)
            if(trigger.jobKey != jobKey && trigger instanceof MutableTrigger){
                trigger.setJobKey(jobKey)
            } else {
                throw new IllegalArgumentException(
                        "The trigger job key is not equals the job key and trigger is immutable."
                )
            }
            if (params) {
                trigger.jobDataMap.putAll(params)
            }
            quartzScheduler.scheduleJob(trigger)
        }

        mc.'static'.triggerNow = { Map params = null ->
            quartzScheduler.triggerJob(new JobKey(jobName, jobGroup), params ? new JobDataMap(params) : null)
        }

        mc.'static'.removeJob = {
            quartzScheduler.deleteJob(new JobKey(jobName, jobGroup))
        }

        mc.'static'.reschedule = { Trigger trigger, Map params = null ->
            if (params) trigger.jobDataMap.putAll(params)
            quartzScheduler.rescheduleJob(trigger.key, trigger)
        }

        mc.'static'.unschedule = { String triggerName, String triggerGroup = Constants.DEFAULT_TRIGGERS_GROUP ->
            quartzScheduler.unscheduleJob(TriggerKey.triggerKey(triggerName, triggerGroup))
        }
    }

    def doWithDynamicMethods = { ctx ->
        application.jobClasses.each { GrailsJobClass tc ->
            addMethods(tc, ctx)
        }
    }

    def doWithApplicationContext = { applicationContext ->
        application.jobClasses.each { GrailsJobClass jobClass ->
            scheduleJob.delegate = delegate
            scheduleJob(jobClass, applicationContext)
        }
        log.debug("Scheduled Job Classes Count:" + application.jobClasses.size())
    }

    def onChange = { event ->
        if (application.isArtefactOfType(JobArtefactHandler.TYPE, event.source)) {
            log.debug("Job ${event.source} changed. Reloading...")
            def context = event.ctx
            def scheduler = context?.getBean("quartzScheduler")

            def jobClass = application.getJobClass(event.source?.name)

            if (context && jobClass) {
                addMethods(jobClass, context)
            }

            // get quartz scheduler
            if (context && scheduler) {
                // if job already exists, delete it from scheduler                
                if (jobClass) {
                    def jobKey = new JobKey(jobClass.fullName, jobClass.group)
                    scheduler.deleteJob(jobKey)
                    log.debug("Job ${jobClass.fullName} deleted from the scheduler")
                }

{'fraction_non_alphanumeric': 0.09437234615154597, 'fraction_numerical': 0.001435320854015908, 'mean_word_length': 2.4140465496120864, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 53, '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': '1173159', 'n_tokens_mistral': 4536, 'n_tokens_neox': 4302, 'n_words': 1063}