Subversion Repositories bacoAlunos

Rev

Rev 1076 | Rev 1133 | 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
 
169
                            //CourseUnitSummary s = map.get(aula.getSumNumeroAula() + ":" + aula.getCodigoSumario());
170
                            //if(s == null)
171
                            //{
172
                            CourseUnitSummaryImpl s = DomainObjectFactory.createCourseUnitSummaryImpl();
173
                            s.setCourseUnit(c);
174
                                //c.getSummaries().add(s);
175
                                //DaoFactory.getCourseUnitSummaryDaoImpl().save(s);
176
                            //summaries.add();
177
                            //}
178
                            s.setCodigoSumario(""+aula.getCodigoSumario().intValue());
179
                            s.setCodigoAula(""+aula.getSumNumeroAula().intValue());
180
                            s.setNumeroAula(aula.getSumNumeroAula().intValue());
181
                            s.setDataAula(aula.getData().toGregorianCalendar().getTime());
182
                            s.setTipoAula(aula.getSumTipoAula());
183
                            s.setCodigoSalaAula("" + aula.getAulaCodigoSalaAula().intValue());
184
                            s.setAlunosPresentes(aula.getSumNumeroAlunos().intValue());
185
                            s.setTitulo(aula.getSumTitulo());
186
                            s.setDescricao(aula.getSumDescricao());
187
                            s.setcEstado(""+aula.getSumCdEstado().intValue());
188
                            s.setNumeroHoras("" + aula.getNumeroCelulas().intValue());
189
                            summaries.put(s.getJson());
190
                            courseUnitSummaries.add(s);
1081 jmachado 191
                            if(s.getNumeroAula() > 0)
192
                                summariesValid++;
995 jmachado 193
                        }
194
                        if(courseUnitSummaries.size() == 0)
195
                        {
196
                            countUnitsZeroSummaries++;
197
                            unitsZeroSummaries.add(c.getCode());
1081 jmachado 198
                            logger.info("ZERO SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
199
                            serviceLogInfo("ZERO SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
995 jmachado 200
                        }
1081 jmachado 201
                        else if(summariesValid == 0)
202
                        {
203
                            countUnitsZeroValidSummaries++;
204
                            unitsZeroSummaries.add(c.getCode());
205
                            logger.info("ZERO VALID SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
206
                            serviceLogInfo("ZERO VALID SUMARIES unit:" + c.getCode() + " course: " + c.getCourseCode());
207
                        }
995 jmachado 208
                        else
209
                        {
210
                            countUnitsOk++;
211
                        }
212
                        c.setSummariesJson(summariesJson.toString());
213
 
214
                        if(sendIONLINE)
215
                        {
216
                            1.5.0/docs/api/java/lang/String.html">String path = generatePdf(c);
217
                            sendPdfFtpIonline(c,new ArrayList<String>(),null,path,null);
218
                            FilesUtils.delete(path);
219
                        }
220
                        if(sendEMAIL)
221
                        {
222
                            sendEmail(null, courseUnitSummaries,true);
223
                        }
224
                    }
225
                    else
226
                    {
227
                        countUnitsZeroSummaries++;
228
                        unitsZeroSummaries.add(c.getCode());
229
                        logger.error("Summaries come null in unit:" + c.getCode());
230
                        serviceLogError("Summaries come null in unit:" + c.getCode());
231
                    }
232
                }
233
                catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
234
                {
235
                    unitsFailed.add(nowCode);
236
                    logger.error(e,e);
237
                    serviceLogError(e.toString(),e);
238
                }
239
            }
240
 
241
            setProgress(100);
242
            serviceLogError("Finish commiting");
243
 
244
        }
245
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
246
        {
247
            logger.error(e, e);
248
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
249
            serviceLogError(logMessages.getLastMessage(),e);
250
            throw new ServiceException(e.toString(), e);
251
        }
252
 
253
        logMessages.addMessage(new DefaultLogMessage("import.summaries.terminating", LogMessageTypeEnum.INFO));
254
        logger.info("terminating summaries import");
255
        serviceLogInfo(logMessages.getLastMessage());
256
 
257
        serviceLogInfo("#######################################");
258
        serviceLogInfo("#######################################");
259
        serviceLogInfo("UNITS PROCESSED: " + countUnits);
260
        serviceLogInfo("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
261
        serviceLogInfo("UNITS IMPORT OK: " + countUnitsOk);
262
        serviceLogInfo("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
1081 jmachado 263
        serviceLogInfo("UNITS ZERO VALID SUMARIES: " + countUnitsZeroValidSummaries);
995 jmachado 264
        serviceLogInfo("#######################################");
1025 jmachado 265
 
266
        logger.info("#######################################");
267
        logger.info("#######################################");
268
        logger.info("UNITS PROCESSED: " + countUnits);
269
        logger.info("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
270
        logger.info("UNITS IMPORT OK: " + countUnitsOk);
271
        logger.info("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
1081 jmachado 272
        logger.info("UNITS ZERO VALID SUMARIES: " + countUnitsZeroValidSummaries);
1025 jmachado 273
        logger.info("#######################################");
995 jmachado 274
        return logMessages;
275
    }
276
 
277
 
278
    public static SendEmailService sendEmailService = new SendEmailService();
279
 
280
    private void sendEmail(UserSession userSession,List<CourseUnitSummary> summaries,boolean sendEmail)
281
    {
282
        if(Globals.EMAIL_SUMMARIES && summaries.size() > 0 && sendEmail)
283
        {
284
           // for(CourseUnitSummary summary: summaries)
285
           // {
286
 
287
                List<String> emails = DaoFactory.getCourseUnitSummaryDaoImpl().getStudentsEmails(summaries.get(0).getId());
288
                if(emails == null)
289
                    logger.warn("No students emails in unit: code:" + summaries.get(0).getCourseUnit().getCode() + " " + summaries.get(0).getCourseUnit().getName());
290
                EMAILJob emailJob = new EMAILJob(sendEmailService.getSummariesEmail(emails, summaries, summaries.get(0).getCourseUnit(), LangEnum.PORTUGUESE));
291
                JobScheduleService.getInstance().scheduleNow(emailJob,"New Summary EMAIL from: " + summaries.get(0).getCourseUnit().getName() + " aula: " +summaries.get(summaries.size()-1).getNumeroAula() ,userSession);
292
           // }
293
        }
294
    }
295
 
296
 
297
 
298
 
299
 
300
 
301
    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 {
302
        5+0%2Fdocs%2Fapi+Document">Document dom = new CreateCourseUnitXML().run(c,null);
303
        org.w3c.dom.5+0%2Fdocs%2Fapi+Document">Document dd = Dom4jUtil.toW3c(dom);
304
        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";
305
        1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream out = new 1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream(path);
306
        Map<String,Object> params = new HashMap<String,Object>();
307
        params.put("site", Globals.SITE_URL);
308
        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);
309
        out.flush();
310
        out.close();
311
        return path;
312
    }
313
 
1006 jmachado 314
    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 315
 
316
        FtpServer server = null;
317
        if(client == null)
318
        {
319
            server = FtpServer.getNewServer(Globals.FTP_IONLINE_URL,Globals.FTP_IONLINE_USER,Globals.FTP_IONLINE_PASS);
320
            client = server.getClient();
1005 jmachado 321
            if(client == null)
322
            {
323
                logger.warn("###################");
1009 jmachado 324
                logger.warn("################### > CANT CONNECT FTP - could be FTPTimeout: " + Globals.FTP_TIMEOUT_SECONDS);
325
                errors.add("################### > CANT CONNECT FTP to send summaries " + ((CourseUnitImpl)cu).getSummariosPathIntranet());
1005 jmachado 326
                return;
327
            }
328
 
995 jmachado 329
        }
330
        client.setFileType(FTP.BINARY_FILE_TYPE);
331
 
332
 
333
        1.5.0/docs/api/java/lang/String.html">String pastaFichaCurricular = ((CourseUnitImpl)cu).getSummariosPathIntranet();
334
        if(!client.changeWorkingDirectory(pastaFichaCurricular))
335
        {
336
            logger.error("FTP CANT CHANGE TO PATH: " + pastaFichaCurricular);
337
        }
338
        else
339
        {
1009 jmachado 340
            if(!client.storeFile(((CourseUnitImpl)cu).getSummariosFileNameIntranet(),new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(pdfPath)))
341
            {
1010 jmachado 342
                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;
343
                logger.error(msgS);
344
                serviceLogError(msgS);
1009 jmachado 345
            }
995 jmachado 346
            if(server != null)
347
            {
348
                client.quit();
349
                client.disconnect();
350
            }
351
        }
352
        //
353
    }
354
    /**
355
     * Testar por aqui poi requer Super Role e assim e' autmatico
356
     *
357
     *
358
     * @param args of main
359
     * @throws pt.estgp.estgweb.services.expceptions.ServiceException on error
360
     */
361
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException, JSONException {
362
 
997 jmachado 363
        1.5.0/docs/api/java/lang/System.html">System.out.println("Syntax:");
364
        1.5.0/docs/api/java/lang/System.html">System.out.println("year, semestre, sendIonline, sendEmail");
365
        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");
366
 
995 jmachado 367
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
368
        1.5.0/docs/api/java/lang/String.html">String semestre = null;
369
        boolean sendIonline = true;
370
        boolean sendEmail = true;
371
        if(args != null && args.length > 0)
372
            year = args[0];
997 jmachado 373
 
995 jmachado 374
        if(args != null && args.length > 1)
375
            semestre = args[1];
997 jmachado 376
 
995 jmachado 377
        if(args != null && args.length > 2)
378
            sendIonline = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[2]);
997 jmachado 379
 
995 jmachado 380
        if(args != null && args.length > 3)
381
            sendEmail = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[3]);
997 jmachado 382
 
995 jmachado 383
        AbstractDao.getCurrentSession().beginTransaction();
384
        if(semestre != null)
385
            new ImportSumariesJson().run(year,semestre,sendIonline,sendEmail);
386
        else
387
        {
388
            new ImportSumariesJson().run(year,"S1",sendIonline,sendEmail);
389
            new ImportSumariesJson().run(year,"S2",sendIonline,sendEmail);
390
            new ImportSumariesJson().run(year,"A",sendIonline,sendEmail);
391
        }
392
        AbstractDao.getCurrentSession().getTransaction().commit();
393
    }
394
 
395
 
396
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
397
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_semestre_KEY = "JOB_semestre_KEY";
398
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendIonline_KEY = "JOB_sendIonline_KEY";
399
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendEmail_KEY = "JOB_sendEmail_KEY";
400
 
401
    @1.5.0/docs/api/java/lang/Override.html">Override
1070 jmachado 402
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {
995 jmachado 403
 
1070 jmachado 404
        1.5.0/docs/api/java/lang/String.html">String importYear =  getParametersMap().get(JOB_importYear_KEY).getObject();
405
        1.5.0/docs/api/java/lang/String.html">String semestre =  getParametersMap().get(JOB_semestre_KEY).getObject();
406
        1.5.0/docs/api/java/lang/String.html">String sendIonlineStr = getParametersMap().get(JOB_sendIonline_KEY).getObject();
407
        1.5.0/docs/api/java/lang/String.html">String sendEmailStr =  getParametersMap().get(JOB_sendEmail_KEY).getObject();
408
        boolean sendIonline = sendIonlineStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendIonlineStr);
409
        boolean sendEmail = sendEmailStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendEmailStr);
410
        return run(importYear,semestre,sendIonline,sendEmail);
995 jmachado 411
    }
412
 
413
}