Subversion Repositories bacoAlunos

Rev

Rev 1814 | 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;
1332 jmachado 5
import org.apache.log4j.Level;
995 jmachado 6
import org.apache.log4j.Logger;
7
import org.apache.log4j.PatternLayout;
1814 jmachado 8
import pt.estgp.estgweb.utils.Globals;
995 jmachado 9
import pt.estgp.estgweb.domain.JobServiceTask;
10
import pt.estgp.estgweb.domain.JobServiceTaskImpl;
11
import pt.estgp.estgweb.domain.JobServiceTaskParameter;
1070 jmachado 12
import pt.estgp.estgweb.services.logresults.ILogMessages;
995 jmachado 13
 
14
import java.io.IOException;
15
import java.util.*;
16
 
17
/**
18
 * Created by jorgemachado on 02/11/15.
19
 *
20
 * Todos os serviços podem correr em BackGround através da chamada ao JobRunner
21
 * desde que implementem esta interface
22
 */
23
public abstract class ServiceJob implements JobHandler
24
{
25
 
1133 jmachado 26
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
27
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_semestre_KEY = "JOB_semestre_KEY";
28
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendIonline_KEY = "JOB_sendIonline_KEY";
29
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendEmail_KEY = "JOB_sendEmail_KEY";
30
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_cloneOnlyNews_KEY = "JOB_cloneOnlyNews_KEY";
31
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_generateAllPdfs_KEY = "JOB_generateAllPdfs_KEY";
32
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_validate_KEY = "JOB_validade_KEY";
1312 jmachado 33
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_institution_KEY = "JOB_institution_KEY";
1327 jmachado 34
 
35
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_courseList_KEY = "JOB_questionario_courseList_KEY";
36
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_id_KEY = "JOB_questionario_id_KEY";
1575 jmachado 37
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_report_id_KEY = "JOB_questionario_report_id_KEY";
1830 jmachado 38
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_questionario_sigesCode_KEY = "JOB_questionario_sigesCode_KEY";
1575 jmachado 39
 
995 jmachado 40
    /*Log for service run*/
1133 jmachado 41
 
1332 jmachado 42
    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");
995 jmachado 43
 
44
    /*Class regular log*/
1332 jmachado 45
    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);
995 jmachado 46
 
47
    private Map<String,JobServiceTaskParameter> parameters = new HashMap<String, JobServiceTaskParameter>();
48
    protected pt.estgp.estgweb.domain.JobServiceTaskImpl jobServiceTask = null; //to be used in subService in order to update log and check stopRequest
49
 
50
    public ServiceJob()
51
    {
52
 
53
    }
54
 
55
    public Collection<JobServiceTaskParameter> getParameters() { return parameters.values(); }
56
    public Map<String,JobServiceTaskParameter> getParametersMap() { return parameters;}
57
    public JobServiceTask getJobServiceTask() { return jobServiceTask; }
58
 
59
    public void setParameters(Set<JobServiceTaskParameter> parameters)
60
    {
61
        this.parameters.clear();
62
        for(JobServiceTaskParameter param: parameters)
63
        {
64
            this.parameters.put(param.getName(),param);
65
        }
66
    }
67
 
68
    /**
69
     * Inicialisation
70
     * @param jobServiceTask
71
     */
72
    public void setJobServiceTask(JobServiceTaskImpl jobServiceTask) {
73
        this.jobServiceTask = jobServiceTask;
74
        jobServiceTask.setProgress(0);
75
        //Service Log initialization
76
        logger.info("Defining service log " + jobServiceTask.getLogFilePath());
77
        serviceLog.removeAllAppenders();
78
        serviceLog.setLevel(org.apache.log4j.1.5.0/docs/api/java/util/logging/Level.html">Level.INFO);
79
        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();
80
        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();
81
        if(!dirs.exists())
82
            dirs.mkdirs();
83
 
84
        try {
85
            serviceLog.addAppender(new FileAppender(new PatternLayout("%d (%F:%L) %-5r %-5p [%t] %c{2} - %m%n"), logPath));
86
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException ex) {
87
            logger.info("Error defining service log", ex);
88
        }
89
        serviceLog.setAdditivity(false);
90
        serviceLog.info("STARTING INFO serviceLog FOR SERVICE " + jobServiceTask.getLogFilePath() + " LOG at " + jobServiceTask.getLogFilePath());
91
    }
92
 
93
    /**
94
     * Run the job
95
     * This method is called from JobDaemon is synchronous
96
     */
97
    public void runJob()
98
    {
1333 jmachado 99
        1.5.0/docs/api/java/lang/String.html">String msg;
995 jmachado 100
        if(jobServiceTask == null)
101
            throw new 1.5.0/docs/api/java/lang/RuntimeException.html">RuntimeException("This Service as not been initialized to run as JobService");
102
 
1333 jmachado 103
        msg = "STARTING SERVICE";
104
        serviceLog.info(msg);
105
        logger.info(msg);
106
        msg = "CLASS: " + jobServiceTask.getTargetService();
107
        serviceLog.info(msg);
108
        logger.info(msg);
995 jmachado 109
        if(jobServiceTask.getCreatedBy() != null)
1333 jmachado 110
        {
111
            msg = "CREATED BY: " + jobServiceTask.getCreatedBy().getUsername() + " - " + jobServiceTask.getCreatedBy().getName();
112
            serviceLog.info(msg);
113
            logger.info(msg);
114
        }
995 jmachado 115
        else
1333 jmachado 116
        {
117
            msg ="CREATED BY: unknown";
118
            serviceLog.info(msg);
119
            logger.info(msg);
120
        }
995 jmachado 121
        for(JobServiceTaskParameter parameter: parameters.values())
122
        {
1333 jmachado 123
            msg = "PARAMETER: " + parameter.getName() + " : " + parameter.getObject().toString();
124
            serviceLog.info(msg);
125
            logger.info(msg);
995 jmachado 126
        }
127
        logger.info("Starting job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
128
        jobServiceTask.setProgress(0);
129
        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()));
130
        jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.STARTED);
131
        jobServiceTask.setServiceStartDate(new 5+0%2Fdocs%2Fapi+Date">Date());
132
        jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
1076 jmachado 133
        commitPartially();
995 jmachado 134
        try {
135
            //call the implementation of service this will update serviceLog and progress
1070 jmachado 136
            ILogMessages messages = runJobServiceTask();
137
            if(messages.hasErrors())
138
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_ERRORS);
139
            else if(messages.hasWarnings())
140
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED_WARNINGS);
141
            else
142
                jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FINISHED);
995 jmachado 143
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
144
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
145
            serviceLog.info("FINISHING SERVICE");
146
            logger.info("Finishing job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
147
        } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable throwable) {
148
            jobServiceTask.setStatusEnum(JobServiceTaskImpl.JobStatus.FAILED);
149
            jobServiceTask.setServiceLastUpdateDate(new 5+0%2Fdocs%2Fapi+Date">Date());
150
            jobServiceTask.setServiceFinishDate(new 5+0%2Fdocs%2Fapi+Date">Date());
151
            serviceLog.info("ERROR IN SERVICE", throwable);
152
            logger.info("Error in job service " + getClass().getName() + " more info in serviceLog " + jobServiceTask.getLogFilePath());
153
       }
154
    }
155
 
1312 jmachado 156
    public void setProgress(int progress){
157
        1.5.0/docs/api/java/lang/System.html">System.out.println(progress+"% PROGRESS##############");
158
        if(jobServiceTask != null) jobServiceTask.setProgress(progress);
159
    }
995 jmachado 160
    public void serviceLogInfo(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.info(str);}
161
    public void serviceLogWarn(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.warn(str);}
162
    public void serviceLogError(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.error(str);}
163
    public void serviceLogFatal(1.5.0/docs/api/java/lang/String.html">String str){ if(jobServiceTask != null) serviceLog.fatal(str);}
164
    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);}
165
    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);}
166
    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);}
167
    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);}
168
 
169
    //Implemented in SubService to run the Job
1070 jmachado 170
    protected abstract ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable;
1076 jmachado 171
 
1312 jmachado 172
    /**
173
     * Should be override on services wich can run only once at a time
174
     * Should return false is schedulle over time is permited
175
     * If not only RunNowService will schedulle
176
     * @return
177
     */
178
    public boolean runOnlyOnDemand()
179
    {
180
        return false;
181
    }
182
 
1076 jmachado 183
    protected void commitPartially() {
1119 jmachado 184
 
1076 jmachado 185
        AbstractDao.getCurrentSession().getTransaction().commit();
186
        AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 187
        printMem(false);
188
        AbstractDao.getCurrentSession().clear();
189
        printMem(false);
190
        1.5.0/docs/api/java/lang/System.html">System.gc();
191
        printMem(true);
1119 jmachado 192
        if(jobServiceTask != null)
193
            AbstractDao.getCurrentSession().update(jobServiceTask);
1076 jmachado 194
    }
1312 jmachado 195
 
196
    private void printMem(boolean printService)
197
    {
198
        int mb = 1024*1024;
199
 
200
        //Getting the runtime reference from system
201
        1.5.0/docs/api/java/lang/Runtime.html">Runtime runtime = 1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime();
202
 
203
 
204
        //serviceLogInfo("##### Heap utilization statistics [MB] #####");
1353 jmachado 205
        logger.debug("##### Heap utilization statistics [MB] #####");
1312 jmachado 206
 
207
        //Print used memory
208
        logger.info("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);
209
        if(printService)
210
            serviceLogInfo("#####Heap Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb + "[MB]");
211
 
212
 
213
        //Print free memory
214
        //serviceLogInfo("Free Memory:" + runtime.freeMemory() / mb);
1353 jmachado 215
        logger.debug("Free Memory:" + runtime.freeMemory() / mb);
1312 jmachado 216
 
217
        //Print total available memory
218
        //serviceLogInfo("Total Memory:" + runtime.totalMemory() / mb);
1353 jmachado 219
        logger.debug("Total Memory:" + runtime.totalMemory() / mb);
1312 jmachado 220
 
221
        //Print Maximum available memory
222
        //serviceLogInfo("Max Memory:" + runtime.maxMemory() / mb);
1353 jmachado 223
        logger.debug("Max Memory:" + runtime.maxMemory() / mb);
1312 jmachado 224
    }
1332 jmachado 225
 
226
    public void serviceLogInfoWithLoggerSource(1.5.0/docs/api/java/lang/String.html">String message)
227
    {
228
        serviceLogInfo(message);
229
        logger.log(this.getClass().getCanonicalName(), 1.5.0/docs/api/java/util/logging/Level.html">Level.INFO, message, null);
230
    }
995 jmachado 231
}