Subversion Repositories bacoAlunos

Rev

Rev 1415 | Rev 1692 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
116 jmachado 1
package pt.estgp.estgweb.services.sigesimports;
2
 
333 jmachado 3
import jomm.dao.impl.AbstractDao;
4
import org.apache.log4j.Logger;
996 jmachado 5
import org.hibernate.HibernateException;
6
import org.hibernate.StaleStateException;
333 jmachado 7
import pt.estgp.estgweb.Globals;
996 jmachado 8
import pt.estgp.estgweb.domain.*;
333 jmachado 9
import pt.estgp.estgweb.domain.dao.DaoFactory;
10
import pt.estgp.estgweb.services.common.CommonServicesManager;
863 jmachado 11
import pt.estgp.estgweb.services.email.SendEmailService;
116 jmachado 12
import pt.estgp.estgweb.services.expceptions.ServiceException;
996 jmachado 13
import pt.estgp.estgweb.services.jobs.ServiceJob;
333 jmachado 14
import pt.estgp.estgweb.services.logresults.ILogMessages;
15
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
16
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
165 jmachado 17
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
1246 jmachado 18
import pt.estgp.estgweb.services.sigesimports.oracle.dao.DocenteDao;
1270 jmachado 19
import pt.estgp.estgweb.services.sigesimports.oracle.dao.connection.ConnectionManager;
1246 jmachado 20
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Disciplina;
21
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Docente;
863 jmachado 22
import pt.estgp.estgweb.utils.ConfigProperties;
23
import pt.estgp.estgweb.utils.Email;
333 jmachado 24
import pt.utl.ist.berserk.logic.serviceManager.IService;
116 jmachado 25
 
1270 jmachado 26
import java.sql.Connection;
863 jmachado 27
import java.util.*;
116 jmachado 28
 
29
/**
30
 * @author Jorge Machado
31
 * @date 11/May/2008
32
 * @time 12:51:32
33
 * @see pt.estgp.estgweb
34
 */
996 jmachado 35
public class ImportTeachersService extends ServiceJob implements IService
116 jmachado 36
{
37
 
38
    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(ImportTeachersService.class);
39
 
1076 jmachado 40
    private static final int MAX_COMMIT = 20;
996 jmachado 41
 
42
    //int studentsMerged = 0;
43
    int teachersNew = 0;
44
    int teachersZeroUnits = 0;
45
    int unitsNotFound = 0;
1226 jmachado 46
    int unitsNotFoundCourseNotFound = 0;
1244 jmachado 47
    int unitsFoundForCourseNotFoundMult = 0;
48
    int unitsFoundForCourseNotFoundSingle = 0;
49
    int unitsDuplicated = 0;
996 jmachado 50
    int unitsAddedToTeachers = 0;
51
    int unitsRemovedToTeachers = 0;
52
    int unitsLocalAddedNotRemoved = 0;
53
    int teachersFound = 0;
54
    int teachersChangeBI = 0;
55
    int unitsLocallyRemovedNotAdded = 0;
1312 jmachado 56
    int professoresDesaparecidosDoSigesNesteAno = 0;
1315 jmachado 57
    int cursosFicticios = 0;
996 jmachado 58
 
59
 
1315 jmachado 60
 
1312 jmachado 61
    public ILogMessages run(1.5.0/docs/api/java/lang/String.html">String year,int institutionCode) throws ServiceException
116 jmachado 62
    {
996 jmachado 63
 
64
        teachersNew = 0;
65
        teachersZeroUnits = 0;
66
        unitsNotFound = 0;
1226 jmachado 67
        unitsNotFoundCourseNotFound = 0;
1244 jmachado 68
        unitsFoundForCourseNotFoundMult = 0;
69
        unitsFoundForCourseNotFoundSingle = 0;
70
        unitsDuplicated = 0;
996 jmachado 71
        unitsAddedToTeachers = 0;
72
        unitsRemovedToTeachers = 0;
73
        unitsLocalAddedNotRemoved = 0;
74
        teachersFound = 0;
75
        teachersChangeBI = 0;
76
        unitsLocallyRemovedNotAdded = 0;
1315 jmachado 77
        cursosFicticios = 0;
996 jmachado 78
 
79
        1.5.0/docs/api/java/lang/String.html">String msgS = "STARTING TEACHERS IMPORT SERVICE FOR YEAR: " + year;
80
        serviceLogInfo(msgS);
81
        logger.info(msgS);
82
 
165 jmachado 83
        DefaultLogMessages logMessages = new DefaultLogMessages();
1312 jmachado 84
        logMessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.INFO, "instituicao " + institutionCode));
996 jmachado 85
 
165 jmachado 86
        try
116 jmachado 87
        {
1312 jmachado 88
            List<Integer> codigosDocentes = DocenteDao.getInstance().loadCodigosDocentes(institutionCode, year);
996 jmachado 89
 
1312 jmachado 90
            /**
1315 jmachado 91
             * Este método vai procurar processores no BACO neste ano que não vieram do SIGES
92
             * Os professores que não vieram da extração do SIGES e terão de ser consistidos
1312 jmachado 93
             * pois as suas unidades ter desaparecido todas de uma vez e vão aqui ficar penduradas
94
             * Se foram adicionadas manualmente então nao serao removidas
95
             */
96
            removerUnidadesDosDesaparecidosDoSiges(year, institutionCode, codigosDocentes);
97
 
1270 jmachado 98
            1.5.0/docs/api/java/sql/Connection.html">Connection conn = ConnectionManager.openConnection();
996 jmachado 99
            int i = 1;
1246 jmachado 100
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codigosDocentes)
165 jmachado 101
            {
996 jmachado 102
                teachersFound++;
103
                if (i++ > MAX_COMMIT)
104
                {
105
                    i = 0;
1246 jmachado 106
                    setProgress((int) (((float)teachersFound)/((float)codigosDocentes.size())*100.0f));
1312 jmachado 107
                    conn.close();
1076 jmachado 108
                    commitPartially();
1312 jmachado 109
                    conn = ConnectionManager.openConnection();
996 jmachado 110
                }
1312 jmachado 111
                logger.info("Starting import Funcionario: SIGES:" + c);
996 jmachado 112
 
1312 jmachado 113
                Docente d = DocenteDao.getInstance().load(c, institutionCode, year,conn);
996 jmachado 114
 
1312 jmachado 115
                /******Logging****/
892 jmachado 116
                logger.info("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
1253 jmachado 117
                serviceLogInfo("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
894 jmachado 118
                logger.info("SIGES IMPORTED INFO: " + docenteToString(d));
1253 jmachado 119
                serviceLogInfo("SIGES IMPORTED INFO: " + docenteToString(d));
1312 jmachado 120
                /******Logging****/
121
 
122
                Teacher t = DaoFactory.getTeacherDaoImpl().loadBySigesCode(d.getCodigoFuncionario().intValue());
123
 
223 jmachado 124
                boolean newUser = false;
165 jmachado 125
                if (t == null)
126
                {
1312 jmachado 127
                    /******Logging****/
996 jmachado 128
                    msgS = "Teacher does not exist in baco, will create SIGES:" + d.getCodigoFuncionario().intValue();
129
                    logger.info(msgS);
130
                    serviceLogInfo(msgS);
1312 jmachado 131
                    /******Logging****/
996 jmachado 132
 
165 jmachado 133
                    t = DomainObjectFactory.createTeacherImpl();
134
                    DaoFactory.getTeacherDaoImpl().save(t);
223 jmachado 135
                    newUser = true;
1226 jmachado 136
                    //teachersNew++;
165 jmachado 137
                }
892 jmachado 138
                else
139
                {
1312 jmachado 140
                    /******Logging****/
996 jmachado 141
                    msgS = "Teacher EXIST in baco with SIGES: " + d.getCodigoFuncionario().intValue();
142
                    logger.info(msgS);
143
                    //serviceLogInfo(msgS);  //NOT NEED EXCESS OF INFORMATION
1312 jmachado 144
                    /******Logging****/
892 jmachado 145
                }
1312 jmachado 146
 
147
                /******Logging****/
996 jmachado 148
                msgS = "Will persist SIGES(" + d.getCodigoFuncionario().intValue() + ")  baco (username:" + t.getUsername() + ") baco name:" + t.getName();
149
                logger.info(msgS);
150
                serviceLogInfo(msgS);
1312 jmachado 151
                /******Logging****/
152
 
332 jmachado 153
                try
154
                {
1396 jmachado 155
                    persist(d, t, newUser,year,logMessages,institutionCode);
332 jmachado 156
                }
157
                catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
158
                {
159
                    logger.error(e, e);
160
                    throw e;
161
                }
1312 jmachado 162
 
163
                newUserSystemAdvise(t, newUser);
165 jmachado 164
            }
1270 jmachado 165
            conn.close();
996 jmachado 166
 
116 jmachado 167
        }
996 jmachado 168
        catch(StaleStateException e)
169
        {
170
            AbstractDao.getCurrentSession().getTransaction().rollback();
171
            AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 172
            /******Logging****/
996 jmachado 173
            logger.error(e,e);
174
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
1000 jmachado 175
            sendNotificationAdmin("Erro de importacao de docentes",e.toString());
1312 jmachado 176
            /******Logging****/
996 jmachado 177
        }
178
        catch(HibernateException e)
179
        {
180
            AbstractDao.getCurrentSession().getTransaction().rollback();
181
            AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 182
            /******Logging****/
996 jmachado 183
            logger.error(e,e);
184
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
185
            sendNotificationAdmin("Erro de base de dados importacao de docentes, provavelmente chave errada, corrigir no MySql",e.toString());
1312 jmachado 186
            /******Logging****/
996 jmachado 187
        }
165 jmachado 188
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
189
        {
1312 jmachado 190
            /******Logging****/
165 jmachado 191
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
192
            logger.error(e, e);
1312 jmachado 193
            /******Logging****/
165 jmachado 194
            throw new ServiceException(e.toString(), e);
195
        }
996 jmachado 196
 
1024 jmachado 197
 
198
 
199
 
200
 
1312 jmachado 201
        /******Logging****/
996 jmachado 202
        serviceLogInfo("############################");
203
        serviceLogInfo("############################");
204
        serviceLogInfo("#Teachers found: " + teachersFound);
205
        serviceLogInfo("#Teachers New: " + teachersNew);
206
        serviceLogInfo("#Teachers Zero Units: " + teachersZeroUnits);
207
        serviceLogInfo("#Units not found: " + unitsNotFound);
1226 jmachado 208
        serviceLogInfo("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
1244 jmachado 209
        serviceLogInfo("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
210
        serviceLogInfo("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
211
        serviceLogInfo("#Units duplicated : " + unitsDuplicated);
996 jmachado 212
        serviceLogInfo("#Units removed to Teachers: " + unitsRemovedToTeachers);
213
        serviceLogInfo("#Units added to Teachers: " + unitsAddedToTeachers);
214
        serviceLogInfo("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
215
        serviceLogInfo("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);
1312 jmachado 216
        if(professoresDesaparecidosDoSigesNesteAno > 0)
217
        {
218
            serviceLogInfo("########!!!!!!!Professores que desapareceram do Siges neste ano e tinham cadeiras no BACO: " + professoresDesaparecidosDoSigesNesteAno);
219
        }
220
        else
221
        {
222
            serviceLogInfo("CHECK DESAPARECIDOS OK - Não existem professores desaparecidos");
223
        }
1315 jmachado 224
        if(cursosFicticios > 0)
225
        {
226
            serviceLogInfo("#######Cursos Ficticios Encontrados (SITUACAO NAO PREVISTA):" + cursosFicticios);
227
        }
996 jmachado 228
 
1025 jmachado 229
        logger.info("############################");
230
        logger.info("############################");
231
        logger.info("#Teachers found: " + teachersFound);
232
        logger.info("#Teachers New: " + teachersNew);
233
        logger.info("#Teachers Zero Units: " + teachersZeroUnits);
234
        logger.info("#Units not found: " + unitsNotFound);
1226 jmachado 235
        logger.info("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
1244 jmachado 236
        logger.info("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
237
        logger.info("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
238
        logger.info("#Units duplicated : " + unitsDuplicated);
1025 jmachado 239
        logger.info("#Units removed to Teachers: " + unitsRemovedToTeachers);
240
        logger.info("#Units added to Teachers: " + unitsAddedToTeachers);
241
        logger.info("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
242
        logger.info("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);
1312 jmachado 243
        if(professoresDesaparecidosDoSigesNesteAno > 0)
244
        {
245
            logger.info("########!!!!!!!Professores que desapareceram do Siges neste ano e tinham cadeiras no BACO: " + professoresDesaparecidosDoSigesNesteAno);
246
        }
247
        else
248
        {
249
            logger.info("CHECK DESAPARECIDOS OK - Não existem professores desaparecidos");
250
        }
1315 jmachado 251
        if(cursosFicticios > 0)
252
        {
253
            logger.info("#######Cursos Ficticios Encontrados (SITUACAO NAO PREVISTA):" + cursosFicticios);
254
        }
1025 jmachado 255
 
996 jmachado 256
        if(teachersChangeBI>0)
257
        {
258
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
259
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
260
            serviceLogInfo("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
261
            serviceLogInfo("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);
1025 jmachado 262
 
263
            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
264
            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
265
            logger.info("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
266
            logger.info("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);
996 jmachado 267
        }
268
        setProgress(100);
269
 
165 jmachado 270
        logMessages.addMessage(new DefaultLogMessage("import.teachers.terminating", LogMessageTypeEnum.INFO));
271
        logger.info("terminating teacher import");
996 jmachado 272
        serviceLogInfo("terminating teacher import");
1312 jmachado 273
        /******Logging****/
165 jmachado 274
        return logMessages;
116 jmachado 275
    }
276
 
996 jmachado 277
 
1312 jmachado 278
 
116 jmachado 279
    /**
1312 jmachado 280
     * Este métido vai consistir os alunos que não eram tratados porque não vinham do SIGES logo não constavam do
281
     * ciclo
282
     * @param year
283
     * @param institutionCode
284
     * @param codigos
285
     */
1399 jmachado 286
    private void  removerUnidadesDosDesaparecidosDoSiges(1.5.0/docs/api/java/lang/String.html">String year, int institutionCode, List<Integer> codigos) {
1312 jmachado 287
        1.5.0/docs/api/java/lang/String.html">String msgS;
288
        List<Integer> codesInBaco = DaoFactory.getTeacherDaoImpl().findAllSigesCodesYear(year,institutionCode);
289
        codesInBaco.removeAll(codigos);
290
 
291
        if(codesInBaco.size() > 0)
292
        {
293
            msgS = "Existem professores no BACO que não estao no SIGES no ano: " + year + " institution:" + institutionCode + " possiveis adicionados manualmente, confirmar";
294
            serviceLogWarn(msgS);
295
            logger.warn(msgS);
296
            msgS = "";
297
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codesInBaco)
298
            {
299
                msgS+=c + ", ";
300
            }
301
            serviceLogWarn(msgS);
302
            logger.warn(msgS);
303
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codesInBaco)
304
            {
305
                professoresDesaparecidosDoSigesNesteAno++;
306
                Teacher t = DaoFactory.getTeacherDaoImpl().loadBySigesCode(c);
307
                TeacherImpl teacherImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(t);
1396 jmachado 308
                removerUnidadesQueDesapareceramNoSiges(year, teacherImpl, new HashSet<CourseUnit>(),institutionCode);
1312 jmachado 309
                //consistirTurmasAluno(studentImpl, year, new HashMap<CourseUnit, String>());
310
            }
311
        }
312
        else
313
        {
314
            msgS = "OK check - Não existem alunos desaparecidos no SIGES ano: " + year + " institution:" + institutionCode + " possiveis adicionados manualmente, confirmar";
315
            serviceLogInfo(msgS);
316
            logger.info(msgS);
317
        }
318
    }
319
 
320
    private void newUserSystemAdvise(Teacher t, boolean newUser) {
321
        if (newUser)
322
            CommonServicesManager.getInstance().adviseNew(t);
323
        else
324
        {
325
            1.5.0/docs/api/java/lang/String.html">String password = t.getPassword();
326
            t.setPassword(null);
327
            CommonServicesManager.getInstance().adviseUpdate(t);
328
            t.setPassword(password);
329
        }
330
    }
331
 
332
 
333
    /**
996 jmachado 334
     * Envio de Notificação aos operadores do CI
335
     * @param subject
336
     * @param cause
337
     */
338
    private void sendNotificationAdmin(1.5.0/docs/api/java/lang/String.html">String subject, 1.5.0/docs/api/java/lang/String.html">String cause)
339
    {
1000 jmachado 340
 
996 jmachado 341
        List<String> emails = ConfigProperties.getListValues("admin.email");
342
        for(1.5.0/docs/api/java/lang/String.html">String email:emails)
343
        {
344
            serviceLogWarn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
345
            logger.warn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
346
        }
347
        List<String> arguments = new ArrayList<String>();
348
        arguments.add(cause.replace("\n","<br/>"));
349
        Email email = new Email(subject,emails,Globals.SYSTEM_EMAIL_BOX,"messageToAdmin_pt.txt",arguments);
1038 jmachado 350
        email.setHtml(true);
996 jmachado 351
        try {
352
            new SendEmailService().sendEmail(email);
353
        } catch (ServiceException e) {
354
            e.printStackTrace();
355
        }
1000 jmachado 356
 
996 jmachado 357
    }
358
 
359
    /**
893 jmachado 360
     * Implementação local do toString para a class Docente que foi gerada pelos web-services
361
     * @param d
362
     * @return
363
     */
364
 
365
    public 1.5.0/docs/api/java/lang/String.html">String docenteToString(Docente d)
366
    {
367
        return "Docente{" +
368
                "codigoFuncionario=" + d.getCodigoFuncionario() +
369
                ", nomeFuncionario='" + d.getNomeFuncionario() + '\'' +
370
                ", nomeFuncionarioInt='" + d.getNomeFuncionarioInt() + '\'' +
371
                ", nomeAcademico='" + d.getNomeAcademico() + '\'' +
372
                ", sexo='" + d.getSexo() + '\'' +
1246 jmachado 373
                ", dataNascimento=" + d.getData_nascimento() +
893 jmachado 374
                ", morada='" + d.getMorada() + '\'' +
375
                ", codigoPostal=" + d.getCodigoPostal() +
376
                ", subCodigoPostal=" + d.getSubCodigoPostal() +
377
                ", email='" + d.getEmail() + '\'' +
378
                ", numeroBi='" + d.getNumeroBi() + '\'' +
379
                ", usernameNetpa='" + d.getUsernameNetpa() + '\'' +
380
                ", disciplinas=" + d.getDisciplinas() +
381
                '}';
382
    }
996 jmachado 383
 
384
    private void cloneFields(Docente teacherSiges, Teacher teacher)
385
    {
386
 
387
        teacher.setName(teacherSiges.getNomeFuncionarioInt());
388
        teacher.setEmail(teacherSiges.getEmail());
389
        1.5.0/docs/api/java/lang/String.html">String msgS;
390
 
391
        if(teacherSiges.getEmail() != null && teacherSiges.getEmail().endsWith(Globals.EMAIL_LOCAL_SUFFIX))
392
        {
393
            int atIndex = teacherSiges.getEmail().indexOf("@");
394
            if (atIndex > 0)
395
            {
396
                teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
397
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
398
                logger.info(msgS);
399
                serviceLogInfo(msgS);
400
            }
401
            else
402
            {
403
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
404
                logger.info(msgS);
405
                serviceLogInfo(msgS);
406
            }
407
        }
408
        else
409
        {
410
            msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
411
            logger.info(msgS);
412
            serviceLogInfo(msgS);
413
            teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
414
        }
415
        teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
416
        teacher.setAddress(teacherSiges.getMorada());
417
        teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
418
        teacher.setBi(teacherSiges.getNumeroBi());
419
        teacher.setEmployerName(teacherSiges.getNomeFuncionario());
420
        teacher.setAcademicName(teacherSiges.getNomeAcademico());
1246 jmachado 421
        teacher.setBirthDate(teacherSiges.getData_nascimento());
996 jmachado 422
    }
1244 jmachado 423
 
424
    private static class TipologiaCourseUnitPair
425
    {
426
        CourseUnit cu;
427
        1.5.0/docs/api/java/lang/Integer.html">Integer cdTipologia;
428
        1.5.0/docs/api/java/lang/Integer.html">Integer cdFuncaoDocente;
429
    }
893 jmachado 430
    /**
116 jmachado 431
     * Nao esta testado
432
     * jm
165 jmachado 433
     *
996 jmachado 434
     * @param teacherSiges docente
435
     * @param teacher teacher
333 jmachado 436
     * @throws Exception .
116 jmachado 437
     */
1396 jmachado 438
    private void persist(Docente teacherSiges, Teacher teacher, boolean newUser, 1.5.0/docs/api/java/lang/String.html">String year,DefaultLogMessages logmessages,int institutionCode) throws 1.5.0/docs/api/java/lang/Exception.html">Exception
116 jmachado 439
    {
996 jmachado 440
        1.5.0/docs/api/java/lang/String.html">String msgS;
332 jmachado 441
        try
221 jmachado 442
        {
1312 jmachado 443
            updateTeacherFields(teacherSiges, teacher, newUser);
444
            //Desta forma as relacoes antigas sao ignoradas cria-se uma lista nova e atribui-se ao Teacher, o Hibernate faz resto e apaga as chaves estrangeiras antigas
445
            if (teacherSiges.getDisciplinas() == null ||  teacherSiges.getDisciplinas().size() == 0)
116 jmachado 446
            {
1312 jmachado 447
                /******Logging****/
448
                msgS = "ATENTION TEACHER WITH ZERO UNITS: codigoFuncionario " + teacherSiges.getCodigoFuncionario();
449
                logger.warn(msgS);
450
                serviceLogInfo(msgS);
451
                /******Logging****/
1315 jmachado 452
 
453
                TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
1396 jmachado 454
                removerUnidadesQueDesapareceramNoSiges(year, tImpl, new HashSet<CourseUnit>(),institutionCode);
996 jmachado 455
            }
1312 jmachado 456
            else
996 jmachado 457
            {
1312 jmachado 458
                //1 - PROCEDIMENTO CADEIRAS SAO CARREGADAS DO BACO DA LISTA QUE VEM DO SIGES -> units
459
                //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
460
                //3 - Sao adicionadas ao teacher as que o docente ainda nao tiver da lista units
461
                //4 - Remover da lista do teacher as unidades que não vêm do SIGES e que não foram adicionadas localmente
996 jmachado 462
 
1315 jmachado 463
                //o mapa nao esta a ser usado neste momento mas fica porque podera vir a ser necessario
464
                //o docente e' colocado nas unidades todas e as turmas ficam nas tipologias tratadas na importacao de cursos
1312 jmachado 465
                Map<CourseUnit,String> map_CourseUnit_x_Turma = new HashMap<CourseUnit, String>();
996 jmachado 466
 
1312 jmachado 467
                //PASSO 1
1315 jmachado 468
                Set<CourseUnit> unitsFromSigesPersistentInBaco = obterCadeirasBacoCorrespondentes(year,teacherSiges, teacher, logmessages,map_CourseUnit_x_Turma);
1312 jmachado 469
                //PASSO 2
1315 jmachado 470
                TeacherImpl tImpl = removerRemovidasLocalmente(teacher, unitsFromSigesPersistentInBaco);
1312 jmachado 471
                //PASSO 3
1315 jmachado 472
                adicionarCadeirasNovasAoDocente(tImpl, unitsFromSigesPersistentInBaco);
1312 jmachado 473
                //PASSO 4
1396 jmachado 474
                removerUnidadesQueDesapareceramNoSiges(year, tImpl, unitsFromSigesPersistentInBaco,institutionCode);
996 jmachado 475
 
1312 jmachado 476
            }
996 jmachado 477
 
478
 
1312 jmachado 479
        }
480
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
481
        {
482
            logger.error(e, e);
1426 jmachado 483
            List<String> emails = ConfigProperties.getListValues("admin.email");
1312 jmachado 484
            List<String> arguments = new ArrayList<String>();
485
            1.5.0/docs/api/java/lang/String.html">String cause = e.getCause() == null ? "" : e.getCause().toString();
486
            arguments.add((e.toString() + "\n" + cause).replace("\n","<br/>"));
1396 jmachado 487
            Email email = new Email("Erro de importacao de professores",emails,"baco@estgp.pt","messageToAdmin_pt.txt",arguments);
1312 jmachado 488
            new SendEmailService().sendEmail(email);
489
            throw e;
490
        }
996 jmachado 491
 
1312 jmachado 492
    }
996 jmachado 493
 
1396 jmachado 494
    private void removerUnidadesQueDesapareceramNoSiges(1.5.0/docs/api/java/lang/String.html">String year, Teacher teacher, Set<CourseUnit> units,int institutionCode)
1312 jmachado 495
    {
496
        //Remover unidades deste ano que nao vem do SIGES e que nao foram adicionadas localmente
497
        Iterator<CourseUnit> iterNowUnits = teacher.getTeachedUnits().iterator();
498
        TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
499
        while(iterNowUnits.hasNext())
500
        {
501
            CourseUnit cUNow = iterNowUnits.next();
1396 jmachado 502
            if(cUNow.getImportYear().equals(year) && cUNow.getInstitutionCode().equals(institutionCode+""))
996 jmachado 503
            {
1312 jmachado 504
                //Apenas tentamos apagar as unidades do ano corrente.
505
                //Este servico trabalha com unidades importadas do ano que e passado como argumento
506
                //Se importamos unidades desse ano, as dos outros anos nao vem na lista, logo
507
                //iriamos constatar que nenhuma estava no SIGES o que nao e verdade.
508
                //Assim so apagamos unidades do ano que estamos a importar e que nao venham
509
                //na importacao desse ano
996 jmachado 510
 
1312 jmachado 511
                boolean added = false;
512
                for(CourseUnit c: units)
892 jmachado 513
                {
1315 jmachado 514
                    if(cUNow.getId() == c.getId())
996 jmachado 515
                    {
1312 jmachado 516
                        added = true;
517
                        break;
996 jmachado 518
                    }
1312 jmachado 519
                }
520
                if(!added)
521
                {
522
 
523
                    if(!tImpl.isLocalUnit(cUNow))
524
                    {
525
                        /******Logging****/
526
                        1.5.0/docs/api/java/lang/String.html">String msg = "Removendo unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES";
527
                        serviceLogInfo(msg);
528
                        logger.info(msg);
529
                        unitsRemovedToTeachers++;
530
                        /******Logging****/
531
 
532
                        iterNowUnits.remove();
533
                    }
996 jmachado 534
                    else
535
                    {
1312 jmachado 536
                        /******Logging****/
537
                        1.5.0/docs/api/java/lang/String.html">String msg = "NAO REMOVIDA - Unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES mas foi adicionada localmente";
538
                        serviceLogInfo(msg);
539
                        logger.info(msg);
540
                        unitsLocalAddedNotRemoved++;
541
                        /******Logging****/
996 jmachado 542
                    }
892 jmachado 543
                }
1312 jmachado 544
            }
545
        }
546
    }
547
 
548
    private void adicionarCadeirasNovasAoDocente(Teacher teacher, Set<CourseUnit> units) {
549
        //3 - da lista units sao adicionadas  ao teacher as que sobraram do passo 2 e o docente ainda nao tiver
550
        if (teacher.getTeachedUnits() != null)
551
        {
552
            for (CourseUnit c : units)
553
            {
554
                boolean isIn = false;
555
                for (CourseUnit tc : teacher.getTeachedUnits())
996 jmachado 556
                {
1315 jmachado 557
                    if (tc.getId() == c.getId())
1312 jmachado 558
                    {
559
                        isIn = true;
560
                        break;
561
                    }
996 jmachado 562
                }
1312 jmachado 563
                if (!isIn)
892 jmachado 564
                {
1312 jmachado 565
 
566
                    /******Logging****/
567
                    1.5.0/docs/api/java/lang/String.html">String msg = "Adicionando unidade: " + ((CourseUnitImpl)c).getSigesUniqueIdentifiers() + " - ao teacher: " + teacher.getSigesCode() + " turma " + c.getCdTurma() + " - Associacao nova no SIGES";
568
                    serviceLogInfo(msg);
569
                    logger.info(msg);
570
                    unitsAddedToTeachers++;
571
                    /******Logging****/
572
 
573
                    teacher.getTeachedUnits().add(c);
892 jmachado 574
                }
332 jmachado 575
            }
1312 jmachado 576
        }
577
        else
578
            teacher.setTeachedUnits(units);
579
    }
996 jmachado 580
 
1315 jmachado 581
    private TeacherImpl removerRemovidasLocalmente(Teacher teacher, Set<CourseUnit> units) {
1312 jmachado 582
        //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
583
        Iterator<CourseUnit> iter = units.iterator();
1315 jmachado 584
        TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
1312 jmachado 585
        while (iter.hasNext())
586
        {
587
            CourseUnit courseUnit = iter.next();
588
            //In case of a comming proxy
589
            if (tImpl.isLocalRemovedUnit(courseUnit))
892 jmachado 590
            {
1312 jmachado 591
                /******Logging****/
592
                unitsLocallyRemovedNotAdded++;
593
                1.5.0/docs/api/java/lang/String.html">String msg = "Removendo unidade: " + ((CourseUnitImpl)courseUnit).getSigesUniqueIdentifiers() + " - do professor: " + tImpl.getSigesCode() + " - Associacao existe no SIGES mas foi removido LOCALMENTE";
594
                serviceLogInfo(msg);
595
                logger.info(msg);
596
                /******Logging****/
996 jmachado 597
 
1312 jmachado 598
                iter.remove();
892 jmachado 599
            }
1312 jmachado 600
        }
1315 jmachado 601
        return tImpl;
1312 jmachado 602
    }
996 jmachado 603
 
1315 jmachado 604
    private Set<CourseUnit> obterCadeirasBacoCorrespondentes(1.5.0/docs/api/java/lang/String.html">String year, Docente teacherSiges, Teacher teacher, DefaultLogMessages logmessages,Map<CourseUnit,String> map_CourseUnit_x_Turma) {
1312 jmachado 605
        1.5.0/docs/api/java/lang/String.html">String msgS;
606
        Set<CourseUnit> units = new HashSet<CourseUnit>();
1244 jmachado 607
 
1312 jmachado 608
        for (Disciplina disciplina : teacherSiges.getDisciplinas())
609
        {
610
            List<CourseUnit> loadedunits = new ArrayList<CourseUnit>();
611
            if(disciplina.getCodigoCurso().intValue() < 0)
612
            {
613
                //O CODIGO DE CURSO VEM A NULL E E METIDO PELO DAO A -1
614
                //PORQUE OS ACADEMICOS NAO DEFINEM CURSO NA ASSOCIAÇÃO DO DOCENTE À TURMA NA TABELA T_DOC_TURMA
615
                //ISTO ACONTECE PORQUE A TURMA E MISTA E DE VARIOS CURSOS
1315 jmachado 616
                //NESTE CASO COLOCAMOS O DOCENTE NAS cadeiras dos cursos TODOS
1235 jmachado 617
 
618
 
1315 jmachado 619
                //todo futuro turmas separadas
620
                //neste caso das turmas separadas existe uma duvida:
621
                //Vir < 0 no codigo de curso significa que alunos de varios cursos podem estar nesta unidade
622
                //isso significa que nao temos cursos --> nao saber se é separated turmas
623
                //se nao sabemos se é separated turmas nunca podemos saber como ir buscar as unidades ao BACO
624
                // neste caso vamos busca-las sem a turma a descriminar e atribuimos todas ao docente.
625
                //a hipotese no futuro é, para todas as cadaeiras que forem devolvidas
626
                //corremos uma a uma e verificamos o seu curso, se for separated turmas e a turma for igual
627
                //a da disciplina adicionamos, se não for seprated turmas adicionamos sempre
1235 jmachado 628
 
1315 jmachado 629
 
1312 jmachado 630
                List<CourseUnit> courseUnits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUniqueAllCourses("" + disciplina.getCodigo(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
631
                if(courseUnits!=null)
632
                {
633
                    loadedunits = courseUnits;
634
                }
1123 jmachado 635
 
1312 jmachado 636
                /*******Logging************************/
637
                if(loadedunits.size() > 0)
638
                {
639
                    msgS = "Unit No Course -> course = " + disciplina.getCodigoCurso().intValue() + " semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " year:" + disciplina.getCdLectivo()
640
                            + " will load of all possible courses:{ ";
641
                    for(CourseUnit cc : courseUnits)
332 jmachado 642
                    {
1312 jmachado 643
                        msgS+= cc.getCourseCode() + ",";
332 jmachado 644
                    }
1312 jmachado 645
                    msgS+=" } all added to teacher: " + teacher.getSigesCode();
646
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
647
                    if(loadedunits.size() > 1)
648
                        unitsFoundForCourseNotFoundMult++;
332 jmachado 649
                    else
1312 jmachado 650
                        unitsFoundForCourseNotFoundSingle++;
651
                    logger.warn(msgS);
652
                    serviceLogWarn(msgS);
332 jmachado 653
                }
1312 jmachado 654
                /******Logging****/
655
            }
1315 jmachado 656
            else{
1312 jmachado 657
 
1315 jmachado 658
                boolean cursoFicticio = ImportStudentsService.isCursoFicticio(disciplina.getCodigoCurso());
659
                if(cursoFicticio)
660
                {
661
                    msgS = "WARNING WARNING #### Docente com curso ficticio, nao esperamos aqui cursos ficticios: " + disciplina.getCodigoCurso();
662
                    serviceLogWarn(msgS);
663
                    logger.warn(msgS);
664
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
665
                    cursosFicticios++;
666
                    continue;
667
                }
668
 
669
                //Nao vamos usar este pormenor aqui. Caregamos todas e pronto. Os docentes ficam associados às duas unidades das duas turmas
670
                //mesmo no caso das turmas separadas. As tipologias tratam das associações às turmas para que não haja questionarios a mais
671
                //na criacao de questionarios é natural que falhe alguma coisa por haver aqui unidades a mais
672
                //por isso devera ser ai feita a verificacao destes casos
673
                boolean separateTurmas = ImportCourseService.loadCourseYearTurmasPolicy(disciplina.getCodigoCurso(), year, logmessages, this);
1415 jmachado 674
 
675
                //este procedimento requer que a turma venha do siges, neste momento nao vem
676
                //Este procedimento foi colocado por mim a 6 de Junho para que os questionarios tenham os profs certos nas disciplinas
677
                //e não em duplicado, daqui para baixo o código nunca compara com separateTurmas, o mapa apenas é acedido aqui
678
                //porque daqui para baixo uma vez carregadas as turmas persistentes do SIGES apenas o id é comparado para ver se fica ou se é removida
679
                //Vamos apenas ter de  verificar que o código de turma vem na associação do docente à turma.
680
                //NAO DA A TURMA NUNCA VEM DO SIGENS PARA NAO DUPLICAR TURMAS NO JOIN
681
                //RESOVE-SE NA ATRIBUICAO DE RESPOSTAS DOS QUESTINARIOS SO SE METE O QUE TEM SUMARIO SE O CURSO FOR DE TURMAS
682
                //SEPARADAS
683
                //if(separateTurmas)
684
                //    loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUniqueWithTurma("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo(),disciplina.getCdTurma());
685
                //else
686
                //    loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUnique("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
687
 
1312 jmachado 688
                loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUnique("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
689
                /*******Logging************************/
1315 jmachado 690
                if(loadedunits.size() > 1 && !separateTurmas)
225 jmachado 691
                {
1312 jmachado 692
                    unitsDuplicated++;
693
                    msgS = "WARNING WARNING #### UnitsDuplicated: ";
694
                    serviceLogWarn(msgS);
695
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
696
                    msgS = "WARNING WARNING ####String sigesCode, String courseCode, String semestre, String year = " + disciplina.getCodigo() + ", " + disciplina.getCodigoCurso() + ","+ disciplina.getCdDuracao() + "," +  disciplina.getCdLectivo();
697
                    serviceLogWarn(msgS);
698
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
699
                    msgS = "WARNING WARNING ####returning first one, this could be a case of units spared because of TURMAS split used in 201516: ";
700
                    serviceLogWarn(msgS);
701
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
225 jmachado 702
                }
1315 jmachado 703
                if(loadedunits.size() > 1 && separateTurmas)
704
                {
705
                    Map<String,String> turmas = new HashMap<String, String>();
706
 
707
                    for(CourseUnit c :loadedunits)
708
                    {
709
                        turmas.put(c.getCdTurma(),c.getCdTurma());
710
                    }
711
                    if(turmas.size() < loadedunits.size())
712
                    {
713
                        unitsDuplicated++;
714
                        msgS = "WARNING WARNING #### O Curso é de turmas separadas mas o docente tem unidades repetidas com a mesma turma: ";
715
                        serviceLogWarn(msgS);
716
                        logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
717
                        logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
718
                        msgS = "WARNING WARNING ####String sigesCode, String courseCode, String semestre, String year = " + disciplina.getCodigo() + ", " + disciplina.getCodigoCurso() + ","+ disciplina.getCdDuracao() + "," +  disciplina.getCdLectivo();
719
                        serviceLogWarn(msgS);
720
                    }
721
                    turmas.clear();
722
                }
1312 jmachado 723
                /*******Logging************************/
724
            }
725
 
726
 
727
            if (loadedunits.size() == 0)
728
            {
729
                /*******Logging************************/
730
                msgS = "Unit not found: semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " course:" + disciplina.getCodigoCurso() + " year:" + disciplina.getCdLectivo();
731
                unitsNotFound++;
732
                if(disciplina.getCodigoCurso()==null || disciplina.getCodigoCurso().intValue() < 0)
251 jmachado 733
                {
1312 jmachado 734
                    unitsNotFoundCourseNotFound++;
735
                    msgS += "... unit with No Course Found in SIGES";
736
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
251 jmachado 737
                }
332 jmachado 738
                else
996 jmachado 739
                {
1312 jmachado 740
                    msgS += "... probably unit with zero students not imported in CoursesImport";
996 jmachado 741
                }
1312 jmachado 742
                logger.warn(msgS);
743
                serviceLogWarn(msgS);
744
                /*******Logging************************/
251 jmachado 745
            }
1312 jmachado 746
            else
747
            {
748
                for(CourseUnit found: loadedunits)
749
                {
750
                    map_CourseUnit_x_Turma.put(found,disciplina.getCdTurma());
751
                }
752
                units.addAll(loadedunits);
753
            }
754
        }
755
        return units;
756
    }
996 jmachado 757
 
1312 jmachado 758
    private void updateTeacherFields(Docente teacherSiges, Teacher teacher, boolean newUser) {
759
        1.5.0/docs/api/java/lang/String.html">String msgS;
760
        if(newUser)
761
        {
762
            cloneFields(teacherSiges, teacher);
996 jmachado 763
 
1312 jmachado 764
            /*******Logging************************/
765
            teachersNew++;
766
            serviceLogInfo("NOVO PROFESSOR ENCONTRADO: siges:" + teacherSiges.getCodigoFuncionario() + " bi:" + teacher.getBi() + " nome:" + teacher.getName());
767
            /*******Logging************************/
116 jmachado 768
        }
1312 jmachado 769
 
770
        //CASO EM QUE O DOCENTE NO SIGES FOI ATRIBUIDO A OUTRO ESTUDANTE PARA PREENCHER BURACO NA NUMERACAO
771
        else if(teacherSiges.getNumeroBi() == null || teacher.getBi() == null || ! teacherSiges.getNumeroBi().equals(teacher.getBi()))
332 jmachado 772
        {
1312 jmachado 773
 
774
            teachersChangeBI++;
775
 
776
            1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder builder = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
777
 
778
            /*******Logging************************/
779
            builder.append("ATENCAO NUMERO DE PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO Confirme dados\n");
780
            builder.append("ALTERANDO DADOS DO PROFESSOR " + teacherSiges.getCodigoFuncionario() + "\n");
781
            builder.append("-------ANTES: " + "\n");
782
            builder.append("-------BI: " + teacher.getBi() + "\n");
783
            builder.append("-------Nome: " + teacher.getName() + "\n");
784
            builder.append("-------Username: " + teacher.getUserNameNetpa() + "\n");
785
            builder.append("-------Address: " + teacher.getAddress() + "\n");
786
            builder.append("-------Zip: " + teacher.getZip() + "\n");
787
            builder.append("-------Email: " + teacher.getEmail() + "\n");
788
            builder.append("-------Phone: " + teacher.getPhonenumber() + "\n");
789
            /*******Logging************************/
790
 
791
 
792
            cloneFields(teacherSiges, teacher);
793
 
794
            //teacher.setAutoBlockMode(false);
795
            //teacher.setManualBlock(true);
796
 
797
            /*******Logging************************/
798
            builder.append("DEPOIS: " + "\n");
799
            builder.append("BI: " + teacher.getBi() + "\n");
800
            builder.append("Nome: " + teacher.getName() + "\n");
801
            builder.append("Username: " + teacher.getUserNameNetpa() + "\n");
802
            builder.append("Address: " + teacher.getAddress() + "\n");
803
            builder.append("Zip: " + teacher.getZip() + "\n");
804
            builder.append("Email: " + teacher.getEmail() + "\n");
805
            builder.append("Phone: " + teacher.getPhonenumber() + "\n");
806
            serviceLogWarn(builder.toString());
807
            sendNotificationAdmin("CODIGO SIGES PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO - NAO FOI BLOQUEADO OS DADOS FORAM REPOSTOS ",builder.toString());
808
            /*******Logging************************/
809
 
332 jmachado 810
        }
1312 jmachado 811
        else
812
        {
1316 jmachado 813
            //novo para termos sempre o email externo
814
            if(teacher.getOutEmail() == null ||teacher.getOutEmail().indexOf("@") < 0)
815
                teacher.setOutEmail(teacherSiges.getEmail());
1312 jmachado 816
            //VAMOS APENAS ADICIONAR CAMPOS QUE AINDA NAO EXISTAM IGUAL AO CLONE MAS NAO MECHE
817
            if(teacher.getName() == null || teacher.getName().length() == 0)
818
                teacher.setName(teacherSiges.getNomeFuncionarioInt());
819
            //Email instituicao
1316 jmachado 820
            //if(teacher.getEmail() == null || teacher.getEmail().indexOf("@") < 0)
821
            //    teacher.setEmail(teacherSiges.getEmail());
332 jmachado 822
 
1316 jmachado 823
            1.5.0/docs/api/java/lang/String.html">String suffixReaded = null;
824
            List<String> sufixes = ConfigProperties.getListValues("email.local.suffix.");
825
            for(1.5.0/docs/api/java/lang/String.html">String suffix: sufixes)
1312 jmachado 826
            {
1316 jmachado 827
                if(teacherSiges.getEmail()!=null && teacherSiges.getEmail().endsWith("@"+suffix))
828
                {
829
                    suffixReaded = suffix;
830
                    break;
831
                }
832
            }
833
 
834
            if (teacherSiges.getEmail() != null && (teacher.getUsername() == null || teacher.getUsername().trim().length() == 0)
835
                    && suffixReaded != null)
836
            {
1312 jmachado 837
                int atIndex = teacherSiges.getEmail().indexOf("@");
838
                if (atIndex > 0)
839
                {
840
                    teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
841
                    /*******Logging************************/
842
                    msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
843
                    logger.info(msgS);
844
                    serviceLogInfo(msgS);
845
                    /*******Logging************************/
846
                }
847
                else
848
                {
849
                    /*******Logging************************/
850
                    msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
851
                    logger.info(msgS);
852
                    serviceLogInfo(msgS);
853
                    /*******Logging************************/
854
                }
855
            }
856
            else if(teacher.getUsername() == null || teacher.getUsername().trim().length() == 0)
857
            {
858
                /*******Logging************************/
859
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
860
                logger.info(msgS);
861
                serviceLogInfo(msgS);
862
                /*******Logging************************/
863
 
864
                teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
865
            }
866
            else
867
            {
868
                //ALL OK
869
                //username não foi alterado
870
                //msgS="Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao lhe foi alterado o username " + teacher.getUsername();
871
                //logger.info(msgS);
872
                //serviceLogInfo(msgS);
873
            }
874
            teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
875
            if(teacher.getAddress() == null || teacher.getAddress().length() == 0)
876
                teacher.setAddress(teacherSiges.getMorada());
877
            if(teacher.getZip() == null || teacher.getZip().length() == 0)
878
                teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
879
            if(teacher.getBi() == null || teacher.getBi().length() == 0)
880
                teacher.setBi(teacherSiges.getNumeroBi());
881
            teacher.setEmployerName(teacherSiges.getNomeFuncionario());
882
            teacher.setAcademicName(teacherSiges.getNomeAcademico());
883
            if(teacher.getBirthDate() == null || teacher.getBirthDate().getTime() == 0)
884
                teacher.setBirthDate(teacherSiges.getData_nascimento());
885
        }
116 jmachado 886
    }
887
 
996 jmachado 888
    @1.5.0/docs/api/java/lang/Override.html">Override
1070 jmachado 889
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {
996 jmachado 890
 
1070 jmachado 891
        1.5.0/docs/api/java/lang/String.html">String importYear = getParametersMap().get(JOB_importYear_KEY).getObject();
1312 jmachado 892
        1.5.0/docs/api/java/lang/String.html">String institutionCode = getParametersMap().get(JOB_institution_KEY).getObject();
893
        return run(importYear,1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(institutionCode));
996 jmachado 894
    }
895
 
896
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
897
 
898
 
116 jmachado 899
    /**
900
     * Testar por aqui poi requer Super Role e assim e' autmatico
165 jmachado 901
     *
116 jmachado 902
     * @param args of main
903
     * @throws ServiceException on error
904
     */
165 jmachado 905
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException
116 jmachado 906
    {
995 jmachado 907
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
491 jmachado 908
        if(args != null && args.length > 0)
909
            year = args[0];
1312 jmachado 910
        1.5.0/docs/api/java/lang/String.html">String institutionCode = "1";
911
        if(args != null && args.length > 1)
912
            institutionCode = args[1];
116 jmachado 913
        AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 914
        new ImportTeachersService().run(year,1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(institutionCode));
116 jmachado 915
        AbstractDao.getCurrentSession().getTransaction().commit();
916
    }
917
 
918
 
919
}