Subversion Repositories bacoAlunos

Rev

Rev 1070 | Rev 1081 | 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;
82
 
83
        List<String> unitsZeroSummaries = new ArrayList<String>();
84
        List<String> unitsFailed = new ArrayList<String>();
85
        try
86
        {
87
 
88
            SiGesWEB service;
1017 jmachado 89
            1.5.0/docs/api/java/lang/String.html">String WSDL = DaoFactory.getConfigurationDaoImpl().getSigesWebServicesWsdl();
995 jmachado 90
            try
91
            {
1017 jmachado 92
                serviceLogInfo("STARTING WEB SERVICE AT " + WSDL);
93
                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 94
            }
95
            catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
96
            {
97
                logMessages.addMessage(new DefaultLogMessage("import.error",e.toString(),"erro na configuracao do WEB Service", LogMessageTypeEnum.INFO));
98
                serviceLogInfo(logMessages.getLastMessage());
99
                logger.fatal(e, e);
100
                serviceLogError(e.toString(), e);
101
                return logMessages;
102
            }
103
 
104
            int i = 0;
105
            //List<Long> cUs = DaoFactory.getCourseUnitDaoImpl().loadIds(year,DatesUtils.getSemestre());
106
            List<Long> cUs = DaoFactory.getCourseUnitDaoImpl().loadIds(year,semestre);
107
            1.5.0/docs/api/java/lang/String.html">String nowCode = "";
108
            for(1.5.0/docs/api/java/lang/Long.html">Long cId: cUs)
109
            {
110
                nowCode = "BACO_ONLY_CODE" + cId;
111
                countUnits++;
112
                try
113
                {
114
                    if (i++ > MAX_COMMIT)
115
                    {
116
                        i = 0;
996 jmachado 117
                        setProgress((int) (((float)countUnits)/((float)cUs.size())*100.0f));
1076 jmachado 118
                        commitPartially();
995 jmachado 119
                    }
120
                    CourseUnit c = DaoFactory.getCourseUnitDaoImpl().load(cId);
121
                    nowCode = c.getCode();
122
                    logMessages.addMessage(new DefaultLogMessage("import.info","Importing Summaries to CourseUnit: " + c.getCode() + ": course: " + c.getCourse().getCode(),"", LogMessageTypeEnum.INFO));
123
                    logger.info("Importing Summaries to CourseUnit: " + c.getName() + " (" + c.getCode() + ") course " + c.getCourse().getName() + " (" + c.getCourse().getCode() + ")");
124
                    serviceLogInfo(logMessages.getLastMessage());
125
 
126
                    int tries = 3;
127
                    ArrayOfAula arrayOfAulas = null;
128
                    while(tries > 0)
129
                    {
130
                    //comentario de teste
131
                        try
132
                        {
1048 jmachado 133
                            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 134
                            break;
135
                        }
136
                        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
137
                        {
138
                            if(tries-- == 0)
139
                            {
140
                                logger.error("Giving up of courseUnit:" + cId + " ( " + c.getName() + " ) ",t);
141
                                serviceLogError("Giving up of courseUnit:" + cId + " ( " + c.getName() + " ) ",t);
142
                                break;
143
                            }
144
 
145
                            logger.error("WebService Fail, trying " + tries + " times sleeping a while");
146
                            serviceLogError("WebService Fail, trying " + tries + " times sleeping a while");
147
                            1.5.0/docs/api/java/lang/Thread.html">Thread.sleep(5000);
148
                        }
149
                    }
150
 
151
                    if(arrayOfAulas != null && arrayOfAulas.getAula() != null)
152
                    {
153
                        List<CourseUnitSummary> courseUnitSummaries = new ArrayList<CourseUnitSummary>();
154
 
155
                        //HashMap<String, CourseUnitSummary> map = new HashMap<String, CourseUnitSummary>();
156
                        /*if(c.getSummaries() != null && c.getSummaries().size() > 0)
157
                            for(CourseUnitSummary s: c.getSummaries())
158
                                map.put(s.getCodigoAula() + ":" + s.getCodigoSumario(),s);
159
                        else
160
                            c.setSummaries(new HashSet<CourseUnitSummary>());*/
161
                        JSONObject summariesJson = new JSONObject();
162
                        JSONArray summaries = new JSONArray();
163
                        summariesJson.put("summary",summaries);
164
                        for(Aula aula: arrayOfAulas.getAula())
165
                        {
166
 
167
                            //CourseUnitSummary s = map.get(aula.getSumNumeroAula() + ":" + aula.getCodigoSumario());
168
                            //if(s == null)
169
                            //{
170
                            CourseUnitSummaryImpl s = DomainObjectFactory.createCourseUnitSummaryImpl();
171
                            s.setCourseUnit(c);
172
                                //c.getSummaries().add(s);
173
                                //DaoFactory.getCourseUnitSummaryDaoImpl().save(s);
174
                            //summaries.add();
175
                            //}
176
                            s.setCodigoSumario(""+aula.getCodigoSumario().intValue());
177
                            s.setCodigoAula(""+aula.getSumNumeroAula().intValue());
178
                            s.setNumeroAula(aula.getSumNumeroAula().intValue());
179
                            s.setDataAula(aula.getData().toGregorianCalendar().getTime());
180
                            s.setTipoAula(aula.getSumTipoAula());
181
                            s.setCodigoSalaAula("" + aula.getAulaCodigoSalaAula().intValue());
182
                            s.setAlunosPresentes(aula.getSumNumeroAlunos().intValue());
183
                            s.setTitulo(aula.getSumTitulo());
184
                            s.setDescricao(aula.getSumDescricao());
185
                            s.setcEstado(""+aula.getSumCdEstado().intValue());
186
                            s.setNumeroHoras("" + aula.getNumeroCelulas().intValue());
187
                            summaries.put(s.getJson());
188
                            courseUnitSummaries.add(s);
189
                        }
190
                        if(courseUnitSummaries.size() == 0)
191
                        {
192
                            countUnitsZeroSummaries++;
193
                            unitsZeroSummaries.add(c.getCode());
194
                        }
195
                        else
196
                        {
197
                            countUnitsOk++;
198
                        }
199
                        c.setSummariesJson(summariesJson.toString());
200
 
201
                        if(sendIONLINE)
202
                        {
203
                            1.5.0/docs/api/java/lang/String.html">String path = generatePdf(c);
204
                            sendPdfFtpIonline(c,new ArrayList<String>(),null,path,null);
205
                            FilesUtils.delete(path);
206
                        }
207
                        if(sendEMAIL)
208
                        {
209
                            sendEmail(null, courseUnitSummaries,true);
210
                        }
211
                    }
212
                    else
213
                    {
214
                        countUnitsZeroSummaries++;
215
                        unitsZeroSummaries.add(c.getCode());
216
                        logger.error("Summaries come null in unit:" + c.getCode());
217
                        serviceLogError("Summaries come null in unit:" + c.getCode());
218
                    }
219
                }
220
                catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
221
                {
222
                    unitsFailed.add(nowCode);
223
                    logger.error(e,e);
224
                    serviceLogError(e.toString(),e);
225
                }
226
            }
227
 
228
            setProgress(100);
229
            serviceLogError("Finish commiting");
230
 
231
        }
232
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
233
        {
234
            logger.error(e, e);
235
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
236
            serviceLogError(logMessages.getLastMessage(),e);
237
            throw new ServiceException(e.toString(), e);
238
        }
239
 
240
        logMessages.addMessage(new DefaultLogMessage("import.summaries.terminating", LogMessageTypeEnum.INFO));
241
        logger.info("terminating summaries import");
242
        serviceLogInfo(logMessages.getLastMessage());
243
 
244
        serviceLogInfo("#######################################");
245
        serviceLogInfo("#######################################");
246
        serviceLogInfo("UNITS PROCESSED: " + countUnits);
247
        serviceLogInfo("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
248
        serviceLogInfo("UNITS IMPORT OK: " + countUnitsOk);
249
        serviceLogInfo("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
250
        serviceLogInfo("#######################################");
1025 jmachado 251
 
252
        logger.info("#######################################");
253
        logger.info("#######################################");
254
        logger.info("UNITS PROCESSED: " + countUnits);
255
        logger.info("UNITS FAILED: " + (countUnits - countUnitsZeroSummaries - countUnitsOk));
256
        logger.info("UNITS IMPORT OK: " + countUnitsOk);
257
        logger.info("UNITS ZERO SUMARIES: " + countUnitsZeroSummaries);
258
        logger.info("#######################################");
995 jmachado 259
        return logMessages;
260
    }
261
 
262
 
263
    public static SendEmailService sendEmailService = new SendEmailService();
264
 
265
    private void sendEmail(UserSession userSession,List<CourseUnitSummary> summaries,boolean sendEmail)
266
    {
267
        if(Globals.EMAIL_SUMMARIES && summaries.size() > 0 && sendEmail)
268
        {
269
           // for(CourseUnitSummary summary: summaries)
270
           // {
271
 
272
                List<String> emails = DaoFactory.getCourseUnitSummaryDaoImpl().getStudentsEmails(summaries.get(0).getId());
273
                if(emails == null)
274
                    logger.warn("No students emails in unit: code:" + summaries.get(0).getCourseUnit().getCode() + " " + summaries.get(0).getCourseUnit().getName());
275
                EMAILJob emailJob = new EMAILJob(sendEmailService.getSummariesEmail(emails, summaries, summaries.get(0).getCourseUnit(), LangEnum.PORTUGUESE));
276
                JobScheduleService.getInstance().scheduleNow(emailJob,"New Summary EMAIL from: " + summaries.get(0).getCourseUnit().getName() + " aula: " +summaries.get(summaries.size()-1).getNumeroAula() ,userSession);
277
           // }
278
        }
279
    }
280
 
281
 
282
 
283
 
284
 
285
 
286
    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 {
287
        5+0%2Fdocs%2Fapi+Document">Document dom = new CreateCourseUnitXML().run(c,null);
288
        org.w3c.dom.5+0%2Fdocs%2Fapi+Document">Document dd = Dom4jUtil.toW3c(dom);
289
        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";
290
        1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream out = new 1.5.0/docs/api/java/io/FileOutputStream.html">FileOutputStream(path);
291
        Map<String,Object> params = new HashMap<String,Object>();
292
        params.put("site", Globals.SITE_URL);
293
        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);
294
        out.flush();
295
        out.close();
296
        return path;
297
    }
298
 
1006 jmachado 299
    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 300
 
301
        FtpServer server = null;
302
        if(client == null)
303
        {
304
            server = FtpServer.getNewServer(Globals.FTP_IONLINE_URL,Globals.FTP_IONLINE_USER,Globals.FTP_IONLINE_PASS);
305
            client = server.getClient();
1005 jmachado 306
            if(client == null)
307
            {
308
                logger.warn("###################");
1009 jmachado 309
                logger.warn("################### > CANT CONNECT FTP - could be FTPTimeout: " + Globals.FTP_TIMEOUT_SECONDS);
310
                errors.add("################### > CANT CONNECT FTP to send summaries " + ((CourseUnitImpl)cu).getSummariosPathIntranet());
1005 jmachado 311
                return;
312
            }
313
 
995 jmachado 314
        }
315
        client.setFileType(FTP.BINARY_FILE_TYPE);
316
 
317
 
318
        1.5.0/docs/api/java/lang/String.html">String pastaFichaCurricular = ((CourseUnitImpl)cu).getSummariosPathIntranet();
319
        if(!client.changeWorkingDirectory(pastaFichaCurricular))
320
        {
321
            logger.error("FTP CANT CHANGE TO PATH: " + pastaFichaCurricular);
322
        }
323
        else
324
        {
1009 jmachado 325
            if(!client.storeFile(((CourseUnitImpl)cu).getSummariosFileNameIntranet(),new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(pdfPath)))
326
            {
1010 jmachado 327
                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;
328
                logger.error(msgS);
329
                serviceLogError(msgS);
1009 jmachado 330
            }
995 jmachado 331
            if(server != null)
332
            {
333
                client.quit();
334
                client.disconnect();
335
            }
336
        }
337
        //
338
    }
339
    /**
340
     * Testar por aqui poi requer Super Role e assim e' autmatico
341
     *
342
     *
343
     * @param args of main
344
     * @throws pt.estgp.estgweb.services.expceptions.ServiceException on error
345
     */
346
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException, JSONException {
347
 
997 jmachado 348
        1.5.0/docs/api/java/lang/System.html">System.out.println("Syntax:");
349
        1.5.0/docs/api/java/lang/System.html">System.out.println("year, semestre, sendIonline, sendEmail");
350
        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");
351
 
995 jmachado 352
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
353
        1.5.0/docs/api/java/lang/String.html">String semestre = null;
354
        boolean sendIonline = true;
355
        boolean sendEmail = true;
356
        if(args != null && args.length > 0)
357
            year = args[0];
997 jmachado 358
 
995 jmachado 359
        if(args != null && args.length > 1)
360
            semestre = args[1];
997 jmachado 361
 
995 jmachado 362
        if(args != null && args.length > 2)
363
            sendIonline = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[2]);
997 jmachado 364
 
995 jmachado 365
        if(args != null && args.length > 3)
366
            sendEmail = 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(args[3]);
997 jmachado 367
 
995 jmachado 368
        AbstractDao.getCurrentSession().beginTransaction();
369
        if(semestre != null)
370
            new ImportSumariesJson().run(year,semestre,sendIonline,sendEmail);
371
        else
372
        {
373
            new ImportSumariesJson().run(year,"S1",sendIonline,sendEmail);
374
            new ImportSumariesJson().run(year,"S2",sendIonline,sendEmail);
375
            new ImportSumariesJson().run(year,"A",sendIonline,sendEmail);
376
        }
377
        AbstractDao.getCurrentSession().getTransaction().commit();
378
    }
379
 
380
 
381
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
382
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_semestre_KEY = "JOB_semestre_KEY";
383
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendIonline_KEY = "JOB_sendIonline_KEY";
384
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_sendEmail_KEY = "JOB_sendEmail_KEY";
385
 
386
    @1.5.0/docs/api/java/lang/Override.html">Override
1070 jmachado 387
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {
995 jmachado 388
 
1070 jmachado 389
        1.5.0/docs/api/java/lang/String.html">String importYear =  getParametersMap().get(JOB_importYear_KEY).getObject();
390
        1.5.0/docs/api/java/lang/String.html">String semestre =  getParametersMap().get(JOB_semestre_KEY).getObject();
391
        1.5.0/docs/api/java/lang/String.html">String sendIonlineStr = getParametersMap().get(JOB_sendIonline_KEY).getObject();
392
        1.5.0/docs/api/java/lang/String.html">String sendEmailStr =  getParametersMap().get(JOB_sendEmail_KEY).getObject();
393
        boolean sendIonline = sendIonlineStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendIonlineStr);
394
        boolean sendEmail = sendEmailStr != null && 1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(sendEmailStr);
395
        return run(importYear,semestre,sendIonline,sendEmail);
995 jmachado 396
    }
397
 
398
}