Subversion Repositories bacoAlunos

Rev

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