Subversion Repositories bacoAlunos

Rev

Rev 1306 | Rev 1312 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.sigesimports;

import jomm.dao.impl.AbstractDao;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.StaleStateException;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.services.common.CommonServicesManager;
import pt.estgp.estgweb.services.email.SendEmailService;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.services.jobs.ServiceJob;
import pt.estgp.estgweb.services.logresults.ILogMessages;
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
import pt.estgp.estgweb.services.sigesimports.oracle.dao.DocenteDao;
import pt.estgp.estgweb.services.sigesimports.oracle.dao.connection.ConnectionManager;
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Disciplina;
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Docente;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.estgp.estgweb.utils.Email;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import java.sql.Connection;
import java.util.*;

/**
 * @author Jorge Machado
 * @date 11/May/2008
 * @time 12:51:32
 * @see pt.estgp.estgweb
 */

public class ImportTeachersService extends ServiceJob implements IService
{

    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);

    private static final int MAX_COMMIT = 20;

    //int studentsMerged = 0;
    int teachersNew = 0;
    int teachersZeroUnits = 0;
    int unitsNotFound = 0;
    int unitsNotFoundCourseNotFound = 0;
    int unitsFoundForCourseNotFoundMult = 0;
    int unitsFoundForCourseNotFoundSingle = 0;
    int unitsDuplicated = 0;
    int unitsAddedToTeachers = 0;
    int unitsRemovedToTeachers = 0;
    int unitsLocalAddedNotRemoved = 0;
    int teachersFound = 0;
    int teachersChangeBI = 0;
    int unitsLocallyRemovedNotAdded = 0;

    //todo meter a zero no run

    public ILogMessages run(1.5.0/docs/api/java/lang/String.html">String year) throws ServiceException
    {

        teachersNew = 0;
        teachersZeroUnits = 0;
        unitsNotFound = 0;
        unitsNotFoundCourseNotFound = 0;
        unitsFoundForCourseNotFoundMult = 0;
        unitsFoundForCourseNotFoundSingle = 0;
        unitsDuplicated = 0;
        unitsAddedToTeachers = 0;
        unitsRemovedToTeachers = 0;
        unitsLocalAddedNotRemoved = 0;
        teachersFound = 0;
        teachersChangeBI = 0;
        unitsLocallyRemovedNotAdded = 0;

        1.5.0/docs/api/java/lang/String.html">String msgS = "STARTING TEACHERS IMPORT SERVICE FOR YEAR: " + year;
        serviceLogInfo(msgS);
        logger.info(msgS);

        DefaultLogMessages logMessages = new DefaultLogMessages();
        logMessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.INFO, "instituicao " + DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode()));

        try
        {
            //String WSDL = DaoFactory.getConfigurationDaoImpl().getSigesWebServicesWsdl();
            //SiGesWEB service;
            /*try
            {
                serviceLogInfo("STARTING WEB SERVICE AT " + WSDL);
                service = new SiGesWEB(new URL(WSDL), new QName(Globals.SIGES_WEBSERVICE_TARGET_NAMESPACE, "SiGesWEB"));
            }
            catch (MalformedURLException e)
            {
                logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "erro na configuracao do WEB Service", LogMessageTypeEnum.INFO));
                logger.fatal(e, e);
                serviceLogFatal(logMessages.getLastMessage(), e);
                return logMessages;
            }
            ArrayOfDecimal codigosDocentes = service.getSiGesWEBSoap().getCodigosDocentesInscritosDaInstituicao(new BigDecimal(DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode()), year);
            */

            List<Integer> codigosDocentes = DocenteDao.getInstance().loadCodigosDocentes(DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode(), year);
           // List<BigDecimal> codigos = codigosDocentes.getDecimal();

            1.5.0/docs/api/java/sql/Connection.html">Connection conn = ConnectionManager.openConnection();
            int i = 1;
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codigosDocentes)
            {

                teachersFound++;
                if (i++ > MAX_COMMIT)
                {
                    i = 0;
                    setProgress((int) (((float)teachersFound)/((float)codigosDocentes.size())*100.0f));
                    commitPartially();
                }


                logger.info("Starting import Funcionario: SIGES:" + c);
                //Docente d = service.getSiGesWEBSoap().getDocente(c, new BigDecimal(DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode()), year);
                Docente d = DocenteDao.getInstance().load(c, DaoFactory.getConfigurationDaoImpl().getSigesInstitutionCode(), year,conn);
                logger.info("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
                serviceLogInfo("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
                logger.info("SIGES IMPORTED INFO: " + docenteToString(d));
                serviceLogInfo("SIGES IMPORTED INFO: " + docenteToString(d));
                        Teacher t = DaoFactory.getTeacherDaoImpl().loadBySigesCode(d.getCodigoFuncionario().intValue());
                boolean newUser = false;
                if (t == null)
                {
                    msgS = "Teacher does not exist in baco, will create SIGES:" + d.getCodigoFuncionario().intValue();
                    logger.info(msgS);
                    serviceLogInfo(msgS);

                    t = DomainObjectFactory.createTeacherImpl();
                    DaoFactory.getTeacherDaoImpl().save(t);
                    newUser = true;
                    //teachersNew++;
                }
                else
                {
                    msgS = "Teacher EXIST in baco with SIGES: " + d.getCodigoFuncionario().intValue();
                    logger.info(msgS);
                    //serviceLogInfo(msgS);  //NOT NEED EXCESS OF INFORMATION
                }
                msgS = "Will persist SIGES(" + d.getCodigoFuncionario().intValue() + ")  baco (username:" + t.getUsername() + ") baco name:" + t.getName();
                logger.info(msgS);
                serviceLogInfo(msgS);
                try
                {
                    persist(d, t, newUser,year,logMessages);
                }
                catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
                {
                    logger.error(e, e);
                    throw e;
                }
                if (newUser)
                    CommonServicesManager.getInstance().adviseNew(t);
                else
                {
                    1.5.0/docs/api/java/lang/String.html">String password = t.getPassword();
                    t.setPassword(null);
                    CommonServicesManager.getInstance().adviseUpdate(t);
                    t.setPassword(password);
                }
            }
            conn.close();

        }
        catch(StaleStateException e)
        {
            AbstractDao.getCurrentSession().getTransaction().rollback();
            AbstractDao.getCurrentSession().beginTransaction();
            logger.error(e,e);
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
            sendNotificationAdmin("Erro de importacao de docentes",e.toString());
        }
        catch(HibernateException e)
        {
            AbstractDao.getCurrentSession().getTransaction().rollback();
            AbstractDao.getCurrentSession().beginTransaction();
            logger.error(e,e);
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
            sendNotificationAdmin("Erro de base de dados importacao de docentes, provavelmente chave errada, corrigir no MySql",e.toString());
        }
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
        {
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
            logger.error(e, e);
            throw new ServiceException(e.toString(), e);
        }






        serviceLogInfo("############################");
        serviceLogInfo("############################");
        serviceLogInfo("#Teachers found: " + teachersFound);
        serviceLogInfo("#Teachers New: " + teachersNew);
        serviceLogInfo("#Teachers Zero Units: " + teachersZeroUnits);
        serviceLogInfo("#Units not found: " + unitsNotFound);
        serviceLogInfo("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
        serviceLogInfo("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
        serviceLogInfo("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
        serviceLogInfo("#Units duplicated : " + unitsDuplicated);
        serviceLogInfo("#Units removed to Teachers: " + unitsRemovedToTeachers);
        serviceLogInfo("#Units added to Teachers: " + unitsAddedToTeachers);
        serviceLogInfo("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
        serviceLogInfo("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);

        logger.info("############################");
        logger.info("############################");
        logger.info("#Teachers found: " + teachersFound);
        logger.info("#Teachers New: " + teachersNew);
        logger.info("#Teachers Zero Units: " + teachersZeroUnits);
        logger.info("#Units not found: " + unitsNotFound);
        logger.info("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
        logger.info("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
        logger.info("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
        logger.info("#Units duplicated : " + unitsDuplicated);
        logger.info("#Units removed to Teachers: " + unitsRemovedToTeachers);
        logger.info("#Units added to Teachers: " + unitsAddedToTeachers);
        logger.info("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
        logger.info("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);


        if(teachersChangeBI>0)
        {
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
            serviceLogInfo("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
            serviceLogInfo("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);

            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
            logger.info("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
            logger.info("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);
        }
        setProgress(100);

        logMessages.addMessage(new DefaultLogMessage("import.teachers.terminating", LogMessageTypeEnum.INFO));
        logger.info("terminating teacher import");
        serviceLogInfo("terminating teacher import");
        return logMessages;
    }


    /**
     * Envio de Notificação aos operadores do CI
     * @param subject
     * @param cause
     */

    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)
    {
        //todo JOB

        List<String> emails = ConfigProperties.getListValues("admin.email");
        for(1.5.0/docs/api/java/lang/String.html">String email:emails)
        {
            serviceLogWarn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
            logger.warn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
        }
        List<String> arguments = new ArrayList<String>();
        arguments.add(cause.replace("\n","<br/>"));
        Email email = new Email(subject,emails,Globals.SYSTEM_EMAIL_BOX,"messageToAdmin_pt.txt",arguments);
        email.setHtml(true);
        try {
            new SendEmailService().sendEmail(email);
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }

    /**
     * Implementação local do toString para a class Docente que foi gerada pelos web-services
     * @param d
     * @return
     */


    public 1.5.0/docs/api/java/lang/String.html">String docenteToString(Docente d)
    {
        return "Docente{" +
                "codigoFuncionario=" + d.getCodigoFuncionario() +
                ", nomeFuncionario='" + d.getNomeFuncionario() + '\'' +
                ", nomeFuncionarioInt='" + d.getNomeFuncionarioInt() + '\'' +
                ", nomeAcademico='" + d.getNomeAcademico() + '\'' +
                ", sexo='" + d.getSexo() + '\'' +
                ", dataNascimento=" + d.getData_nascimento() +
                ", morada='" + d.getMorada() + '\'' +
                ", codigoPostal=" + d.getCodigoPostal() +
                ", subCodigoPostal=" + d.getSubCodigoPostal() +
                ", email='" + d.getEmail() + '\'' +
                ", numeroBi='" + d.getNumeroBi() + '\'' +
                ", usernameNetpa='" + d.getUsernameNetpa() + '\'' +
                ", disciplinas=" + d.getDisciplinas() +
                '}';
    }

    private void cloneFields(Docente teacherSiges, Teacher teacher)
    {

        teacher.setName(teacherSiges.getNomeFuncionarioInt());
        teacher.setEmail(teacherSiges.getEmail());
        1.5.0/docs/api/java/lang/String.html">String msgS;

        if(teacherSiges.getEmail() != null && teacherSiges.getEmail().endsWith(Globals.EMAIL_LOCAL_SUFFIX))
        {
            int atIndex = teacherSiges.getEmail().indexOf("@");
            if (atIndex > 0)
            {
                teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
                logger.info(msgS);
                serviceLogInfo(msgS);
            }
            else
            {
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
                logger.info(msgS);
                serviceLogInfo(msgS);
            }
        }
        else
        {
            msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
            logger.info(msgS);
            serviceLogInfo(msgS);
            teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
        }
        teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
        teacher.setAddress(teacherSiges.getMorada());
        teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
        teacher.setBi(teacherSiges.getNumeroBi());
        teacher.setEmployerName(teacherSiges.getNomeFuncionario());
        teacher.setAcademicName(teacherSiges.getNomeAcademico());
        teacher.setBirthDate(teacherSiges.getData_nascimento());
    }

    private static class TipologiaCourseUnitPair
    {
        CourseUnit cu;
        1.5.0/docs/api/java/lang/Integer.html">Integer cdTipologia;
        1.5.0/docs/api/java/lang/Integer.html">Integer cdFuncaoDocente;
    }
    /**
     * Nao esta testado
     * jm
     *
     * @param teacherSiges docente
     * @param teacher teacher
     * @throws Exception .
     */

    private void persist(Docente teacherSiges, Teacher teacher, boolean newUser, 1.5.0/docs/api/java/lang/String.html">String year,DefaultLogMessages logmessages) throws 1.5.0/docs/api/java/lang/Exception.html">Exception
    {
        1.5.0/docs/api/java/lang/String.html">String msgS;
        1.5.0/docs/api/java/lang/System.html">System.out.println("STATING PERSIST");

        try
        {

            if(newUser)
            {
                teachersNew++;
                cloneFields(teacherSiges, teacher);
                serviceLogInfo("NOVO PROFESSOR ENCONTRADO: siges:" + teacherSiges.getCodigoFuncionario() + " bi:" + teacher.getBi() + " nome:" + teacher.getName());
            }
            //CASO EM QUE O DOCENTE NO SIGES FOI ATRIBUIDO A OUTRO ESTUDANTE PARA PREENCHER BURACO NA NUMERACAO
            else if(teacherSiges.getNumeroBi() == null || teacher.getBi() == null || ! teacherSiges.getNumeroBi().equals(teacher.getBi()))
            {
                teachersChangeBI++;

                1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder builder = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();

                builder.append("ATENCAO NUMERO DE PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO Confirme dados\n");
                builder.append("ALTERANDO DADOS DO PROFESSOR " + teacherSiges.getCodigoFuncionario() + "\n");
                builder.append("-------ANTES: " + "\n");
                builder.append("-------BI: " + teacher.getBi() + "\n");
                builder.append("-------Nome: " + teacher.getName() + "\n");
                builder.append("-------Username: " + teacher.getUserNameNetpa() + "\n");
                builder.append("-------Address: " + teacher.getAddress() + "\n");
                builder.append("-------Zip: " + teacher.getZip() + "\n");
                builder.append("-------Email: " + teacher.getEmail() + "\n");
                builder.append("-------Phone: " + teacher.getPhonenumber() + "\n");

                cloneFields(teacherSiges, teacher);

                //teacher.setAutoBlockMode(false);
                //teacher.setManualBlock(true);

                builder.append("DEPOIS: " + "\n");
                builder.append("BI: " + teacher.getBi() + "\n");
                builder.append("Nome: " + teacher.getName() + "\n");
                builder.append("Username: " + teacher.getUserNameNetpa() + "\n");
                builder.append("Address: " + teacher.getAddress() + "\n");
                builder.append("Zip: " + teacher.getZip() + "\n");
                builder.append("Email: " + teacher.getEmail() + "\n");
                builder.append("Phone: " + teacher.getPhonenumber() + "\n");

                serviceLogWarn(builder.toString());

                sendNotificationAdmin("CODIGO SIGES PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO - NAO FOI BLOQUEADO OS DADOS FORAM REPOSTOS ",builder.toString());

            }
            else
            {
                //VAMOS APENAS ADICIONAR CAMPOS QUE AINDA NAO EXISTAM IGUAL AO CLONE MAS NAO MECHE
                if(teacher.getName() == null || teacher.getName().length() == 0)
                    teacher.setName(teacherSiges.getNomeFuncionarioInt());
                //Email instituicao
                if(teacher.getEmail() == null || teacher.getEmail().indexOf("@") < 0)
                    teacher.setEmail(teacherSiges.getEmail());

                if (teacherSiges.getEmail() != null && (teacher.getUsername() == null || teacher.getUsername().trim().length() == 0) && teacherSiges.getEmail().endsWith(Globals.EMAIL_LOCAL_SUFFIX))
                {
                    int atIndex = teacherSiges.getEmail().indexOf("@");
                    if (atIndex > 0)
                    {
                        teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
                        msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
                        logger.info(msgS);
                        serviceLogInfo(msgS);
                    }
                    else
                    {
                        msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
                        logger.info(msgS);
                        serviceLogInfo(msgS);
                    }
                }
                else if(teacher.getUsername() == null || teacher.getUsername().trim().length() == 0)
                {
                    msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
                    logger.info(msgS);
                    serviceLogInfo(msgS);
                    teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
                }
                else
                {
                    //ALL OK
                    //username não foi alterado
                    //msgS="Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao lhe foi alterado o username " + teacher.getUsername();
                    //logger.info(msgS);
                    //serviceLogInfo(msgS);
                }
                teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
                if(teacher.getAddress() == null || teacher.getAddress().length() == 0)
                    teacher.setAddress(teacherSiges.getMorada());
                if(teacher.getZip() == null || teacher.getZip().length() == 0)
                    teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
                if(teacher.getBi() == null || teacher.getBi().length() == 0)
                    teacher.setBi(teacherSiges.getNumeroBi());
                teacher.setEmployerName(teacherSiges.getNomeFuncionario());
                teacher.setAcademicName(teacherSiges.getNomeAcademico());
                if(teacher.getBirthDate() == null || teacher.getBirthDate().getTime() == 0)
                    teacher.setBirthDate(teacherSiges.getData_nascimento());
            }

            //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
            if (teacherSiges.getDisciplinas() == null ||  teacherSiges.getDisciplinas().size() == 0)
            {
                msgS = "ATENTION TEACHER WITH ZERO UNITS: codigoFuncionario " + teacherSiges.getCodigoFuncionario();
                logger.warn(msgS);
                serviceLogInfo(msgS);

            }
            else
            {
                1.5.0/docs/api/java/lang/System.html">System.out.println("STATING STEPS");
                //1 - PROCEDIMENTO CADEIRAS SAO CARREGADAS DO BACO DA LISTA QUE VEM DO SIGES -> units
                //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
                //3 - Sao adicionadas ao teacher as que o docente ainda nao tiver da lista units
                //4 - Remover da lista do teacher as unidades que não vêm do SIGES e que não foram adicionadas localmente

                //PASSO 1
                1.5.0/docs/api/java/lang/System.html">System.out.println("STATING STEP 1");
                Set<CourseUnit> units = new HashSet<CourseUnit>();

                for (Disciplina disciplina : teacherSiges.getDisciplinas())
                {
                    List<CourseUnit> loadedunits = new ArrayList<CourseUnit>();
                    if(disciplina.getCodigoCurso().intValue() < 0)
                    {
                        //TODO -- CASO ESPECIAL TEM DE SER TRATADO DE FORMA ESPECIAL
                        //TODO -- ISTO VAI OBRIGAR A FAZER O MESMO PROCESSO N VEZES MUDAMOS PARA UMA LISTA DE LOADEDUNITS
                        //TODO -- TEMOS MESMO DE IR BUSCAR AS CADEIRAS AO MAPA DAS TURMAS PRIMEIRO, O MAPA DEVOLVE O CURSO REAL DA TURMA??? PODE SER QUE NAO
                        //TODO -- >>>>>NO CASO DA IMPORTACAO DE ESTUDANTES JA GARANTIMOS QUE A TROCA DE CURSO E FEITA PARA O CORRECTO<<<<<<<
                        //TODO -- OU SEJA SE OPTASSEMOS POR IR BUSCAR O CURSO REAL AO MAPA: 1) Caso seja apenas 1 para essa turma é esse o curso real,
                        //TODO --    mas nesse caso também existe apenas uma cadeira com essa Turma que é nesse curso
                        //TODO -- que é precisamente a cadeira com o curso real, será? pode haver uma cadeira noutro curso nessa turma se o mapa der um curso real unico? Nao.
                        //TODO -- O WEB SERVICE DEVOLVE TODAS AS COMBINACOES POSSIVEIS ASSUMIDAS DE INSCRICOES NORMAIS COM CD_TIPDISC = 1 ou 2
                        //TODO -- Caso 2) Caso haja duas metemos o docente em todas as cadeiras possiveis (CASO ESCPECIAL), ou as guardamos no mapa de cursos reais,
                        //TODO -- ou então vamos à base de dados buscar todas as possiveis e metemos o docente em todas.
                        //TODO -- PORTANTO AS CADEIRAS QUE TEMOS NA NOSSA BD JA SAO APENAS AS VALIDAS GARANTIDAS NA IMPORTACAO DE ESTUDANTES
                        //TODO -- NAO HA CURSO VINDO DO WEB-SERVICE METEMOS O DOCENTE COM TODAS AS POSSIVEIS CONSIDERANDO A TURMA
                        //TODO -- FORMA DE ENCONTRAR A TURMA DEPOIS, TEM DE MUDAR PORQUE VAI MUDAR DE TABELA

                        //TODO -- Isto vai passar a vir com Tipologias. Muda alguma coisa? A mesma cadeira vem duas vezes, mas o procedimento tem de ser o mesmo para as duas vezes
                        //TODO -- que ela é devolvida, caso já exista nao se faz nada, pode-se meter na lista à mesma, fica lá duas vezes, sera?

                        List<CourseUnit> courseUnits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUniqueAllCourses("" + disciplina.getCodigo(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
                        if(courseUnits!=null)
                        {
                            loadedunits = courseUnits;
                        }

                        if(loadedunits.size() > 0)
                        {
                            msgS = "Unit No Course -> course = " + disciplina.getCodigoCurso().intValue() + " semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " year:" + disciplina.getCdLectivo()
                                    + " will load of all possible courses:{ ";
                            for(CourseUnit cc : courseUnits)
                            {
                                msgS+= cc.getCourseCode() + ",";
                            }
                            msgS+=" } all added to teacher: " + teacher.getSigesCode();
                            logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
                            if(loadedunits.size() > 1)
                                unitsFoundForCourseNotFoundMult++;
                            else
                                unitsFoundForCourseNotFoundSingle++;
                            logger.warn(msgS);
                            serviceLogWarn(msgS);
                        }
                    }
                    else{
                        loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUnique("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
                        if(loadedunits.size()>1)
                        {
                            unitsDuplicated++;
                            msgS = "WARNING WARNING #### UnitsDuplicated: ";
                            serviceLogWarn(msgS);
                            logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
                            msgS = "WARNING WARNING ####String sigesCode, String courseCode, String semestre, String year = " + disciplina.getCodigo() + ", " + disciplina.getCodigoCurso() + ","+ disciplina.getCdDuracao() + "," +  disciplina.getCdLectivo();
                            serviceLogWarn(msgS);
                            logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
                            msgS = "WARNING WARNING ####returning first one, this could be a case of units spared because of TURMAS split used in 201516: ";
                            serviceLogWarn(msgS);
                            logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
                        }
                    }

                    //COMENTARIO OBSOLETO - VOLTAMOS AO MESMO, UMA CADEIRA VARIAS TURMAS
                    // Ja todas as unidades tem todas turma, um dos docentes vai perder uma e o outro docente perde a outra
                    //por exemplo uma que era dos dois vai continuar nos dois e será removida de um deles
                    //a outra será adicionada

                    if (loadedunits.size() == 0)
                    {
                        msgS = "Unit not found: semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " course:" + disciplina.getCodigoCurso() + " year:" + disciplina.getCdLectivo();
                        unitsNotFound++;
                        if(disciplina.getCodigoCurso()==null || disciplina.getCodigoCurso().intValue() < 0)
                        {
                            unitsNotFoundCourseNotFound++;
                            msgS += "... unit with No Course Found in SIGES";
                            logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
                        }
                        else
                        {
                            msgS += "... probably unit with zero students not imported in CoursesImport";
                        }
                        logger.warn(msgS);
                        serviceLogWarn(msgS);

                    }
                    else
                        units.addAll(loadedunits);
                }
                1.5.0/docs/api/java/lang/System.html">System.out.println("STATING STEP 2");
                //PASSO 2
                //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
                Iterator<CourseUnit> iter = units.iterator();
                while (iter.hasNext())
                {
                    CourseUnit courseUnit = iter.next();
                    //In case of a comming proxy
                    TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
                    if (tImpl.isLocalRemovedUnit(courseUnit))
                    {
                        unitsLocallyRemovedNotAdded++;
                        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";
                        serviceLogInfo(msg);
                        logger.info(msg);
                        iter.remove();
                    }
                }
                1.5.0/docs/api/java/lang/System.html">System.out.println("STATING STEP 3");
                //PASSO 3
                //3 - da lista units sao adicionadas  ao teacher as que sobraram do passo 2 e o docente ainda nao tiver
                if (teacher.getTeachedUnits() != null)
                {
                    for (CourseUnit c : units)
                    {
                        boolean isIn = false;
                        for (CourseUnit tc : teacher.getTeachedUnits())
                        {
                            if (tc.equals(c))
                            {
                                isIn = true;
                                break;
                            }
                        }
                        if (!isIn)
                        {
                            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";
                            serviceLogInfo(msg);
                            logger.info(msg);
                            unitsAddedToTeachers++;
                            teacher.getTeachedUnits().add(c);
                        }
                    }
                }
                else
                    teacher.setTeachedUnits(units);

                1.5.0/docs/api/java/lang/System.html">System.out.println("STATING STEP 4");
                //PASSO 4
                //Remover unidades deste ano que nao vem do SIGES e que nao foram adicionadas localmente
                Iterator<CourseUnit> iterNowUnits = teacher.getTeachedUnits().iterator();
                TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
                while(iterNowUnits.hasNext())
                {
                    CourseUnit cUNow = iterNowUnits.next();
                    if(cUNow.getImportYear().equals(year))
                    //Apenas tentamos apagar as unidades do ano corrente.
                    //Este servico trabalha com unidades importadas do ano que e passado como argumento
                    //Se importamos unidades desse ano, as dos outros anos nao vem na lista, logo
                    //iriamos constatar que nenhuma estava no SIGES o que nao e verdade.
                    //Assim so apagamos unidades do ano que estamos a importar e que nao venham
                    //na importacao desse ano
                    {

                        boolean added = false;
                        for(CourseUnit c: units)
                        {
                            if(cUNow.equals(c))
                            {
                                added = true;
                                break;
                            }
                        }
                        if(!added)
                        {

                            if(!tImpl.isLocalUnit(cUNow))
                            {
                                1.5.0/docs/api/java/lang/String.html">String msg = "Removendo unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES";
                                //String msg = "Temporariamente não mas sim adicionando localmente, Removendo unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES";
                                //((TeacherImpl)tImpl).addUnitLocaly(cUNow);
                                serviceLogInfo(msg);
                                logger.info(msg);
                                iterNowUnits.remove();
                                unitsRemovedToTeachers++;
                            }
                            else
                            {
                                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";
                                serviceLogInfo(msg);
                                logger.info(msg);
                                unitsLocalAddedNotRemoved++;
                            }
                        }
                    }
                }
                1.5.0/docs/api/java/lang/System.html">System.out.println("END STEP 4");
            }


        }
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
        {
            logger.error(e, e);
            List<String> emails = new ArrayList<String>();
            emails.add(ConfigProperties.getProperty("admin.email"));
            List<String> arguments = new ArrayList<String>();
            1.5.0/docs/api/java/lang/String.html">String cause = e.getCause() == null ? "" : e.getCause().toString();
            arguments.add((e.toString() + "\n" + cause).replace("\n","<br/>"));
            Email email = new Email("Erro de importa��o de professores",emails,"baco@estgp.pt","messageToAdmin_pt.txt",arguments);
            new SendEmailService().sendEmail(email);
            throw e;
        }

    }

    @1.5.0/docs/api/java/lang/Override.html">Override
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {

        1.5.0/docs/api/java/lang/String.html">String importYear = getParametersMap().get(JOB_importYear_KEY).getObject();
        return run(importYear);
    }

    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";


    /**
     * Testar por aqui poi requer Super Role e assim e' autmatico
     *
     * @param args of main
     * @throws ServiceException on error
     */

    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException
    {
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
        if(args != null && args.length > 0)
            year = args[0];
        AbstractDao.getCurrentSession().beginTransaction();
        new ImportTeachersService().run(year);
        AbstractDao.getCurrentSession().getTransaction().commit();
    }


}