com.athena.peacock.agent.scheduler.quartz.BaseJob.java Source code

Java tutorial

Introduction

Here is the source code for com.athena.peacock.agent.scheduler.quartz.BaseJob.java

Source

/* 
 * Copyright 2013 The Athena-Peacock Project.
 *
 * 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.
 *
 * Revision History
 * Author         Date            Description
 * ---------------   ----------------   ------------
 * Sang-cheon Park   2013. 8. 1.      First Draft.
 */
package com.athena.peacock.agent.scheduler.quartz;

import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.lang.time.DateFormatUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.context.ApplicationContext;

import com.athena.peacock.agent.scheduler.InternalJobExecutionException;

/**
 * <pre>
 * ? ?  ?,   ??  ? ??.
 * </pre>
 * @author Sang-cheon Park
 * @version 1.0
 */
public abstract class BaseJob implements Job, JobEventListener {

    protected static final Logger logger = LoggerFactory.getLogger(BaseJob.class);
    private static final String LOGGING_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String APPLICAITON_CONTEXT_KEY = "APPCTX";

    protected ApplicationContext context;

    /**
    * <pre>
    * Trigger? ? ? Quartz Job?  
    * </pre>
    * @param context
    * @throws JobExecutionException
    * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
    */
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.debug("? (JOB)? ??.[job: {} , instance: {}, start: {}]",
                new Object[] { context.getJobDetail().getFullName(), context.getJobInstance().toString(),
                        DateFormatUtils.format(System.currentTimeMillis(), LOGGING_DATE_FORMAT) });

        initializingContext(context);

        // TODO   
        JobExecution wrapper = JobExecution.newExecution(context);

        try {
            //  
            beforeJob(wrapper);

            //  
            executeInternal(wrapper);

            //  
            afterJob(wrapper);

            wrapper.getJobStatus().complete();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("(JOB)?    ?  .[job: "
                        + context.getJobDetail().getFullName() + ", instance:" + context.getJobInstance().toString()
                        + " , interrupt: " + DateFormatUtils.format(System.currentTimeMillis(), LOGGING_DATE_FORMAT)
                        + "]", e);
            }

            wrapper.getJobStatus().fail();
            onError(wrapper, e);
            throw new JobExecutionException("Job     ?", e);
        }

        logger.debug("(JOB)? ? ? .[job: {} , instance: {}, end: {}]",
                new Object[] { context.getJobDetail().getFullName(), context.getJobInstance().toString(),
                        DateFormatUtils.format(System.currentTimeMillis(), LOGGING_DATE_FORMAT) });
    }//end of execute()

    /**
     * <pre>
     *   ? ?? {@link JobExecutionContext}?  .
     * </pre>
     * @param context
     * @throws JobExecutionException
     */
    public void initializingContext(JobExecutionContext context) throws JobExecutionException {
        try {
            this.context = (ApplicationContext) context.getScheduler().getContext().get(APPLICAITON_CONTEXT_KEY);

            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.addPropertyValues(context.getScheduler().getContext());
            pvs.addPropertyValues(context.getMergedJobDataMap());

            resolveDependenciesOfJobObject(context, pvs);

            bw.setPropertyValues(pvs, true);
        } catch (SchedulerException ex) {
            throw new JobExecutionException(ex);
        }
    }// end of initializingContext()

    /**
     * <pre>
     * {@link BaseJob}  ?? ? ? 
     * </pre>
     * @param context
     * @param pvs
     */
    @SuppressWarnings("unchecked")
    private void resolveDependenciesOfJobObject(JobExecutionContext context, MutablePropertyValues pvs) {
        for (Iterator<Entry<String, Object>> iterator = context.getMergedJobDataMap().entrySet()
                .iterator(); iterator.hasNext();) {
            Entry<String, Object> entry = (Entry<String, Object>) iterator.next();
            pvs.addPropertyValue((String) entry.getKey(), entry.getValue());
        }
    }// end of resolveDependenciesOfJobObject()

    /**
     * <pre>
     * ? ?     ??   .      ?  ?.
     * </pre>
     * @param context
     * @throws InternalJobExecutionException
     */
    protected abstract void executeInternal(JobExecution context) throws InternalJobExecutionException;

    /* (non-Javadoc)
     * @see com.athena.peacock.scheduler.quartz.JobEventListener#afterJob(com.athena.peacock.scheduler.quartz.JobExecution)
     */
    public void afterJob(JobExecution context) {
        logger.debug("{} will be terminated... [instance : {}]", this.getClass().getSimpleName(), context);
    }//end of afterJob()

    /* (non-Javadoc)
     * @see com.athena.peacock.scheduler.quartz.JobEventListener#beforeJob(com.athena.peacock.scheduler.quartz.JobExecution)
     */
    public void beforeJob(JobExecution context) {
        logger.debug("{} will be started... [instance : {}]", this.getClass().getSimpleName(), context);
    }//end of beforeJob()

    /* (non-Javadoc)
     * @see com.athena.peacock.scheduler.quartz.JobEventListener#onError(com.athena.peacock.scheduler.quartz.JobExecution, java.lang.Throwable)
     */
    public void onError(JobExecution context, Throwable t) {
        logger.error("Exception has occurred : ", t);
    }//end of onError()
}//end of BaseJob.java