Subversion Repositories bacoAlunos

Rev

Rev 1306 | Rev 1312 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.jobs;

import jomm.dao.impl.AbstractDao;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.JobServiceTask;
import pt.estgp.estgweb.domain.JobServiceTaskImpl;
import pt.estgp.estgweb.domain.JobServiceTaskParameter;
import pt.estgp.estgweb.services.logresults.ILogMessages;

import java.io.IOException;
import java.util.*;

/**
 * Created by jorgemachado on 02/11/15.
 *
 * Todos os serviços podem correr em BackGround através da chamada ao JobRunner
 * desde que implementem esta interface
 */

public abstract class ServiceJob implements JobHandler
{

    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_semestre_KEY = "JOB_semestre_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendIonline_KEY = "JOB_sendIonline_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendEmail_KEY = "JOB_sendEmail_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_cloneOnlyNews_KEY = "JOB_cloneOnlyNews_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_generateAllPdfs_KEY = "JOB_generateAllPdfs_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_validate_KEY = "JOB_validade_KEY";
    /*Log for service run*/

    protected final 1.5.0/docs/api/java/util/logging/Logger.html">Logger serviceLog = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(ServiceJob.class);

    /*Class regular log*/
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger("JobServiceTaskLog");

    private Map<String,JobServiceTaskParameter> parameters = new HashMap<String, JobServiceTaskParameter>();
    protected pt.estgp.estgweb.domain.JobServiceTaskImpl jobServiceTask = null; //to be used in subService in order to update log and check stopRequest

    public ServiceJob()
    {

    }

    public Collection<JobServiceTaskParameter> getParameters() { return parameters.values(); }
    public Map<String,JobServiceTaskParameter> getParametersMap() { return parameters;}
    public JobServiceTask getJobServiceTask() { return jobServiceTask; }

    public void setParameters(Set<JobServiceTaskParameter> parameters)
    {
        this.parameters.clear();
        for(JobServiceTaskParameter param: parameters)
        {
            this.parameters.put(param.getName(),param);
        }
    }

    /**
     * Inicialisation
     * @param jobServiceTask
     */

    public void setJobServiceTask(JobServiceTaskImpl jobServiceTask) {
        this.jobServiceTask = jobServiceTask;
        jobServiceTask.setProgress(0);
        //Service Log initialization
        logger.info("Defining service log " + jobServiceTask.getLogFilePath());
        serviceLog.removeAllAppenders();
        serviceLog.setLevel(org.apache.log4j.1.5.0/docs/api/java/util/logging/Level.html">Level.INFO);
        1.5.0/docs/api/java/lang/String.html">String logPath = Globals.JOB_SERVICES_LOG_DIR + java.io.1.5.0/docs/api/java/io/File.html">File.separator + jobServiceTask.getLogFilePath();
        java.io.1.5.0/docs/api/java/io/File.html">File dirs = new java.io.1.5.0/docs/api/java/io/File.html">File(logPath).getParentFile();
        if(!dirs.exists())
            dirs.mkdirs();

        try {
            serviceLog.addAppender(new FileAppender(new PatternLayout("%d (%F:%L) %-5r %-5p [%t] %c{2} - %m%n"), logPath));
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException ex) {
            logger.info("Error defining service log", ex);
        }
        serviceLog.setAdditivity(false);
        serviceLog.info("STARTING INFO serviceLog FOR SERVICE " + jobServiceTask.getLogFilePath() + " LOG at " + jobServiceTask.getLogFilePath());
    }

    /**
     * Run the job
     * This method is called from JobDaemon is synchronous
     */

    public void runJob()
    {
        if(jobServiceTask == null)
            throw new 1.5.0/docs/api/java/lang/RuntimeException.html">RuntimeException("This Service as not been initialized to run as JobService");

        serviceLog.info("STARTING SERVICE");
        serviceLog.info("CLASS: " + jobServiceTask.getTargetService());
        if(jobServiceTask.getCreatedBy() != null)
            serviceLog.info("CREATED BY: " + jobServiceTask.getCreatedBy().getUsername() + " - " + jobServiceTask.getCreatedBy().getName());
        else
            serviceLog.info("CREATED BY: unknown");
        for(JobServiceTaskParameter parameter: parameters.values())
        {
            serviceLog.info("PARAMETER: " + parameter.getName() + " : " + parameter.getObject().toString());
        }
        logger.info("Starting job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
        jobServiceTask.setProgress(0);
        jobServiceTask.setThreadId(new 1.5.0/docs/api/java/lang/Integer.html">Integer("" + 1.5.0/docs/api/java/lang/Thread.html">Thread.currentThread().getId()));
        jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.STARTED);
        jobServiceTask.setServiceStartDate(new 5+0%2Fdocs%2Fapi+Date">Date());
        jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
        commitPartially();
        try {
            //call the implementation of service this will update serviceLog and progress
            ILogMessages messages = runJobServiceTask();
            if(messages.hasErrors())
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_ERRORS);
            else if(messages.hasWarnings())
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_WARNINGS);
            else
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED);
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
            serviceLog.info("FINISHING SERVICE");
            logger.info("Finishing job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
        } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable throwable) {
            jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FAILED);
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
            serviceLog.info("ERROR IN SERVICE", throwable);
            logger.info("Error in job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
       }
    }

    public void setProgress(int progress){ if(jobServiceTask != null) jobServiceTask.setProgress(progress);}
    public void serviceLogInfo(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.info(str);}
    public void serviceLogWarn(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.warn(str);}
    public void serviceLogError(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.error(str);}
    public void serviceLogFatal(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.fatal(str);}
    public void serviceLogInfo(1.5.0/docs/api/java/lang/String.html">String str, 1.5.0/docs/api/java/lang/Throwable.html">Throwable e){ if(jobServiceTask != null) serviceLog.info(str,e);}
    public void serviceLogWarn(1.5.0/docs/api/java/lang/String.html">String str, 1.5.0/docs/api/java/lang/Throwable.html">Throwable e){ if(jobServiceTask != null) serviceLog.warn(str,e);}
    public void serviceLogError(1.5.0/docs/api/java/lang/String.html">String str, 1.5.0/docs/api/java/lang/Throwable.html">Throwable e){ if(jobServiceTask != null) serviceLog.error(str,e);}
    public void serviceLogFatal(1.5.0/docs/api/java/lang/String.html">String str, 1.5.0/docs/api/java/lang/Throwable.html">Throwable e){ if(jobServiceTask != null) serviceLog.fatal(str,e);}

    //Implemented in SubService to run the Job
    protected abstract ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable;

    protected void commitPartially() {

        AbstractDao.getCurrentSession().getTransaction().commit();
        AbstractDao.getCurrentSession().beginTransaction();
        if(jobServiceTask != null)
            AbstractDao.getCurrentSession().update(jobServiceTask);
    }
}