package pt.estgp.estgweb.services.sigesimports;
import jomm.dao.impl.AbstractDao;
import jomm.utils.StringsUtils;
import org.apache.log4j.Logger;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.utils.DatesUtils;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.services.common.CommonServicesManager;
import pt.estgp.estgweb.services.logresults.ILogMessages;
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
import pt.ipportalegre.siges.web.services.*;
import pt.utl.ist.berserk.logic.serviceManager.IService;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
/**
* @author Jorge Machado
* @date 11/May/2008
* @time 12:51:32
* @see pt.estgp.estgweb
*/
public class ImportStudentsService
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(ImportStudentsService.
class);
private static final int MAX_COMMIT =
100;
public ILogMessages run
(1.5.0/docs/api/java/lang/String.html">String year
) throws ServiceException
{
DefaultLogMessages logMessages =
new DefaultLogMessages
();
logMessages.
addMessage(new DefaultLogMessage
("import.students", LogMessageTypeEnum.
INFO,
"instituicao " + Globals.
SIGES_INSTITUTION_CODE));
logger.
info("starting student import");
try
{
AbstractDao.
getCurrentSession().
beginTransaction();
SiGesWEB service
;
try
{
service =
new SiGesWEB
(new 1.5.0/docs/api/java/net/URL.html">URL(Globals.
SIGES_WEBSERVICE_WSDL),
new 1.5.0/docs/api/javax/xml/namespace/QName.html">QName(Globals.
SIGES_WEBSERVICE_TARGET_NAMESPACE,
"SiGesWEB"));
}
catch (1.5.0/docs/api/java/net/MalformedURLException.html">MalformedURLException e
)
{
logger.
fatal(e, e
);
logMessages.
addMessage(new DefaultLogMessage
("import.error",e.
toString(),
"erro na configuracao do WEB Service", LogMessageTypeEnum.
INFO));
AbstractDao.
getCurrentSession().
getTransaction().
rollback();
return logMessages
;
}
ArrayOfDecimal codigosAlunos = service.
getSiGesWEBSoap().
getCodigosAlunosInscritosDaInstituicao(Globals.
SIGES_INSTITUTION_CODE, year
);
List
<BigDecimal
> codigos = codigosAlunos.
getDecimal();
int i =
1;
for (1.5.0/docs/api/java/math/BigDecimal.html">BigDecimal c : codigos
)
{
if (i++
> MAX_COMMIT
)
{
i =
0;
AbstractDao.
getCurrentSession().
getTransaction().
commit();
AbstractDao.
getCurrentSession().
beginTransaction();
}
Aluno d = service.
getSiGesWEBSoap().
getAlunoInscrito(c, Globals.
SIGES_INSTITUTION_CODE, year
);
User u = DaoFactory.
getUserDaoImpl().
loadByUsernameOrSigesCode(d.
getCodigo().
intValue());
Student s =
null;
boolean newUser =
false;
if(u
!=
null && !(u
instanceof Student
))
{
logger.
warn("Student " + u.
getUsername() +
"already exist in system, will merge both users");
// Set<Record> records = u.getCreatorRecords();
DaoFactory.
getUserDaoImpl().
delete(u
);
logger.
warn("Student " + u.
getUsername() +
"1");
i =
0;
AbstractDao.
getCurrentSession().
getTransaction().
commit();
AbstractDao.
getCurrentSession().
beginTransaction();
logger.
warn("Student " + u.
getUsername() +
"2");
s = DomainObjectFactory.
createStudentImpl();
DaoFactory.
getStudentDaoImpl().
save(s
);
// for(Record r:records)
// {
// r.setOwner(null);
// DaoFactory.getRecordDaoImpl().reattach(r);
// r.setOwner(s);
// }
newUser =
true;
}
else if(u
!=
null)
{
s = DaoFactory.
getStudentDaoImpl().
load(u.
getId());
}
if (s ==
null)
{
s = DomainObjectFactory.
createStudentImpl();
DaoFactory.
getStudentDaoImpl().
save(s
);
newUser =
true;
}
persist
(d, s, newUser
);
//Advising CommonsServicesManager before change password
if (newUser
)
CommonServicesManager.
getInstance().
adviseNew(s
);
else
{
1.5.0/docs/api/java/lang/String.html">String password = s.
getPassword();
s.
setPassword(null);
CommonServicesManager.
getInstance().
adviseUpdate(s
);
s.
setPassword(password
);
}
}
logMessages.
addMessage(new DefaultLogMessage
("import.students.terminating", LogMessageTypeEnum.
INFO));
logger.
info("terminating student import");
AbstractDao.
getCurrentSession().
getTransaction().
commit();
}
catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
logger.
error(e,e
);
AbstractDao.
getCurrentSession().
getTransaction().
rollback();
logMessages.
addMessage(new DefaultLogMessage
("import.error",e.
toString(),
"see log for details", LogMessageTypeEnum.
ERROR));
}
return logMessages
;
}
/**
* Nao esta testado
* jm
*
* @param d Aluno
* @param student Student
*/
private void persist
(Aluno d, Student student,
boolean newUser
)
{
if(newUser
)
{
student.
setName(d.
getNome());
student.
setEmail(d.
getEmail());
student.
setSigesCode(d.
getCodigo().
intValue());
student.
setAddress(d.
getMorada());
student.
setPhonenumber(StringsUtils.
cleanKeepNumbers(d.
getTelemovel()));
student.
setZip("" + d.
getCodigoPostal().
intValue());
student.
setBi(d.
getNumeroBi());
student.
setSex(d.
getSexo());
student.
setUserNameNetpa(d.
getUsernameNetpa());
student.
setBirthDate(d.
getDataNascimento().
toGregorianCalendar().
getTime());
student.
setUsername("a" + d.
getCodigo().
intValue());
}
/*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 (d.
getDisciplinasInscrito() ==
null || d.
getDisciplinasInscrito().
getDisciplina() ==
null || d.
getDisciplinasInscrito().
getDisciplina().
size() ==
0)
logger.
warn("ATENTION STUDENT WITH ZERO UNITS: codigo " + d.
getCodigo());
else
{
Set
<CourseUnit
> units =
new HashSet
<CourseUnit
>();
ArrayOfDisciplina disciplinas = d.
getDisciplinasInscrito();
for (Disciplina disciplina : disciplinas.
getDisciplina())
{
CourseUnit courseUnit = DaoFactory.
getCourseUnitDaoImpl().
loadBySigesCodeUnique("" + disciplina.
getCodigo(),
"" + disciplina.
getCodigoCurso(),disciplina.
getCdDuracao(),disciplina.
getCdLectivo());
if(courseUnit ==
null)
{
logger.
warn("Unit not found: semestre:" + disciplina.
getCdDuracao() +
" codigo:" + disciplina.
getCodigo() +
" course:" + disciplina.
getCodigoCurso() +
" year:" + disciplina.
getCdLectivo());
}
else
units.
add(courseUnit
);
}
Iterator
<CourseUnit
> iter = units.
iterator();
while (iter.
hasNext())
{
CourseUnit courseUnit = iter.
next();
//In case of a comming proxy
StudentImpl sImpl =
(StudentImpl
) DaoFactory.
getStudentDaoImpl().
narrow(student
);
if(sImpl.
isLocalRemovedUnit(courseUnit
))
iter.
remove();
}
if(student.
getSubscribedUnits() !=
null)
{
for(CourseUnit c: units
)
{
boolean isIn =
false;
for(CourseUnit tc : student.
getSubscribedUnits())
{
if(tc.
equals(c
))
{
isIn =
true;
break;
}
}
if(!isIn
)
student.
getSubscribedUnits().
add(c
);
}
}
else
student.
setSubscribedUnits(units
);
//Remover unidades que nao vem do SIGES e que nao foram adicionadas localmente
Iterator
<CourseUnit
> iterNowUnits = student.
getSubscribedUnits().
iterator();
while(iter.
hasNext())
{
CourseUnit cUNow = iterNowUnits.
next();
boolean added =
false;
for(CourseUnit c: units
)
{
if(cUNow.
equals(c
))
{
added =
true;
break;
}
}
if(!added
)
{
if(!StringsUtils.
hasElement(student.
getLocalSubscribedUnits(),
""+cUNow,
","))
{
logger.
info("Removendo unidade: " + cUNow.
getCode() +
" - do aluno: " + student.
getSigesCode() +
" - Associação desapareceu do SIGES");
iter.
remove();
}
else
{
logger.
info("NÃO REMOVIDA - Unidade: " + cUNow.
getCode() +
" - do aluno: " + student.
getSigesCode() +
" - Associação desapareceu do SIGES mas foi adicionada localmente");
}
}
}
}
}
/**
* 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 = DatesUtils.
getImportYear();
if(args
!=
null && args.
length > 0
)
year = args
[0
];
new ImportStudentsService
().
run(year
);
}
}