Subversion Repositories bacoAlunos

Rev

Rev 1081 | Rev 1144 | 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.sigesimports;
2
 
3
import jomm.dao.impl.AbstractDao;
4
import jomm.utils.FilesUtils;
5
import jomm.utils.PdfUtils;
6
import org.apache.commons.net.ftp.FTP;
7
import org.apache.commons.net.ftp.FTPClient;
8
import org.apache.fop.apps.FOPException;
9
import org.apache.log4j.Logger;
10
import org.dom4j.Document;
11
import org.json.JSONArray;
12
import org.json.JSONException;
13
import org.json.JSONObject;
14
import pt.estgp.estgweb.Globals;
15
import pt.estgp.estgweb.domain.*;
16
import pt.estgp.estgweb.domain.dao.DaoFactory;
17
import pt.estgp.estgweb.domain.enums.LangEnum;
18
import pt.estgp.estgweb.services.courseunits.CreateCourseUnitXML;
19
import pt.estgp.estgweb.services.email.EMAILJob;
20
import pt.estgp.estgweb.services.email.SendEmailService;
21
import pt.estgp.estgweb.services.expceptions.ServiceException;
22
import pt.estgp.estgweb.services.jobs.JobScheduleService;
23
import pt.estgp.estgweb.services.jobs.ServiceJob;
24
import pt.estgp.estgweb.services.logresults.ILogMessages;
25
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
26
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
27
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
28
import pt.estgp.estgweb.utils.Dom4jUtil;
29
import pt.estgp.estgweb.web.FtpServer;
30
import pt.ipportalegre.siges.web.services.ArrayOfAula;
31
import pt.ipportalegre.siges.web.services.Aula;
32
import pt.ipportalegre.siges.web.services.SiGesWEB;
33
import pt.utl.ist.berserk.logic.serviceManager.IService;
34
 
35
import javax.xml.namespace.QName;
36
import javax.xml.transform.TransformerException;
37
import javax.xml.transform.dom.DOMSource;
38
import java.io.File;
39
import java.io.FileInputStream;
40
import java.io.FileOutputStream;
41
import java.io.IOException;
1017 jmachado 42
import java.math.BigDecimal;
995 jmachado 43
import java.net.URL;
44
import java.util.ArrayList;
45
import java.util.HashMap;
46
import java.util.List;
47
import java.util.Map;
48
 
49
/**
50
 * @author Jorge Machado
51
 * @date 11/May/2008
52
 * @time 12:51:32
53
 * @see pt.estgp.estgweb
54
 */
55
public class ImportSumariesJson extends ServiceJob implements IService
56
{
57
 
58
    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(ImportSumariesJson.class);
59
 
1030 jmachado 60
    private static final int MAX_COMMIT = 10;
995 jmachado 61
 
62
 
63
    public ILogMessages run(1.5.0/docs/api/java/lang/String.html">String year,1.5.0/docs/api/java/lang/String.html">String semestre) throws ServiceException
64
    {
65
        return run(year,semestre,true,true);
66
    }
67
 
68
    public ILogMessages run(1.5.0/docs/api/java/lang/String.html">String year,1.5.0/docs/api/java/lang/String.html">String semestre,boolean sendIONLINE,boolean sendEMAIL) throws ServiceException
69
    {
70
        1.5.0/docs/api/java/lang/String.html">String msgS = "STARTING SUMARIES IMPORT SERVICE FOR year: " + year + " semestre: " + semestre + " sendIONLINE: " + sendIONLINE + " sendEMAIL: " + sendEMAIL;
71
        serviceLogInfo(msgS);
72
        logger.info(msgS);
73
 
74
        DefaultLogMessages logMessages = new DefaultLogMessages();
1017 jmachado 75
        logMessages.addMessage(new DefaultLogMessage("import.summaries", LogMessageTypeEnum.INFO, "instituicao " + DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode()));
995 jmachado 76
        serviceLogInfo(logMessages.getLastMessage());
77
 
78
 
79
        int countUnits = 0;
80
        int countUnitsOk = 0;
81
        int countUnitsZeroSummaries = 0;
1081 jmachado 82
        int countUnitsZeroValidSummaries = 0;
995 jmachado 83
 
84
        List<String> unitsZeroSummaries = new ArrayList<String>();
85
        List<String> unitsFailed = new ArrayList<String>();
86
        try
87
        {
88
 
89
            SiGesWEB service;
1017 jmachado 90
            1.5.0/docs/api/java/lang/String.html">String WSDL = DaoFactory.getConfigurationDaoImpl().getSigesWebServicesWsdl();
995 jmachado 91
            try
92
            {
1017 jmachado 93
                serviceLogInfo("STARTING WEB SERVICE AT " + WSDL);
94
                service = new SiGesWEB(new 1.5.0/docs/api/java/net/URL.html">URL(WSDL), new 1.5.0/docs/api/javax/xml/namespace/QName.html">QName(Globals.SIGES_WEBSERVICE_TARGET_NAMESPACE, "SiGesWEB"));
995 jmachado 95
            }
96
            catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
97
            {
98
                logMessages.addMessage(new DefaultLogMessage("import.error",e.toString(),"erro na configuracao do WEB Service", LogMessageTypeEnum.INFO));
99
                serviceLogInfo(logMessages.getLastMessage());
100
                logger.fatal(e, e);
101
                serviceLogError(e.toString(), e);
102
                return logMessages;
103
            }
104
 
105
            int i = 0;
106
            //List<Long> cUs = DaoFactory.getCourseUnitDaoImpl().loadIds(year,DatesUtils.getSemestre());
107
            List<Long> cUs = DaoFactory.getCourseUnitDaoImpl().loadIds(year,semestre);
108
            1.5.0/docs/api/java/lang/String.html">String nowCode = "";
109
            for(1.5.0/docs/api/java/lang/Long.html">Long cId: cUs)
110
            {
111
                nowCode = "BACO_ONLY_CODE" + cId;
112
                countUnits++;
113
                try
114
                {
115
                    if (i++ > MAX_COMMIT)
116
                    {
117
                        i = 0;
996 jmachado 118
                        setProgress((int) (((float)countUnits)/((float)cUs.size())*100.0f));
1076 jmachado 119
                        commitPartially();
995 jmachado 120
                    }
121
                    CourseUnit c = DaoFactory.getCourseUnitDaoImpl().load(cId);
122
                    nowCode = c.getCode();
123
                    logMessages.addMessage(new DefaultLogMessage("import.info","Importing Summaries to CourseUnit: " + c.getCode() + ": course: " + c.getCourse().getCode(),"", LogMessageTypeEnum.INFO));
124
                    logger.info("Importing Summaries to CourseUnit: " + c.getName() + " (" + c.getCode() + ") course " + c.getCourse().getName() + " (" + c.getCourse().getCode() + ")");
125
                    serviceLogInfo(logMessages.getLastMessage());
126
 
127
                    int tries = 3;
128
                    ArrayOfAula arrayOfAulas = null;
129
                    while(tries > 0)
130
                    {
131
                    //comentario de teste
132
                        try
133
                        {
1048 jmachado 134
                            arrayOfAulas = service.getSiGesWEBSoap().getAulas(new 1.5.0/docs/api/java/math/BigDecimal.html">BigDecimal(DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode()), year,c.getCode(),semestre,c.getCourse().getCode());
995 jmachado 135
                            break;
136
                        }
137
                        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
138
                        {
139
                            if(tries-- == 0)
140
                            {
141
                                logger.error("Giving up of courseUnit:" + cId + " ( " + c.getName() + " ) ",t);
142
                                serviceLogError("Giving up of courseUnit:" + cId + " ( " + c.getName() + " ) ",t);
143
                                break;
144
                            }
145
 
146
                            logger.error("WebService Fail, trying " + tries + " times sleeping a while");
147
                            serviceLogError("WebService Fail, trying " + tries + " times sleeping a while");
148
                            1.5.0/docs/api/java/lang/Thread.html">Thread.sleep(5000);
149
                        }
150
                    }
151
 
152
                    if(arrayOfAulas != null && arrayOfAulas.getAula() != null)
153
                    {
154
                        List<CourseUnitSummary> courseUnitSummaries = new ArrayList<CourseUnitSummary>();
155
 
156
                        //HashMap<String, CourseUnitSummary> map = new HashMap<String, CourseUnitSummary>();
157
                        /*if(c.getSummaries() != null && c.getSummaries().size() > 0)
158
                            for(CourseUnitSummary s: c.getSummaries())
159
                                map.put(s.getCodigoAula() + ":" + s.getCodigoSumario(),s);
160
                        else
161
                            c.setSummaries(new HashSet<CourseUnitSummary>());*/
162
                        JSONObject summariesJson = new JSONObject();
163
                        JSONArray summaries = new JSONArray();
164
                        summariesJson.put("summary",summaries);
1081 jmachado 165
                        int summariesValid = 0;
995 jmachado 166
                        for(Aula aula: arrayOfAulas.getAula())
167
                        {
168
 
1133 jmachado 169
                            if(c.getCdTurma() != null && aula.getAulaCodigoTurma()!=null
170
                                    && c.getCdTurma().trim().length() > 0
171
                                    && aula.getAulaCodigoTurma().trim().length() > 0
172
                                    && !aula.getAulaCodigoTurma().equals(c.getCdTurma()))
173
                            {
174
                                //Código de Turma diferente
175
                                1.5.0/docs/api/java/lang/System.html">System.out.println("Ignoring summary code: " + aula.getAulaCodigoTurma() + " for unit " + c.getName() + "/" + c.getCode() + " T:" + c.getCdTurma());
176
                                continue;
177
                            }
178
 
995 jmachado 179
                            //CourseUnitSummary s = map.get(aula.getSumNumeroAula() + ":" + aula.getCodigoSumario());
180
                            //if(s == null)
181
                            //{
182
                            CourseUnitSummaryImpl s = DomainObjectFactory.createCourseUnitSummaryImpl();
183
                            s.setCourseUnit(c);
184
                                //c.getSummaries().add(s);
185
                                //DaoFactory.getCourseUnitSummaryDaoImpl().save(s);
186
                            //summaries.add();
187
                            //}
188
                            s.setCodigoSumario(""+aula.getCodigoSumario().intValue());
189
                            s.setCodigoAula(""+aula.getSumNumeroAula().intValue());
190
                            s.setNumeroAula(aula.getSumNumeroAula().intValue());
191
                            s.setDataAula(aula.getData().toGregorianCalendar().getTime());
192
                            s.setTipoAula(aula.getSumTipoAula());
193
                            s.setCodigoSalaAula("" + aula.getAulaCodigoSalaAula().intValue());
194
                            s.setAlunosPresentes(aula.getSumNumeroAlunos().intValue());
195
                            s.setTitulo(aula.getSumTitulo());
196
                            s.setDescricao(aula.getSumDescricao());
197
                            s.setcEstado(""+aula.getSumCdEstado().intValue());
198
                            s.setNumeroHoras("" + aula.getNumeroCelulas().intValue());
199
                            summaries.put(s.getJson());
200
                            courseUnitSummaries.add(s);
1081 jmachado 201
                            if(s.getNumeroAula() > 0)
202
                                summariesValid++;
995 jmachado 203
                        }
204
                        if(courseUnitSummaries.size() == 0)
205
                        {
206
                            countUnitsZeroSummaries++;
207
                            unitsZeroSummaries.add(c.getCode());
1081 jmachado 208
                            logger.info("ZERO SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
209
                            serviceLogInfo("ZERO SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
995 jmachado 210
                        }
1081 jmachado 211
                        else if(summariesValid == 0)
212
                        {
213
                            countUnitsZeroValidSummaries++;
214
                            unitsZeroSummaries.add(c.getCode());
215
                            logger.info("ZERO VALID SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
216
                            serviceLogInfo("ZERO VALID SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
217
                        }
995 jmachado 218
                        else
219
                        {
220
                            countUnitsOk++;
221
                        }
222
                        c.setSummariesJson(summariesJson.toString());
223
 
224
                        if(sendIONLINE)
225
                        {
226
                            1.5.0/docs/api/java/lang/String.html">String path = generatePdf(c);
227
                            sendPdfFtpIonline(c,new ArrayList<String>(),null,path,null);
228
                            FilesUtils.delete(path);
229
                        }
230
                        if(sendEMAIL)
231
                        {
232
                            sendEmail(null, courseUnitSummaries,true);
233
                        }
234
                    }
235
                    else
236
                    {
237
                        countUnitsZeroSummaries++;
238
                        unitsZeroSummaries.add(c.getCode());
239
                        logger.error("Summaries come null in unit:" + c.getCode());
240
                        serviceLogError("Summaries come null in unit:" + c.getCode());
241
                    }
242
                }
243
                catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
244
                {
245
                    unitsFailed.add(nowCode);
246
                    logger.error(e,e);
247
                    serviceLogError(e.toString(),e);
248
                }
249
            }
250
 
251
            setProgress(100);
252
            serviceLogError("Finish commiting");
253
 
254
        }
255
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
256
        {
257
            logger.error(e, e);
258
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
259
            serviceLogError(logMessages.getLastMessage(),e);
260
            throw new ServiceException(e.toString(), e);
261
        }
262
 
263
        logMessages.addMessage(new DefaultLogMessage("import.summaries.terminating", LogMessageTypeEnum.INFO));
264
        logger.info("terminating summaries import");
265
        serviceLogInfo(logMessages.getLastMessage());
266
 
267
        serviceLogInfo("#######################################");
268
        serviceLogInfo("#######################################");
269
        serviceLogInfo("UNITS PROCESSED: " + countUnits);
270
        serviceLogInfo("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
271
        serviceLogInfo("UNITS IMPORT OK: " + countUnitsOk);
272
        serviceLogInfo("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
1081 jmachado 273
        serviceLogInfo("UNITS ZERO VALID SUMARIES: " + countUnitsZeroValidSummaries);
995 jmachado 274
        serviceLogInfo("#######################################");
1025 jmachado 275
 
276
        logger.info("#######################################");
277
        logger.info("#######################################");
278
        logger.info("UNITS PROCESSED: " + countUnits);
279
        logger.info("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
280
        logger.info("UNITS IMPORT OK: " + countUnitsOk);
281
        logger.info("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
1081 jmachado 282
        logger.info("UNITS ZERO VALID SUMARIES: " + countUnitsZeroValidSummaries);
1025 jmachado 283
        logger.info("#######################################");
995 jmachado 284
        return logMessages;
285
    }
286
 
287
 
288
    public static SendEmailService sendEmailService = new SendEmailService();
289
 
290
    private void sendEmail(UserSession userSession,List<CourseUnitSummary> summaries,boolean sendEmail)
291
    {
292
        if(Globals.EMAIL_SUMMARIES && summaries.size() > 0 && sendEmail)
293
        {
294
           // for(CourseUnitSummary summary: summaries)
295
           // {
296
 
297
                List<String> emails = DaoFactory.getCourseUnitSummaryDaoImpl().getStudentsEmails(summaries.get(0).getId());
298
                if(emails == null)
299
                    logger.warn("No students emails in unit: code:" + summaries.get(0).getCourseUnit().getCode() + " " + summaries.get(0).getCourseUnit().getName());
300
                EMAILJob emailJob = new EMAILJob(sendEmailService.getSummariesEmail(emails, summaries, summaries.get(0).getCourseUnit(), LangEnum.PORTUGUESE));
301
                JobScheduleService.getInstance().scheduleNow(emailJob,"New Summary EMAIL from: " + summaries.get(0).getCourseUnit().getName() + " aula: " +summaries.get(summaries.size()-1).getNumeroAula() ,userSession);
302
           // }
303
        }
304
    }
305
 
306
 
307
 
308
 
309
 
310
 
311
    public static 1.5.0/docs/api/java/lang/String.html">String generatePdf(CourseUnit c) throws 1.5.0/docs/api/java/io/IOException.html">IOException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, FOPException {
312
        5+0%2Fdocs%2Fapi+Document">Document dom = new CreateCourseUnitXML().run(c,null);
313
        org.w3c.dom.5+0%2Fdocs%2Fapi+Document">Document dd = Dom4jUtil.toW3c(dom);
314
        1.5.0/docs/api/java/lang/String.html">String path = Globals.TMP_DIR + 1.5.0/docs/api/java/io/File.html">File.separator + c.getCode() + "-" + c.getNormalizedName() + "-sumarios.pdf";
315
        1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream out = new 1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream(path);
316
        Map<String,Object> params = new HashMap<String,Object>();
317
        params.put("site", Globals.SITE_URL);
318
        PdfUtils.createPdfFromXml(new 1.5.0/docs/api/javax/xml/transform/dom/DOMSource.html">DOMSource(dd), "pt/estgp/estgweb/services/courseunits/courseunitsummaries.fo.xsl", out, params);
319
        out.flush();
320
        out.close();
321
        return path;
322
    }
323
 
1006 jmachado 324
    private void sendPdfFtpIonline(CourseUnit cu, List<String> errors, UserSession u,1.5.0/docs/api/java/lang/String.html">String pdfPath,FTPClient client) throws 1.5.0/docs/api/java/io/IOException.html">IOException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, FOPException {
995 jmachado 325
 
326
        FtpServer server = null;
327
        if(client == null)
328
        {
329
            server = FtpServer.getNewServer(Globals.FTP_IONLINE_URL,Globals.FTP_IONLINE_USER,Globals.FTP_IONLINE_PASS);
330
            client = server.getClient();
1005 jmachado 331
            if(client == null)
332
            {
333
                logger.warn("###################");
1009 jmachado 334
                logger.warn("################### > CANT CONNECT FTP - could be FTPTimeout: " + Globals.FTP_TIMEOUT_SECONDS);
335
                errors.add("################### > CANT CONNECT FTP to send summaries " + ((CourseUnitImpl)cu).getSummariosPathIntranet());
1005 jmachado 336
                return;
337
            }
338
 
995 jmachado 339
        }
340
        client.setFileType(FTP.BINARY_FILE_TYPE);
341
 
342
 
343
        1.5.0/docs/api/java/lang/String.html">String pastaFichaCurricular = ((CourseUnitImpl)cu).getSummariosPathIntranet();
344
        if(!client.changeWorkingDirectory(pastaFichaCurricular))
345
        {
346
            logger.error("FTP CANT CHANGE TO PATH: " + pastaFichaCurricular);
347
        }
348
        else
349
        {
1009 jmachado 350
            if(!client.storeFile(((CourseUnitImpl)cu).getSummariosFileNameIntranet(),new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(pdfPath)))
351
            {
1010 jmachado 352
                1.5.0/docs/api/java/lang/String.html">String msgS = "CANT store file in given time, probably timeout at " + Globals.FTP_DATA_STORE_TIMEOUT_SECONDS;
353
                logger.error(msgS);
354
                serviceLogError(msgS);
1009 jmachado 355
            }
995 jmachado 356
            if(server != null)
357
            {
358
                client.quit();
359
                client.disconnect();
360
            }
361
        }
362
        //
363
    }
364
    /**
365
     * Testar por aqui poi requer Super Role e assim e' autmatico
366
     *
367
     *
368
     * @param args of main
369
     * @throws pt.estgp.estgweb.services.expceptions.ServiceException on error
370
     */
371
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException, JSONException {
372
 
997 jmachado 373
        1.5.0/docs/api/java/lang/System.html">System.out.println("Syntax:");
374
        1.5.0/docs/api/java/lang/System.html">System.out.println("year, semestre, sendIonline, sendEmail");
375
        1.5.0/docs/api/java/lang/System.html">System.out.println("If no arguments wil user actual year import config in all semestres and true in email and ionline");
376
 
995 jmachado 377
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
378
        1.5.0/docs/api/java/lang/String.html">String semestre = null;
1133 jmachado 379
        boolean sendIonline = false;
380
        boolean sendEmail = false;
995 jmachado 381
        if(args != null && args.length > 0)
382
            year = args[0];
997 jmachado 383
 
995 jmachado 384
        if(args != null && args.length > 1)
385
            semestre = args[1];
997 jmachado 386
 
995 jmachado 387
        if(args != null && args.length > 2)
388
            sendIonline = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[2]);
997 jmachado 389
 
995 jmachado 390
        if(args != null && args.length > 3)
391
            sendEmail = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[3]);
997 jmachado 392
 
995 jmachado 393
        AbstractDao.getCurrentSession().beginTransaction();
394
        if(semestre != null)
395
            new ImportSumariesJson().run(year,semestre,sendIonline,sendEmail);
396
        else
397
        {
398
            new ImportSumariesJson().run(year,"S1",sendIonline,sendEmail);
399
            new ImportSumariesJson().run(year,"S2",sendIonline,sendEmail);
400
            new ImportSumariesJson().run(year,"A",sendIonline,sendEmail);
401
        }
402
        AbstractDao.getCurrentSession().getTransaction().commit();
403
    }
404
 
405
 
406
    @1.5.0/docs/api/java/lang/Override.html">Override
1070 jmachado 407
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {
995 jmachado 408
 
1070 jmachado 409
        1.5.0/docs/api/java/lang/String.html">String importYear =  getParametersMap().get(JOB_importYear_KEY).getObject();
410
        1.5.0/docs/api/java/lang/String.html">String semestre =  getParametersMap().get(JOB_semestre_KEY).getObject();
411
        1.5.0/docs/api/java/lang/String.html">String sendIonlineStr = getParametersMap().get(JOB_sendIonline_KEY).getObject();
412
        1.5.0/docs/api/java/lang/String.html">String sendEmailStr =  getParametersMap().get(JOB_sendEmail_KEY).getObject();
413
        boolean sendIonline = sendIonlineStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendIonlineStr);
414
        boolean sendEmail = sendEmailStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendEmailStr);
415
        return run(importYear,semestre,sendIonline,sendEmail);
995 jmachado 416
    }
417
 
418
}