Subversion Repositories bacoAlunos

Rev

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

Rev Author Line No. Line
995 jmachado 1
package pt.estgp.estgweb.services.jobs;
2
 
1076 jmachado 3
import jomm.dao.impl.AbstractDao;
995 jmachado 4
import org.apache.log4j.FileAppender;
5
import org.apache.log4j.Logger;
6
import org.apache.log4j.PatternLayout;
7
import pt.estgp.estgweb.Globals;
8
import pt.estgp.estgweb.domain.JobServiceTask;
9
import pt.estgp.estgweb.domain.JobServiceTaskImpl;
10
import pt.estgp.estgweb.domain.JobServiceTaskParameter;
1070 jmachado 11
import pt.estgp.estgweb.services.logresults.ILogMessages;
995 jmachado 12
 
13
import java.io.IOException;
14
import java.util.*;
15
 
16
/**
17
 * Created by jorgemachado on 02/11/15.
18
 *
19
 * Todos os serviços podem correr em BackGround através da chamada ao JobRunner
20
 * desde que implementem esta interface
21
 */
22
public abstract class ServiceJob implements JobHandler
23
{
24
 
1133 jmachado 25
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
26
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_semestre_KEY = "JOB_semestre_KEY";
27
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendIonline_KEY = "JOB_sendIonline_KEY";
28
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendEmail_KEY = "JOB_sendEmail_KEY";
29
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_cloneOnlyNews_KEY = "JOB_cloneOnlyNews_KEY";
30
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_generateAllPdfs_KEY = "JOB_generateAllPdfs_KEY";
31
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_validate_KEY = "JOB_validade_KEY";
995 jmachado 32
    /*Log for service run*/
1133 jmachado 33
 
995 jmachado 34
    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);
35
 
36
    /*Class regular log*/
37
    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");
38
 
39
    private Map<String,JobServiceTaskParameter> parameters = new HashMap<String, JobServiceTaskParameter>();
40
    protected pt.estgp.estgweb.domain.JobServiceTaskImpl jobServiceTask = null; //to be used in subService in order to update log and check stopRequest
41
 
42
    public ServiceJob()
43
    {
44
 
45
    }
46
 
47
    public Collection<JobServiceTaskParameter> getParameters() { return parameters.values(); }
48
    public Map<String,JobServiceTaskParameter> getParametersMap() { return parameters;}
49
    public JobServiceTask getJobServiceTask() { return jobServiceTask; }
50
 
51
    public void setParameters(Set<JobServiceTaskParameter> parameters)
52
    {
53
        this.parameters.clear();
54
        for(JobServiceTaskParameter param: parameters)
55
        {
56
            this.parameters.put(param.getName(),param);
57
        }
58
    }
59
 
60
    /**
61
     * Inicialisation
62
     * @param jobServiceTask
63
     */
64
    public void setJobServiceTask(JobServiceTaskImpl jobServiceTask) {
65
        this.jobServiceTask = jobServiceTask;
66
        jobServiceTask.setProgress(0);
67
        //Service Log initialization
68
        logger.info("Defining service log " + jobServiceTask.getLogFilePath());
69
        serviceLog.removeAllAppenders();
70
        serviceLog.setLevel(org.apache.log4j.1.5.0/docs/api/java/util/logging/Level.html">Level.INFO);
71
        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();
72
        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();
73
        if(!dirs.exists())
74
            dirs.mkdirs();
75
 
76
        try {
77
            serviceLog.addAppender(new FileAppender(new PatternLayout("%d (%F:%L) %-5r %-5p [%t] %c{2} - %m%n"), logPath));
78
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException ex) {
79
            logger.info("Error defining service log", ex);
80
        }
81
        serviceLog.setAdditivity(false);
82
        serviceLog.info("STARTING INFO serviceLog FOR SERVICE " + jobServiceTask.getLogFilePath() + " LOG at " + jobServiceTask.getLogFilePath());
83
    }
84
 
85
    /**
86
     * Run the job
87
     * This method is called from JobDaemon is synchronous
88
     */
89
    public void runJob()
90
    {
91
        if(jobServiceTask == null)
92
            throw new 1.5.0/docs/api/java/lang/RuntimeException.html">RuntimeException("This Service as not been initialized to run as JobService");
93
 
94
        serviceLog.info("STARTING SERVICE");
95
        serviceLog.info("CLASS: " + jobServiceTask.getTargetService());
96
        if(jobServiceTask.getCreatedBy() != null)
97
            serviceLog.info("CREATED BY: " + jobServiceTask.getCreatedBy().getUsername() + " - " + jobServiceTask.getCreatedBy().getName());
98
        else
99
            serviceLog.info("CREATED BY: unknown");
100
        for(JobServiceTaskParameter parameter: parameters.values())
101
        {
102
            serviceLog.info("PARAMETER: " + parameter.getName() + " : " + parameter.getObject().toString());
103
        }
104
        logger.info("Starting job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
105
        jobServiceTask.setProgress(0);
106
        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()));
107
        jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.STARTED);
108
        jobServiceTask.setServiceStartDate(new 5+0%2Fdocs%2Fapi+Date">Date());
109
        jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
1076 jmachado 110
        commitPartially();
995 jmachado 111
        try {
112
            //call the implementation of service this will update serviceLog and progress
1070 jmachado 113
            ILogMessages messages = runJobServiceTask();
114
            if(messages.hasErrors())
115
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_ERRORS);
116
            else if(messages.hasWarnings())
117
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_WARNINGS);
118
            else
119
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED);
995 jmachado 120
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
121
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
122
            serviceLog.info("FINISHING SERVICE");
123
            logger.info("Finishing job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
124
        } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable throwable) {
125
            jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FAILED);
126
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
127
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
128
            serviceLog.info("ERROR IN SERVICE", throwable);
129
            logger.info("Error in job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
130
       }
131
    }
132
 
133
    public void setProgress(int progress){ if(jobServiceTask != null) jobServiceTask.setProgress(progress);}
134
    public void serviceLogInfo(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.info(str);}
135
    public void serviceLogWarn(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.warn(str);}
136
    public void serviceLogError(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.error(str);}
137
    public void serviceLogFatal(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.fatal(str);}
138
    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);}
139
    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);}
140
    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);}
141
    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);}
142
 
143
    //Implemented in SubService to run the Job
1070 jmachado 144
    protected abstract ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable;
1076 jmachado 145
 
146
    protected void commitPartially() {
1119 jmachado 147
 
1076 jmachado 148
        AbstractDao.getCurrentSession().getTransaction().commit();
149
        AbstractDao.getCurrentSession().beginTransaction();
1119 jmachado 150
        if(jobServiceTask != null)
151
            AbstractDao.getCurrentSession().update(jobServiceTask);
1076 jmachado 152
    }
995 jmachado 153
}