Subversion Repositories bacoAlunos

Rev

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

package pt.estgp.estgweb.services.courses;

import com.owlike.genson.Genson;
import com.owlike.genson.TransformationException;
import com.owlike.genson.reflect.VisibilityFilter;
import jomm.utils.FilesUtils;
import jomm.utils.StreamsUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.domain.views.CourseView;
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
import pt.estgp.estgweb.services.courses.xsd.Curso;
import pt.estgp.estgweb.services.courses.xsd.UnidadeType;
import pt.estgp.estgweb.services.data.IRepositoryFile;
import pt.estgp.estgweb.services.data.RepositoryService;
import pt.estgp.estgweb.services.expceptions.AlreadyExistsException;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.estgp.estgweb.utils.Dom4jUtil;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.*;

/*
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

/**
 * @author Jorge Machado
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

public class CoursesService 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(CoursesService.class);

    RepositoryService repositoryService = new RepositoryService();


    public CourseView loadCourse(long id, boolean initUnits) throws ServiceException
    {
        Course c = DaoFactory.getCourseDaoImpl().get(id);

        if(c != null)
        {
            CourseView cV = new CourseView(c,initUnits);
            if(c.getStudiesPlan() != null)
            {
                RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
                cV.setStudiesPlan(repositoryFile);
            }

            return cV;
        }
        return null;
    }

    public List<String> loadImportYears(UserSession userSession) throws ServiceException
    {
        List<String> importYears = DaoFactory.getCourseDaoImpl().loadImportYears();
        List<String> imStrings = new ArrayList<String>();
        for(1.5.0/docs/api/java/lang/String.html">String importYear: importYears)
        {
            imStrings.add(importYear);
        }
        return imStrings;
    }

    public CourseView loadCourseByCode(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits) throws ServiceException
    {
        try{
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
            if(c != null)
            {
                CourseView cV = new CourseView(c,initUnits);
                if(c.getStudiesPlan() != null)
                {
                    RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
                    cV.setStudiesPlan(repositoryFile);
                }
                return cV;
            }
        }
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
        {
            logger.error(e + " loading code:" + code,e);
            throw new ServiceException("loading code: " + code  + " - " + e.toString(),e);
        }
        return null;
    }

    public CourseView submitCourse(CourseView courseView,
                                   5+0%2Fdocs%2Fapi+InputStream">InputStream stream,
                                   1.5.0/docs/api/java/lang/String.html">String name,
                                   int size,
                                   1.5.0/docs/api/java/lang/String.html">String contentType,
                                   UserSession userSession) throws ServiceException, JAXBException, TransformationException, 1.5.0/docs/api/java/io/IOException.html">IOException {
        Course c;
        if(courseView.getId() > 0)
        {
            c = DaoFactory.getCourseDaoImpl().get(courseView.getId());
        }
        else
        {
            c = DaoFactory.getCourseDaoImpl().findCourseByCodeAndYear(courseView.getCode(),courseView.getImportYear());
            if(c != null)
                throw new AlreadyExistsException(AlreadyExistsException.ALREADY_EXISTS_COURSE);      
            c = DomainObjectFactory.createCourseImpl();
            DaoFactory.getCourseDaoImpl().save(c);
        }

        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;

        htmlTrasformationResult = uploadStudiesPlan(stream, name, size, contentType, userSession, c,false,null);
        courseView.persistViewInObject(c);
        CourseView cv = loadCourse(c.getId(),false);
        cv.setHtmlResult(htmlTrasformationResult);

        /**
         * New## generating course json
         */

        generateCourseJson(c);

        return cv;
    }

    private 1.5.0/docs/api/java/lang/String.html">String uploadStudiesPlan(5+0%2Fdocs%2Fapi+InputStream">InputStream stream, 1.5.0/docs/api/java/lang/String.html">String name, int size, 1.5.0/docs/api/java/lang/String.html">String contentType, UserSession userSession, Course c,boolean forceUrlFichas, 1.5.0/docs/api/java/lang/String.html">String systemUrl) throws JAXBException, TransformationException {
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
        if(stream != null && size > 0)
        {
            1.5.0/docs/api/java/lang/String.html">String extension = FilesUtils.getExtension(name);
            if(c.getStudiesPlan() == null)
            {
                1.5.0/docs/api/java/lang/String.html">String identifier = repositoryService.storeRepositoryFile(stream, contentType, extension, size, name, "course.studies.plan " + c.getName(), ResourceAccessControlEnum.publicDomain,userSession);
                c.setStudiesPlan(identifier);
            }
            else
            {
                repositoryService.updateRepositoryFile(c.getStudiesPlan(), stream, contentType, extension, size, name, "course.studies.plan " + c.getName(), ResourceAccessControlEnum.publicDomain);
            }
            htmlTrasformationResult = generateHtmlCache(userSession, c);
            //####New#### Generating XML with JaxB
            generateXmlJaxbStudiesPlanVersion(userSession, c,forceUrlFichas,systemUrl);
        }
        return htmlTrasformationResult;
    }

    private void generateCourseJson(Course cAux) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
        CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);

        if(c.getValidationRole() != null && c.getValidationRole().trim().length() > 0)
        {
            List<Teacher> courseComissionProxys = DaoFactory.getUserDaoImpl().loadRoleTeachers(c.getValidationRole());
            List<Teacher> courseComission = new ArrayList<Teacher>();
            for(Teacher t: courseComissionProxys)
            {
                courseComission.add(DaoFactory.getTeacherDaoImpl().narrow(t));
            }
            c.setCourseComission(courseComission);
        }
        //Getting Coordinator from proxy
        Teacher t = c.getCoordinator();
        if(t != null)
            t.getName();
        else
        {
            logger.warn("Course does not have coordinator");
        }

        1.5.0/docs/api/java/lang/String.html">String jsonCourse = getGensonCourse().serialize(c);
        c.setJson(jsonCourse);
    }

    private 1.5.0/docs/api/java/lang/String.html">String generateHtmlCache(UserSession userSession, Course c) {
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
        stream = repositoryFile.getInput();
        try
        {
            5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(stream);
            Map<String,Object> parameters = new HashMap<String,Object>();
            parameters.put("COURSE_SIGES_CODE",c.getCode());
            1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.styleDocument(dom, Globals.TEMPLATE_COURSE_XSL_PATH,parameters);
            c.setCacheWebDocument(html);
        }
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
        {
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
            1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter printWriter = new 1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter(writer);
            e.printStackTrace(printWriter);
            htmlTrasformationResult = "<div class=\"error\"><pre>" + e.toString() + "\n" + printWriter.toString() + "</pre></div>";
            printWriter.close();
        }
        try
        {
            stream.close();
        }
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
        {
            logger.error(e,e);
        }
        return htmlTrasformationResult;
    }

    /**
     * ##NEW METHOD###
     * Gera o XML normalizado para o JAXB a partir do XML importado do XML do plano XML quese usou no upload
     * para garantir que está bem formado
     * @param userSession
     * @param c
     * @return
     * @throws JAXBException if XML is not weel formed
     */

    private void generateXmlJaxbStudiesPlanVersion(UserSession userSession, Course c,boolean forceFichaCurricularUrlSet,1.5.0/docs/api/java/lang/String.html">String systemUrl) throws JAXBException, TransformationException
    {
        CourseStudiesPlan courseStudiesPlan;
        if(c.getStudiesPlan() == null || c.getStudiesPlan().trim().length() == 0)
        {
            logger.warn("Course does not have studies plan XML file stream to use in update");
            return;
        }

        if(c.getStudiesPlans() == null || c.getStudiesPlans().size() == 0)
        {
            logger.info("Generating first study plan");
            courseStudiesPlan = DomainObjectFactory.createCourseStudiesPlanImpl();
            courseStudiesPlan.setVersion(1);
            courseStudiesPlan.setVersionDescription("Auto gerado durante a importação de um XML com o plano de estudos a " + new 5+0%2Fdocs%2Fapi+Date">Date().toString());
            courseStudiesPlan.setCourse(c);
            if(c.getStudiesPlans() == null)
                c.setStudiesPlans(new HashSet<CourseStudiesPlan>());
            c.getStudiesPlans().add(courseStudiesPlan);
            DaoFactory.getCourseStudiesPlanDaoImpl().save(courseStudiesPlan);
        }
        else
        {
            courseStudiesPlan = c.getStudiesPlans().iterator().next();
            logger.info("Updating Study Plan version " + courseStudiesPlan.getVersion());
        }

        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;
        IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
        stream = repositoryFile.getInput();

        try {
            JAXBContext jc = JAXBContext.newInstance(Curso.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Curso curso = (Curso) unmarshaller.unmarshal(stream);

            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter sw = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
            marshaller.marshal(curso, sw);
            //SETTING XML in COURSE STUDIES PLAN
            courseStudiesPlan.setXml(sw.toString());
            //##NOVO PARA GERAR LINK SE NAO EXISTIR
            generateAutoUrlFichasCurriculares(curso,systemUrl,forceFichaCurricularUrlSet);
            1.5.0/docs/api/java/lang/String.html">String json = getGensonCursoXmlObj().serialize(curso);
            //SETTING JSON in COURSE STUDIES PLAN
            courseStudiesPlan.setJson(json);

        } catch (JAXBException e) {
            logger.error(e,e);
            throw e;
        } catch (TransformationException e) {
            logger.error(e, e);
            throw e;
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
            e.printStackTrace();
        }
        try
        {
            stream.close();
        }
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
        {
            logger.error(e,e);
        }
    }

    private void generateAutoUrlFichasCurriculares(Curso curso,1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean force)
    {
        for(Curso.Semestre s :curso.getSemestre())
        {
            for(Curso.Semestre.Perfil p :s.getPerfil())
            {
                for(UnidadeType unidadeType : p.getUnidade())
                {
                    generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
                }
            }
            for(UnidadeType unidadeType : s.getUnidade())
            {
                generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
            }
        }
    }

    private void generateAutoUrlUnidade(UnidadeType unidadeType,1.5.0/docs/api/java/lang/String.html">String systemUrl,Curso curso,Curso.Semestre semestre,boolean force)
    {
        if(force || unidadeType.getUrlFichaCurricular() == null || unidadeType.getUrlFichaCurricular().trim().length()==0)
        {
            logger.info("GENERATING FICHA CURRICULAR URL For " + unidadeType.getNome());
            1.5.0/docs/api/java/lang/String.html">String url = systemUrl != null ? systemUrl : "";
            if(!url.endsWith("/;"))
                url = url + "/";
            unidadeType.setUrlFichaCurricular(url + "startLoadCourseUnitSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
        }
    }


    private static Genson getGensonCursoXmlObj(){
        Genson genson = new Genson.Builder()
                .exclude("class")
                .create();
        return genson;
    }



    private static Genson getGensonCourse(){
        Genson genson = new Genson.Builder()
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
                .setUseFields(false)
                .setUseGettersAndSetters(true)
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
                .exclude("admin")
                .exclude("autoBlock")
                .exclude("autoBlockMode")
                .exclude("manualBlock")
                .exclude("newUser")
                .exclude("student")
                .exclude("superuser")
                .exclude("superuserOrAdmin")
                .exclude("teacher")
                .exclude("unitCheck")
                .exclude("id")

/*              .exclude(Course.class)
                .exclude(CourseImpl.class)
                .exclude(GenericUser.class)
                .exclude(User.class)
                .exclude(UserImpl.class)
                .exclude(Teacher.class)
                .exclude(TeacherImpl.class)
                .exclude(SigesUser.class)
                .exclude(SigesUserImpl.class)
                .exclude(GenericUser.class)
                .exclude(GenericUserImpl.class)
*/

                .exclude("id", Course.class)
                .exclude("status",Course.class)
                .include("degreeForJsonApi", CourseImpl.class)
                .include("schoolForJsonApi", CourseImpl.class)
                .include("statusForJsonApi", CourseImpl.class)

                .include("name", Course.class)
                .include("code", Course.class)
                .include("validationRole", Course.class)

                .include("courseComission", CourseImpl.class)

                .include("name", GenericUser.class)
                .include("email", GenericUser.class)
                .include("sigesCode", SigesUser.class)
                .include("coordinator", Course.class)
                .create();

        return genson;
    }



    public List<CourseView> loadCourses() throws ServiceException
    {
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c: courses)
        {
            CourseView courseView = new CourseView(c);
            courseViews.add(courseView);
        }
        return courseViews;
    }

    public List<CourseView> loadCoursesImportYearArea(1.5.0/docs/api/java/lang/String.html">String importYear, 1.5.0/docs/api/java/lang/String.html">String area) throws ServiceException
    {
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
    }

    public List<CourseView> loadCoursesImportYearAreaInstitution(1.5.0/docs/api/java/lang/String.html">String importYear, 1.5.0/docs/api/java/lang/String.html">String area,1.5.0/docs/api/java/lang/String.html">String institutionCode) throws ServiceException
    {
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c: courses)
        {
            CourseView courseView = new CourseView(c);
            courseViews.add(courseView);
        }
        return courseViews;
    }

    public List<CourseView> loadCoursesImportYear() throws ServiceException
    {
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c: courses)
        {
            CourseView courseView = new CourseView(c);
            courseViews.add(courseView);
        }
        return courseViews;
    }
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
    {
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c: courses)
        {
            CourseView courseView = new CourseView(c);
            courseViews.add(courseView);
        }
        return courseViews;
    }

    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
    {
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c: courses)
        {
            CourseView courseView = new CourseView(c);
            courseViews.add(courseView);
        }
        return courseViews;
    }



    /** JSON API **/
    /**
     * @SERVICE@
     *
     * @param school
     * @param type
     * @return
     * @throws JSONException
     */

    public JSONObject getActiveCoursesForJsonApi(1.5.0/docs/api/java/lang/String.html">String school,1.5.0/docs/api/java/lang/String.html">String type) throws JSONException {
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
        1.5.0/docs/api/java/lang/String.html">String degree = null;
        if(school != null && school.length() > 0)
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);

        if(type != null && type.length() > 0)
            degree = ConfigProperties.getProperty("course.inverse." + type);

        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(institutionalCode,degree);
        JSONObject coursesResponse = new JSONObject();

        JSONArray coursesArray = new JSONArray();
        for(Course cAux: courses)
        {
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
            JSONObject courseJson = new JSONObject();
            courseJson.put("name",c.getName());
            courseJson.put("code",c.getCode());
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
            coursesArray.put(courseJson);

        }
        coursesResponse.put("status","ok");
        coursesResponse.put("courses",coursesArray);

        return coursesResponse;
    }

    /**
     *
     * * @SERVICE@
     *
     * @param code
     * @return
     * @throws JSONException
     * @throws IOException
     * @throws TransformationException
     * @throws JAXBException
     */

    public JSONObject getCourseDetailForJsonApi(1.5.0/docs/api/java/lang/String.html">String code) throws JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, JAXBException {

        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);


        JSONObject coursesResponse = new JSONObject();

        if(course.getJson() == null)
        {
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
            new CoursesService().generateCourseJson(course);
        }

        if(course.getJson() != null)
        {
            JSONObject courseObj = new JSONObject(course.getJson());
            coursesResponse.put("courseInfo",courseObj);
            if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
            {
                logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
                UserSession userSession = DomainObjectFactory.createUserSessionImpl();
                userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
                new CoursesService().generateXmlJaxbStudiesPlanVersion(userSession, course, false, null);
            }

            if(course.getStudiesPlans() != null)
            {
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
                JSONObject studiesPlanObj = new JSONObject(studiesPlan.getJson());
                studiesPlanObj.put("version",studiesPlan.getVersion());
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
            }
            else
            {
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
            }
        }
        else
        {
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE");
        }
        return coursesResponse;
    }

    /**
     * @SERVICE@
     *
     * @param code
     * @return
     * @throws JSONException
     */

    public 1.5.0/docs/api/java/lang/String.html">String getCourseStudiesPlanXml(1.5.0/docs/api/java/lang/String.html">String code) throws JSONException {

        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);

        if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
        {
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
            try {
                generateXmlJaxbStudiesPlanVersion(userSession, course, false, null);
            } catch (JAXBException e) {
                logger.error(e,e);
                return "<error>" + e.toString() + ". see log for details</error>";
            } catch (TransformationException e) {
                logger.error(e, e);
                return "<error>" + e.toString() + ". see log for details</error>";
            }
        }
       
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
        {
            return course.getStudiesPlans().iterator().next().getXml();
        }
        return "<error>Does not exixt</error>";

    }


    /**
     * @SERVICE@
     *
     * @param systemUrl
     * @param setActive
     * @return
     * @throws IOException
     * @throws JSONException
     * @throws TransformationException
     * @throws JAXBException
     */


    public 1.5.0/docs/api/java/lang/String.html">String sincronizeCoursesStudiesPlans(1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean setActive) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, TransformationException, JAXBException {

        1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
        1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=listCourses");
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
        JSONObject obj = new JSONObject(str);
        JSONArray courses = obj.getJSONArray("courses");
        for(int i = 0; i < courses.length();i++)
        {
            JSONObject course = courses.getJSONObject(i);
            1.5.0/docs/api/java/lang/String.html">String code = course.getString("code");
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
            if(c == null)
            {
                1.5.0/docs/api/java/lang/String.html">String msg = "SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system";
                log.append("<info>" + msg+"</info>");
                logger.info(msg);
            }
            else
            {
                1.5.0/docs/api/java/lang/String.html">String msg = "UPDATING - Course " + code + " " + course.getString("name") + " exist in this system";
                log.append("<info>" + msg+"</info>");
                logger.info(msg);

                //#############UPDATING STUDIES PLAN
                updateStudiesPlanFromRemoteSystem(systemUrl, setActive, log, course, code, c);

                //#############UPDATING Course Comission Members
                updateCourseComissionMembers(systemUrl, code, c);
            }
        }
        return log.toString();

    }

    /**
     * Update courseComission Members
     * @param systemUrl
     * @param code
     * @param c
     * @throws IOException
     * @throws JSONException
     */

    private void updateCourseComissionMembers(1.5.0/docs/api/java/lang/String.html">String systemUrl, 1.5.0/docs/api/java/lang/String.html">String code, Course c) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException {
        1.5.0/docs/api/java/net/URL.html">URL urlCourseDetails = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getCourse&code=" + code);
        5+0%2Fdocs%2Fapi+InputStream">InputStream isCourseDetails = urlCourseDetails.openStream();
        1.5.0/docs/api/java/lang/String.html">String strCourseDetails = StreamsUtils.readString(isCourseDetails);
        JSONObject objCourseDetails = new JSONObject(strCourseDetails);
        1.5.0/docs/api/java/lang/String.html">String validationRole = objCourseDetails.getJSONObject("courseInfo").getString("validationRole");

        if(validationRole == null)
        {
            logger.info("validationRole is not defined");
        }
        else
        {
            logger.info("found validationRole: " + validationRole);
            c.setValidationRole(validationRole);

            JSONObject coordinator = objCourseDetails.getJSONObject("courseInfo").getJSONObject("coordinator");
            JSONArray courseComission = objCourseDetails.getJSONObject("courseInfo").getJSONArray("courseComission");

            Teacher coordinatorPersistent = findPersonFromCourseDetails(coordinator);
            if(coordinatorPersistent == null)
            {
                logger.warn("Coordinator does not exist in this system ");
            }
            else
            {
                c.setCoordinator(coordinatorPersistent);
            }
            for(int j = 0 ; j < courseComission.length(); j++)
            {
                JSONObject memberComission = courseComission.getJSONObject(j);
                Teacher memberPersistent = findPersonFromCourseDetails(memberComission);
                if(memberPersistent == null)
                {
                    logger.info("Member does not exist in this system ");
                }
                else
                {
                    logger.info("Adding role of course comission member");
                    if(!memberPersistent.hasRole(validationRole))
                    {
                        memberPersistent.addRole(validationRole);
                    }
                }

            }
        }
    }

    private Teacher findPersonFromCourseDetails(JSONObject coordinator) {
        int code;
        try {
            if(coordinator.has("sigesCode"))
            {
                code = coordinator.getInt("sigesCode");
            }
            else
            {
                logger.warn("there is no sigesCode for this person " + coordinator.toString());
                return null;
            }
        } catch (JSONException e){
            return null;
        } catch (1.5.0/docs/api/java/lang/NumberFormatException.html">NumberFormatException e){
            return null;
        }
        return DaoFactory.getTeacherDaoImpl().loadBySigesCode(code);
    }

    private void updateStudiesPlanFromRemoteSystem(1.5.0/docs/api/java/lang/String.html">String systemUrl, boolean setActive, 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log, JSONObject course, 1.5.0/docs/api/java/lang/String.html">String code, Course c) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, TransformationException, JAXBException {
        1.5.0/docs/api/java/lang/String.html">String msg;
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
        1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
        int len = studiesPlan.length();
        if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
        {
            msg = "Course " + code + " " + course.getString("name") + " dont has studies plan";
            log.append("<warn>" + msg+"</warn>");
            logger.warn(msg);
        }
        else
        {
            msg = "Found studies plan for "  + code + " " + course.getString("name") + " will update ";
            log.append("<info>" + msg+"</info>");
            logger.info(msg);
            if(setActive)
            {
                msg = "Setting course to active";
                log.append("<info>" + msg+"</info>");
                logger.info(msg);
                c.setStatus(true);
            }
            //System.out.println(studiesPlan);
            msg = "GENERATING COURSE JSON ....";
            log.append("<info>" + msg+"</info>");
            logger.info(msg);
            new CoursesService().generateCourseJson(c);

            msg="GENERATING COURSE STUDIES PLAN JSON ....";
            log.append("<info>" + msg+"</info>");
            logger.info(msg);
            stream.close();
            stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
            new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,"http://www.estgp.pt");
        }
    }


}