Subversion Repositories bacoAlunos

Rev

Rev 1333 | Rev 1814 | 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.Level;
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";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_institution_KEY = "JOB_institution_KEY";

    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_courseList_KEY = "JOB_questionario_courseList_KEY";
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_id_KEY = "JOB_questionario_id_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("JobServiceTaskLog");

    /*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(ServiceJob.class);

    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()
    {
        1.5.0/docs/api/java/lang/String.html">String msg;
        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");

        msg = "STARTING SERVICE";
        serviceLog.info(msg);
        logger.info(msg);
        msg = "CLASS: " + jobServiceTask.getTargetService();
        serviceLog.info(msg);
        logger.info(msg);
        if(jobServiceTask.getCreatedBy() != null)
        {
            msg = "CREATED BY: " + jobServiceTask.getCreatedBy().getUsername() + " - " + jobServiceTask.getCreatedBy().getName();
            serviceLog.info(msg);
            logger.info(msg);
        }
        else
        {
            msg ="CREATED BY: unknown";
            serviceLog.info(msg);
            logger.info(msg);
        }
        for(JobServiceTaskParameter parameter: parameters.values())
        {
            msg = "PARAMETER: " + parameter.getName() + " : " + parameter.getObject().toString();
            serviceLog.info(msg);
            logger.info(msg);
        }
        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){
        1.5.0/docs/api/java/lang/System.html">System.out.println(progress+"% 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;

    /**
     * Should be override on services wich can run only once at a time
     * Should return false is schedulle over time is permited
     * If not only RunNowService will schedulle
     * @return
     */

    public boolean runOnlyOnDemand()
    {
        return false;
    }

    protected void commitPartially() {

        AbstractDao.getCurrentSession().getTransaction().commit();
        AbstractDao.getCurrentSession().beginTransaction();
        printMem(false);
        AbstractDao.getCurrentSession().clear();
        printMem(false);
        1.5.0/docs/api/java/lang/System.html">System.gc();
        printMem(true);
        if(jobServiceTask != null)
            AbstractDao.getCurrentSession().update(jobServiceTask);
    }

    private void printMem(boolean printService)
    {
        int mb = 1024*1024;

        //Getting the runtime reference from system
        1.5.0/docs/api/java/lang/Runtime.html">Runtime runtime = 1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime();


        //serviceLogInfo("##### Heap utilization statistics [MB] #####");
        logger.debug("##### Heap utilization statistics [MB] #####");

        //Print used memory
        logger.info("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);
        if(printService)
            serviceLogInfo("#####Heap Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb + "[MB]");


        //Print free memory
        //serviceLogInfo("Free Memory:" + runtime.freeMemory() / mb);
        logger.debug("Free Memory:" + runtime.freeMemory() / mb);

        //Print total available memory
        //serviceLogInfo("Total Memory:" + runtime.totalMemory() / mb);
        logger.debug("Total Memory:" + runtime.totalMemory() / mb);

        //Print Maximum available memory
        //serviceLogInfo("Max Memory:" + runtime.maxMemory() / mb);
        logger.debug("Max Memory:" + runtime.maxMemory() / mb);
    }

    public void serviceLogInfoWithLoggerSource(1.5.0/docs/api/java/lang/String.html">String message)
    {
        serviceLogInfo(message);
        logger.log(this.getClass().getCanonicalName(), 1.5.0/docs/api/java/util/logging/Level.html">Level.INFO, message, null);
    }
}