Subversion Repositories bacoAlunos

Rev

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

Rev Author Line No. Line
214 jmachado 1
package pt.estgp.estgweb.services.courses;
2
 
1496 jmachado 3
import com.owlike.genson.Genson;
4
import com.owlike.genson.TransformationException;
5
import com.owlike.genson.reflect.VisibilityFilter;
1507 jmachado 6
import jomm.dao.impl.AbstractDao;
417 jmachado 7
import jomm.utils.FilesUtils;
1496 jmachado 8
import jomm.utils.StreamsUtils;
417 jmachado 9
import org.apache.log4j.Logger;
10
import org.dom4j.Document;
1496 jmachado 11
import org.json.JSONArray;
12
import org.json.JSONException;
13
import org.json.JSONObject;
417 jmachado 14
import pt.estgp.estgweb.Globals;
1496 jmachado 15
import pt.estgp.estgweb.domain.*;
417 jmachado 16
import pt.estgp.estgweb.domain.dao.DaoFactory;
17
import pt.estgp.estgweb.domain.views.CourseView;
18
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
1496 jmachado 19
import pt.estgp.estgweb.services.courses.xsd.Curso;
1518 jmachado 20
import pt.estgp.estgweb.services.courses.xsd.SemestreImpl;
1496 jmachado 21
import pt.estgp.estgweb.services.courses.xsd.UnidadeType;
417 jmachado 22
import pt.estgp.estgweb.services.data.IRepositoryFile;
214 jmachado 23
import pt.estgp.estgweb.services.data.RepositoryService;
444 jmachado 24
import pt.estgp.estgweb.services.expceptions.AlreadyExistsException;
995 jmachado 25
import pt.estgp.estgweb.services.expceptions.ServiceException;
1496 jmachado 26
import pt.estgp.estgweb.utils.ConfigProperties;
248 jmachado 27
import pt.estgp.estgweb.utils.Dom4jUtil;
417 jmachado 28
import pt.utl.ist.berserk.logic.serviceManager.IService;
214 jmachado 29
 
1496 jmachado 30
import javax.xml.bind.JAXBContext;
31
import javax.xml.bind.JAXBException;
32
import javax.xml.bind.Marshaller;
33
import javax.xml.bind.Unmarshaller;
1505 jmachado 34
import java.io.*;
1496 jmachado 35
import java.net.URL;
36
import java.util.*;
214 jmachado 37
 
38
/*
39
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
40
 *
41
 *
42
 * Created at 17/Out/2003 , 23:45:24
43
 *
44
 */
45
/**
46
 * @author Jorge Machado
47
 *
48
 *
49
 * Created at 17/Out/2003 , 23:45:24
50
 *
51
 */
52
public class CoursesService implements IService
53
{
54
    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);
55
 
56
    RepositoryService repositoryService = new RepositoryService();
57
 
58
 
1505 jmachado 59
    /**
60
     * Servico e subservico para termos acesso as variaveis de controlo
61
     * @param id
62
     * @param initUnits
63
     * @return
64
     * @throws ServiceException
65
     */
66
    public CourseView loadCourse(long id, boolean initUnits)
67
            throws ServiceException
214 jmachado 68
    {
1505 jmachado 69
        return loadCourse(id,initUnits,false);
70
    }
71
    public CourseView loadCourseAndStudiesPlans(long id, boolean initUnits)
72
            throws ServiceException
73
    {
74
        return loadCourse(id,initUnits,true);
75
    }
76
 
77
 
78
    private CourseView loadCourse(long id, boolean initUnits,boolean loadStudiesPlans) throws ServiceException
79
    {
214 jmachado 80
        Course c = DaoFactory.getCourseDaoImpl().get(id);
81
 
82
        if(c != null)
83
        {
1505 jmachado 84
            return getCourseView(initUnits, c,loadStudiesPlans);
214 jmachado 85
        }
86
        return null;
87
    }
88
 
1505 jmachado 89
    /**
90
     * Servico e subservico para termos acesso as variaveis de controlo
91
     * @param code
92
     * @param initUnits
93
     * @return
94
     * @throws ServiceException
95
     */
96
 
97
    public CourseView loadCourseByCode(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits) throws ServiceException
345 jmachado 98
    {
1505 jmachado 99
        return loadCourseByCode(code,initUnits,false);
345 jmachado 100
    }
1505 jmachado 101
    public CourseView loadCourseByCodeAndStudiesPlans(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits) throws ServiceException
102
    {
103
        return loadCourseByCode(code,initUnits,true);
104
    }
345 jmachado 105
 
1505 jmachado 106
 
107
    private CourseView loadCourseByCode(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits,boolean loadStudiesPlans) throws ServiceException
214 jmachado 108
    {
444 jmachado 109
        try{
110
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
111
            if(c != null)
214 jmachado 112
            {
1505 jmachado 113
                return getCourseView(initUnits, c, loadStudiesPlans);
214 jmachado 114
            }
115
        }
444 jmachado 116
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
117
        {
118
            logger.error(e + " loading code:" + code,e);
119
            throw new ServiceException("loading code: " + code  + " - " + e.toString(),e);
120
        }
214 jmachado 121
        return null;
122
    }
123
 
1505 jmachado 124
    /**
125
     * Carrega efetivamente o curso nos servicos load e load by code
126
     * @param initUnits
127
     * @param c
128
     * @return
129
     */
130
 
131
    private CourseView getCourseView(boolean initUnits, Course c,boolean loadStudiesPlans) {
132
        CourseView cV = new CourseView(c,initUnits);
133
            /*
134
            * todo Parte antig antigo XML do plano de estudos para remover futuramente*/
135
        if(c.getStudiesPlan() != null)
136
        {
137
            RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
138
            cV.setStudiesPlan(repositoryFile);
139
        }
140
        if(loadStudiesPlans && c.getStudiesPlans() != null && c.getStudiesPlans().size() > 0)
141
        {
142
            for(CourseStudiesPlan sp : c.getStudiesPlans())
143
            {
144
                sp.getVersion();
145
                cV.getCourseStudiesPlans().add(sp);
146
            }
147
        }
148
 
149
        return cV;
150
    }
151
 
152
    public List<String> loadImportYears(UserSession userSession) throws ServiceException
153
    {
154
        List<String> importYears = DaoFactory.getCourseDaoImpl().loadImportYears();
155
        List<String> imStrings = new ArrayList<String>();
156
        for(1.5.0/docs/api/java/lang/String.html">String importYear: importYears)
157
        {
158
            imStrings.add(importYear);
159
        }
160
        return imStrings;
161
    }
162
 
163
 
164
 
214 jmachado 165
    public CourseView submitCourse(CourseView courseView,
166
                                   5+0%2Fdocs%2Fapi+InputStream">InputStream stream,
167
                                   1.5.0/docs/api/java/lang/String.html">String name,
168
                                   int size,
169
                                   1.5.0/docs/api/java/lang/String.html">String contentType,
1496 jmachado 170
                                   UserSession userSession) throws ServiceException, JAXBException, TransformationException, 1.5.0/docs/api/java/io/IOException.html">IOException {
214 jmachado 171
        Course c;
172
        if(courseView.getId() > 0)
444 jmachado 173
        {
214 jmachado 174
            c = DaoFactory.getCourseDaoImpl().get(courseView.getId());
444 jmachado 175
        }
214 jmachado 176
        else
177
        {
444 jmachado 178
            c = DaoFactory.getCourseDaoImpl().findCourseByCodeAndYear(courseView.getCode(),courseView.getImportYear());
179
            if(c != null)
180
                throw new AlreadyExistsException(AlreadyExistsException.ALREADY_EXISTS_COURSE);      
214 jmachado 181
            c = DomainObjectFactory.createCourseImpl();
182
            DaoFactory.getCourseDaoImpl().save(c);
183
        }
184
 
248 jmachado 185
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
186
 
1505 jmachado 187
        //Stream que pode vir do upload da UIde Admin de Cursos
1496 jmachado 188
        htmlTrasformationResult = uploadStudiesPlan(stream, name, size, contentType, userSession, c,false,null);
189
        courseView.persistViewInObject(c);
190
        CourseView cv = loadCourse(c.getId(),false);
191
        cv.setHtmlResult(htmlTrasformationResult);
192
 
193
        /**
194
         * New## generating course json
195
         */
196
        generateCourseJson(c);
197
 
198
        return cv;
199
    }
200
 
201
    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 {
202
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
1505 jmachado 203
        //APENAS NO CASO DO AMDIN FAZER UPLOAD DE UM XML
214 jmachado 204
        if(stream != null && size > 0)
205
        {
268 jmachado 206
            1.5.0/docs/api/java/lang/String.html">String extension = FilesUtils.getExtension(name);
207
            if(c.getStudiesPlan() == null)
208
            {
332 jmachado 209
                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);
268 jmachado 210
                c.setStudiesPlan(identifier);
211
            }
212
            else
213
            {
214
                repositoryService.updateRepositoryFile(c.getStudiesPlan(), stream, contentType, extension, size, name, "course.studies.plan " + c.getName(), ResourceAccessControlEnum.publicDomain);
215
            }
1496 jmachado 216
            htmlTrasformationResult = generateHtmlCache(userSession, c);
217
            //####New#### Generating XML with JaxB
1505 jmachado 218
            //ISTO SO É CHAMADO NO CASO DE SE FAZER UPLOAD DE UM NOVO PLANO PELO MECANISMO ANTIGO
219
            generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, c, forceUrlFichas, systemUrl);
1496 jmachado 220
        }
221
        return htmlTrasformationResult;
222
    }
223
 
1505 jmachado 224
 
225
 
1496 jmachado 226
    private void generateCourseJson(Course cAux) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
227
        CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
228
 
229
        if(c.getValidationRole() != null && c.getValidationRole().trim().length() > 0)
230
        {
231
            List<Teacher> courseComissionProxys = DaoFactory.getUserDaoImpl().loadRoleTeachers(c.getValidationRole());
232
            List<Teacher> courseComission = new ArrayList<Teacher>();
233
            for(Teacher t: courseComissionProxys)
248 jmachado 234
            {
1496 jmachado 235
                courseComission.add(DaoFactory.getTeacherDaoImpl().narrow(t));
248 jmachado 236
            }
1496 jmachado 237
            c.setCourseComission(courseComission);
238
        }
239
        //Getting Coordinator from proxy
240
        Teacher t = c.getCoordinator();
1500 jmachado 241
        if(t != null)
242
            t.getName();
243
        else
244
        {
245
            logger.warn("Course does not have coordinator");
246
        }
1496 jmachado 247
 
248
        1.5.0/docs/api/java/lang/String.html">String jsonCourse = getGensonCourse().serialize(c);
249
        c.setJson(jsonCourse);
250
    }
251
 
252
    private 1.5.0/docs/api/java/lang/String.html">String generateHtmlCache(UserSession userSession, Course c) {
253
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
254
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
255
        stream = repositoryFile.getInput();
256
        try
257
        {
258
            5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(stream);
259
            Map<String,Object> parameters = new HashMap<String,Object>();
260
            parameters.put("COURSE_SIGES_CODE",c.getCode());
261
            1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.styleDocument(dom, Globals.TEMPLATE_COURSE_XSL_PATH,parameters);
262
            c.setCacheWebDocument(html);
263
        }
264
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
265
        {
266
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
267
            1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter printWriter = new 1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter(writer);
268
            e.printStackTrace(printWriter);
269
            htmlTrasformationResult = "<div class=\"error\"><pre>" + e.toString() + "\n" + printWriter.toString() + "</pre></div>";
270
            printWriter.close();
271
        }
272
        try
273
        {
274
            stream.close();
275
        }
276
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
277
        {
278
            logger.error(e,e);
279
        }
280
        return htmlTrasformationResult;
281
    }
282
 
283
    /**
284
     * ##NEW METHOD###
285
     * Gera o XML normalizado para o JAXB a partir do XML importado do XML do plano XML quese usou no upload
286
     * para garantir que está bem formado
287
     * @param userSession
288
     * @param c
289
     * @return
290
     * @throws JAXBException if XML is not weel formed
291
     */
1505 jmachado 292
    private void generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(UserSession userSession, Course c, boolean forceFichaCurricularUrlSet, 1.5.0/docs/api/java/lang/String.html">String systemUrlForUnitPrograms) throws JAXBException, TransformationException
1496 jmachado 293
    {
294
        CourseStudiesPlan courseStudiesPlan;
1500 jmachado 295
        if(c.getStudiesPlan() == null || c.getStudiesPlan().trim().length() == 0)
296
        {
1505 jmachado 297
            //ESTE É O STREAM DO PLANO DE UPLOAD
1500 jmachado 298
            logger.warn("Course does not have studies plan XML file stream to use in update");
299
            return;
300
        }
1496 jmachado 301
 
302
        if(c.getStudiesPlans() == null || c.getStudiesPlans().size() == 0)
303
        {
304
            logger.info("Generating first study plan");
305
            courseStudiesPlan = DomainObjectFactory.createCourseStudiesPlanImpl();
306
            courseStudiesPlan.setVersion(1);
307
            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());
308
            courseStudiesPlan.setCourse(c);
309
            if(c.getStudiesPlans() == null)
310
                c.setStudiesPlans(new HashSet<CourseStudiesPlan>());
311
            c.getStudiesPlans().add(courseStudiesPlan);
312
            DaoFactory.getCourseStudiesPlanDaoImpl().save(courseStudiesPlan);
313
        }
314
        else
315
        {
316
            courseStudiesPlan = c.getStudiesPlans().iterator().next();
317
            logger.info("Updating Study Plan version " + courseStudiesPlan.getVersion());
318
        }
319
 
320
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;
321
        IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
1502 jmachado 322
        long lastVersion = repositoryService.loadView(c.getStudiesPlan()).getLastVersion().getId();
1514 jmachado 323
        //stream = repositoryFile.getInput();
1503 jmachado 324
        //TODO TIRAR
325
        //JUST FOR DEBUG
1514 jmachado 326
       /* try {
1503 jmachado 327
            System.out.println(StreamsUtils.readString(stream));
328
            stream.close();
329
        } catch (IOException e) {
330
            e.printStackTrace();
1514 jmachado 331
        }*/
1503 jmachado 332
        repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
333
        stream = repositoryFile.getInput();
1496 jmachado 334
 
335
        try {
336
            JAXBContext jc = JAXBContext.newInstance(Curso.class);
337
            Unmarshaller unmarshaller = jc.createUnmarshaller();
1503 jmachado 338
            //Just in case lets update SigesCode
1496 jmachado 339
            Curso curso = (Curso) unmarshaller.unmarshal(stream);
1503 jmachado 340
            curso.setSiges(c.getCode());
1505 jmachado 341
            curso.setNome(c.getName());
342
            curso.setDep(c.getArea());
1496 jmachado 343
 
1505 jmachado 344
            //##NOVO PARA GERAR LINK SE NAO EXISTIR
345
            generateAutoUrlFichasCurriculares(curso,systemUrlForUnitPrograms,forceFichaCurricularUrlSet);
346
 
1496 jmachado 347
            Marshaller marshaller = jc.createMarshaller();
348
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
349
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter sw = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
350
            marshaller.marshal(curso, sw);
351
            //SETTING XML in COURSE STUDIES PLAN
352
            courseStudiesPlan.setXml(sw.toString());
1505 jmachado 353
 
354
 
355
            1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(curso);
1496 jmachado 356
            //SETTING JSON in COURSE STUDIES PLAN
357
            courseStudiesPlan.setJson(json);
358
 
359
        } catch (JAXBException e) {
360
            logger.error(e,e);
1502 jmachado 361
            1.5.0/docs/api/java/lang/System.html">System.out.print("check XML for possible errors for repositoryStream:" + c.getStudiesPlan() + " file version: " + lastVersion);
1496 jmachado 362
            throw e;
363
        } catch (TransformationException e) {
364
            logger.error(e, e);
365
            throw e;
366
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
367
            e.printStackTrace();
368
        }
369
        try
370
        {
371
            stream.close();
372
        }
373
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
374
        {
375
            logger.error(e,e);
376
        }
377
    }
378
 
1505 jmachado 379
 
1506 jmachado 380
    /**
381
     * Apenas é chamado quando se tenta injectar um programa a partir de um upload que foi feito
382
     * pelo user ou pela sincronização remota
383
     * @param curso
384
     * @param systemUrl
385
     * @param force
386
     */
1496 jmachado 387
    private void generateAutoUrlFichasCurriculares(Curso curso,1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean force)
388
    {
389
        for(Curso.Semestre s :curso.getSemestre())
390
        {
391
            for(Curso.Semestre.Perfil p :s.getPerfil())
248 jmachado 392
            {
1496 jmachado 393
                for(UnidadeType unidadeType : p.getUnidade())
394
                {
395
                    generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
396
                }
248 jmachado 397
            }
1496 jmachado 398
            for(UnidadeType unidadeType : s.getUnidade())
214 jmachado 399
            {
1496 jmachado 400
                generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
214 jmachado 401
            }
402
        }
403
    }
404
 
1496 jmachado 405
    private void generateAutoUrlUnidade(UnidadeType unidadeType,1.5.0/docs/api/java/lang/String.html">String systemUrl,Curso curso,Curso.Semestre semestre,boolean force)
406
    {
407
        if(force || unidadeType.getUrlFichaCurricular() == null || unidadeType.getUrlFichaCurricular().trim().length()==0)
408
        {
409
            logger.info("GENERATING FICHA CURRICULAR URL For " + unidadeType.getNome());
410
            1.5.0/docs/api/java/lang/String.html">String url = systemUrl != null ? systemUrl : "";
1504 jmachado 411
            if(!url.endsWith("/"))
1496 jmachado 412
                url = url + "/";
1504 jmachado 413
 
1505 jmachado 414
            //Nao fornece o ano pois o servico irá assumir o ultimo
1504 jmachado 415
            unidadeType.setUrlFichaCurricular(url + "startLoadCourseUnitProgramSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
416
            unidadeType.setUrlUnidadeCurricular(url + "startLoadCourseUnitSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
1496 jmachado 417
        }
418
    }
419
 
420
 
1505 jmachado 421
    private static Genson getGensonPlanoEstudos(){
1496 jmachado 422
        Genson genson = new Genson.Builder()
423
                .exclude("class")
1507 jmachado 424
                .exclude("siges", Curso.class)
425
                .exclude("nome",Curso.class)
1534 jmachado 426
                .exclude("codigoPlanoSiges",Curso.class)
427
                .exclude("anoPlanoSiges",Curso.class)
428
                .exclude("descPlanoSiges",Curso.class)
1505 jmachado 429
                .exclude("dep")
1507 jmachado 430
                .exclude("removed",UnidadeType.class)
1517 jmachado 431
                .exclude("perfilId",Curso.Semestre.Perfil.class)
432
                .exclude("semestreId",Curso.Semestre.class)
1496 jmachado 433
                .create();
434
        return genson;
435
    }
436
 
437
 
438
 
439
    private static Genson getGensonCourse(){
440
        Genson genson = new Genson.Builder()
441
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
442
                .setUseFields(false)
443
                .setUseGettersAndSetters(true)
444
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
445
                .exclude("admin")
446
                .exclude("autoBlock")
447
                .exclude("autoBlockMode")
448
                .exclude("manualBlock")
449
                .exclude("newUser")
450
                .exclude("student")
451
                .exclude("superuser")
452
                .exclude("superuserOrAdmin")
453
                .exclude("teacher")
454
                .exclude("unitCheck")
455
                .exclude("id")
456
 
457
/*              .exclude(Course.class)
458
                .exclude(CourseImpl.class)
459
                .exclude(GenericUser.class)
460
                .exclude(User.class)
461
                .exclude(UserImpl.class)
462
                .exclude(Teacher.class)
463
                .exclude(TeacherImpl.class)
464
                .exclude(SigesUser.class)
465
                .exclude(SigesUserImpl.class)
466
                .exclude(GenericUser.class)
467
                .exclude(GenericUserImpl.class)
468
*/
469
                .exclude("id", Course.class)
1505 jmachado 470
                .exclude("status", Course.class)
1521 jmachado 471
                .exclude("showStudiesPlan", Course.class)
1496 jmachado 472
                .include("degreeForJsonApi", CourseImpl.class)
473
                .include("schoolForJsonApi", CourseImpl.class)
474
                .include("statusForJsonApi", CourseImpl.class)
475
 
476
                .include("name", Course.class)
1505 jmachado 477
                .include("nameEn", Course.class)
478
                .include("nameEs", Course.class)
479
                .include("nameFr", Course.class)
480
                .include("department", Course.class)
481
                .exclude("active", CourseDepartment.class)
482
                .include("sigla", CourseDepartment.class)
483
                .include("name", CourseDepartment.class)
484
                .include("nameEn", CourseDepartment.class)
485
                .include("nameEs", CourseDepartment.class)
486
                .include("nameFr", CourseDepartment.class)
1496 jmachado 487
                .include("code", Course.class)
1500 jmachado 488
                .include("validationRole", Course.class)
489
 
1496 jmachado 490
                .include("courseComission", CourseImpl.class)
491
 
492
                .include("name", GenericUser.class)
493
                .include("email", GenericUser.class)
494
                .include("sigesCode", SigesUser.class)
495
                .include("coordinator", Course.class)
496
                .create();
497
 
498
        return genson;
499
    }
500
 
501
 
502
 
214 jmachado 503
    public List<CourseView> loadCourses() throws ServiceException
504
    {
505
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
506
        List<CourseView> courseViews = new ArrayList<CourseView>();
507
        for(Course c: courses)
508
        {
509
            CourseView courseView = new CourseView(c);
510
            courseViews.add(courseView);
511
        }
512
        return courseViews;
513
    }
514
 
376 jmachado 515
    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
516
    {
1312 jmachado 517
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
518
    }
519
 
520
    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
521
    {
522
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
376 jmachado 523
        List<CourseView> courseViews = new ArrayList<CourseView>();
524
        for(Course c: courses)
525
        {
526
            CourseView courseView = new CourseView(c);
527
            courseViews.add(courseView);
528
        }
529
        return courseViews;
530
    }
531
 
249 jmachado 532
    public List<CourseView> loadCoursesImportYear() throws ServiceException
533
    {
995 jmachado 534
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
249 jmachado 535
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
536
        List<CourseView> courseViews = new ArrayList<CourseView>();
537
        for(Course c: courses)
538
        {
539
            CourseView courseView = new CourseView(c);
540
            courseViews.add(courseView);
541
        }
542
        return courseViews;
543
    }
417 jmachado 544
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
545
    {
995 jmachado 546
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
695 jmachado 547
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
417 jmachado 548
        List<CourseView> courseViews = new ArrayList<CourseView>();
549
        for(Course c: courses)
550
        {
551
            CourseView courseView = new CourseView(c);
552
            courseViews.add(courseView);
553
        }
554
        return courseViews;
555
    }
214 jmachado 556
 
790 jmachado 557
    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
558
    {
995 jmachado 559
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
790 jmachado 560
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
561
        List<CourseView> courseViews = new ArrayList<CourseView>();
562
        for(Course c: courses)
563
        {
564
            CourseView courseView = new CourseView(c);
565
            courseViews.add(courseView);
566
        }
567
        return courseViews;
568
    }
249 jmachado 569
 
1500 jmachado 570
 
571
 
572
    /** JSON API **/
573
    /**
574
     * @SERVICE@
575
     *
576
     * @param school
577
     * @param type
578
     * @return
579
     * @throws JSONException
580
     */
1496 jmachado 581
    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 {
582
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
583
        1.5.0/docs/api/java/lang/String.html">String degree = null;
584
        if(school != null && school.length() > 0)
585
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);
249 jmachado 586
 
1496 jmachado 587
        if(type != null && type.length() > 0)
588
            degree = ConfigProperties.getProperty("course.inverse." + type);
790 jmachado 589
 
1521 jmachado 590
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllShowStudiesPlanCoursesOrderByNameEvenWithoutCourseUnit(institutionalCode, degree);
1496 jmachado 591
        JSONObject coursesResponse = new JSONObject();
592
 
593
        JSONArray coursesArray = new JSONArray();
594
        for(Course cAux: courses)
595
        {
596
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
597
            JSONObject courseJson = new JSONObject();
598
            courseJson.put("name",c.getName());
599
            courseJson.put("code",c.getCode());
600
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
601
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
602
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
603
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
604
            coursesArray.put(courseJson);
605
 
606
        }
607
        coursesResponse.put("status","ok");
608
        coursesResponse.put("courses",coursesArray);
609
 
610
        return coursesResponse;
611
    }
612
 
1500 jmachado 613
    /**
614
     *
1505 jmachado 615
     * * Serviço invocado para obter o JSON de um curso
616
     * O JSON tem dois campos o courseInfo e o plano de estudos colocados separadamente
1500 jmachado 617
     *
1505 jmachado 618
     * Atenção o plano de estudos usado é o ultimo considerando o seu ID
619
     *  Nota: O plano de Estudos é uma classe persistente que tem apenas versão e descrição
620
     *  deverá ter como campo o XML e o JSON já gerados do plano de estudos que comporta
621
     *
1500 jmachado 622
     * @param code
623
     * @return
624
     * @throws JSONException
625
     * @throws IOException
626
     * @throws TransformationException
627
     * @throws JAXBException
628
     */
1498 jmachado 629
    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 {
1496 jmachado 630
 
631
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
632
 
633
 
634
        JSONObject coursesResponse = new JSONObject();
635
 
1498 jmachado 636
        if(course.getJson() == null)
637
        {
638
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
639
            new CoursesService().generateCourseJson(course);
640
        }
641
 
1496 jmachado 642
        if(course.getJson() != null)
643
        {
644
            JSONObject courseObj = new JSONObject(course.getJson());
645
            coursesResponse.put("courseInfo",courseObj);
1505 jmachado 646
            //Este caso apenas se dá se o plano nunca tiver sido editado ou sincronizado
647
            //Nesse caso o sistema irá tentar obtê-lo da stream do repositorio
1500 jmachado 648
            if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1498 jmachado 649
            {
1505 jmachado 650
                logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will try generate from studies plan OLD Stream");
1498 jmachado 651
                UserSession userSession = DomainObjectFactory.createUserSessionImpl();
652
                userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
1505 jmachado 653
                new CoursesService().generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1498 jmachado 654
            }
655
 
1505 jmachado 656
            if(course.getStudiesPlans() != null )
1496 jmachado 657
            {
658
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
1505 jmachado 659
                JSONObject studiesPlanObj;
660
                if(studiesPlan.getJson() != null)
661
                {
662
                    studiesPlanObj = new JSONObject(studiesPlan.getJson());
663
                    studiesPlanObj.put("version",studiesPlan.getVersion());
664
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
665
                }
666
                else
667
                {
668
                    studiesPlanObj = new JSONObject();
669
                    studiesPlanObj.put("fault","Zero contents for this version");
670
                    studiesPlanObj.put("version",studiesPlan.getVersion());
671
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
672
                }
1496 jmachado 673
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
1505 jmachado 674
 
1496 jmachado 675
            }
676
            else
677
            {
678
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
679
            }
680
        }
681
        else
682
        {
1505 jmachado 683
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE, PLEASE OPEN AND SAVE COURSE IN ADMINISTRATION");
1496 jmachado 684
        }
685
        return coursesResponse;
686
    }
687
 
1500 jmachado 688
    /**
689
     * @SERVICE@
690
     *
691
     * @param code
692
     * @return
693
     * @throws JSONException
694
     */
1502 jmachado 695
    public 1.5.0/docs/api/java/lang/String.html">String getCourseStudiesPlanXml(1.5.0/docs/api/java/lang/String.html">String code,1.5.0/docs/api/java/lang/String.html">String renew) throws JSONException {
1496 jmachado 696
 
697
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
1501 jmachado 698
 
1502 jmachado 699
        if(renew != null || course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1501 jmachado 700
        {
701
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
702
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
703
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
704
            try {
1505 jmachado 705
                generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1501 jmachado 706
            } catch (JAXBException e) {
707
                logger.error(e,e);
708
                return "<error>" + e.toString() + ". see log for details</error>";
709
            } catch (TransformationException e) {
710
                logger.error(e, e);
711
                return "<error>" + e.toString() + ". see log for details</error>";
712
            }
713
        }
714
 
1496 jmachado 715
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
716
        {
717
            return course.getStudiesPlans().iterator().next().getXml();
718
        }
719
        return "<error>Does not exixt</error>";
720
 
721
    }
722
 
723
 
1500 jmachado 724
    /**
725
     * @SERVICE@
726
     *
727
     * @param systemUrl
728
     * @param setActive
729
     * @return
730
     * @throws IOException
731
     * @throws JSONException
732
     * @throws TransformationException
733
     * @throws JAXBException
734
     */
1496 jmachado 735
 
1502 jmachado 736
    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,UserSession sess) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, TransformationException, JAXBException {
1496 jmachado 737
 
1497 jmachado 738
        1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
739
        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");
1496 jmachado 740
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
741
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
742
        JSONObject obj = new JSONObject(str);
743
        JSONArray courses = obj.getJSONArray("courses");
744
        for(int i = 0; i < courses.length();i++)
745
        {
1502 jmachado 746
            1.5.0/docs/api/java/lang/String.html">String code = "";
747
            try{
748
                JSONObject course = courses.getJSONObject(i);
749
                code = course.getString("code");
750
                Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
751
                if(c == null)
752
                {
753
                    1.5.0/docs/api/java/lang/String.html">String msg = "SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system";
754
                    log.append("<info>" + msg+"</info>");
755
                    logger.info(msg);
756
                }
757
                else
758
                {
759
                    1.5.0/docs/api/java/lang/String.html">String msg = "UPDATING - Course " + code + " " + course.getString("name") + " exist in this system";
760
                    log.append("<info>" + msg+"</info>");
761
                    logger.info(msg);
1500 jmachado 762
 
1505 jmachado 763
                    //#############UPDATING Course Comission Members
1516 jmachado 764
                    updateCourseComissionMembersAndCourseInfo(systemUrl, code, c);
1505 jmachado 765
 
1502 jmachado 766
                    //#############UPDATING STUDIES PLAN
767
                    updateStudiesPlanFromRemoteSystem(systemUrl, setActive, log, course, code, c);
1500 jmachado 768
 
1505 jmachado 769
 
1502 jmachado 770
                }
1500 jmachado 771
            }
1502 jmachado 772
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
773
            {
774
                logger.error("UPDATE COURSE: " + i + " code: " + code + " FAILED");
775
                logger.error(e,e);
776
            }
1500 jmachado 777
        }
778
        return log.toString();
779
 
780
    }
781
 
1505 jmachado 782
    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 {
783
        1.5.0/docs/api/java/lang/String.html">String msg;
784
        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 + "&renew=true").openStream();
785
        1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
786
        int len = studiesPlan.length();
787
        if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
788
        {
789
            msg = "Course " + code + " " + course.getString("name") + " dont has studies plan";
790
            log.append("<warn>" + msg+"</warn>");
791
            logger.warn(msg);
792
        }
793
        else
794
        {
795
            msg = "Found studies plan for "  + code + " " + course.getString("name") + " will update ";
796
            log.append("<info>" + msg+"</info>");
797
            logger.info(msg);
798
            if(setActive)
799
            {
800
                msg = "Setting course to active";
801
                log.append("<info>" + msg+"</info>");
802
                logger.info(msg);
803
                c.setStatus(true);
804
            }
805
            //System.out.println(studiesPlan);
806
            msg = "GENERATING COURSE JSON ....";
807
            log.append("<info>" + msg+"</info>");
808
            logger.info(msg);
809
            new CoursesService().generateCourseJson(c);
810
 
811
            msg="GENERATING COURSE STUDIES PLAN JSON ....";
812
            log.append("<info>" + msg+"</info>");
813
            logger.info(msg);
814
            stream.close();
815
            stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
816
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
817
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
818
            new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,systemUrl);
819
        }
820
    }
821
 
822
 
1500 jmachado 823
    /**
824
     * Update courseComission Members
825
     * @param systemUrl
826
     * @param code
827
     * @param c
828
     * @throws IOException
829
     * @throws JSONException
830
     */
1516 jmachado 831
    private void updateCourseComissionMembersAndCourseInfo(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
832
    {
833
 
1500 jmachado 834
        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);
835
        5+0%2Fdocs%2Fapi+InputStream">InputStream isCourseDetails = urlCourseDetails.openStream();
836
        1.5.0/docs/api/java/lang/String.html">String strCourseDetails = StreamsUtils.readString(isCourseDetails);
837
        JSONObject objCourseDetails = new JSONObject(strCourseDetails);
1516 jmachado 838
 
839
        //DEPARTMENT
840
        JSONObject department = objCourseDetails.getJSONObject("courseInfo").getJSONObject("department");
841
        if(department != null)
842
        {
843
            1.5.0/docs/api/java/lang/String.html">String sigla = department.getString("sigla");
844
            if(sigla != null)
845
            {
846
                CourseDepartment department1 =  DaoFactory.getCourseDepartmentDaoImpl().findBySigla(sigla);
847
                if(department1 != null)
848
                {
849
                    c.setDepartment(department1);
850
                }
851
            }
852
        }
853
 
854
 
1500 jmachado 855
        1.5.0/docs/api/java/lang/String.html">String validationRole = objCourseDetails.getJSONObject("courseInfo").getString("validationRole");
856
 
1516 jmachado 857
 
858
 
859
 
1500 jmachado 860
        if(validationRole == null)
861
        {
862
            logger.info("validationRole is not defined");
863
        }
864
        else
865
        {
866
            logger.info("found validationRole: " + validationRole);
867
            c.setValidationRole(validationRole);
868
 
869
            JSONObject coordinator = objCourseDetails.getJSONObject("courseInfo").getJSONObject("coordinator");
870
            JSONArray courseComission = objCourseDetails.getJSONObject("courseInfo").getJSONArray("courseComission");
871
 
872
            Teacher coordinatorPersistent = findPersonFromCourseDetails(coordinator);
873
            if(coordinatorPersistent == null)
874
            {
875
                logger.warn("Coordinator does not exist in this system ");
876
            }
877
            else
878
            {
879
                c.setCoordinator(coordinatorPersistent);
880
            }
1516 jmachado 881
 
882
            List<User> users = DaoFactory.getUserDaoImpl().loadRoleUsers(validationRole);
883
            logger.info("Encontrados " + users.size() + " docentes com o papel de comissao " + validationRole + " vai remover");
884
            for(User u: users)
885
            {
886
                logger.info("Removendo role a " + u.getName());
887
                u.removeRole(validationRole);
888
            }
889
 
1500 jmachado 890
            for(int j = 0 ; j < courseComission.length(); j++)
891
            {
892
                JSONObject memberComission = courseComission.getJSONObject(j);
893
                Teacher memberPersistent = findPersonFromCourseDetails(memberComission);
894
                if(memberPersistent == null)
1496 jmachado 895
                {
1500 jmachado 896
                    logger.info("Member does not exist in this system ");
1496 jmachado 897
                }
898
                else
899
                {
1500 jmachado 900
                    logger.info("Adding role of course comission member");
901
                    if(!memberPersistent.hasRole(validationRole))
1497 jmachado 902
                    {
1500 jmachado 903
                        memberPersistent.addRole(validationRole);
1497 jmachado 904
                    }
1500 jmachado 905
                }
1496 jmachado 906
            }
907
        }
1500 jmachado 908
    }
1497 jmachado 909
 
1500 jmachado 910
    private Teacher findPersonFromCourseDetails(JSONObject coordinator) {
911
        int code;
912
        try {
913
            if(coordinator.has("sigesCode"))
914
            {
915
                code = coordinator.getInt("sigesCode");
916
            }
917
            else
918
            {
919
                logger.warn("there is no sigesCode for this person " + coordinator.toString());
920
                return null;
921
            }
922
        } catch (JSONException e){
923
            return null;
924
        } catch (1.5.0/docs/api/java/lang/NumberFormatException.html">NumberFormatException e){
925
            return null;
926
        }
927
        return DaoFactory.getTeacherDaoImpl().loadBySigesCode(code);
1496 jmachado 928
    }
929
 
1505 jmachado 930
 
931
 
932
    /*
933
     * Studies Plans Administration Services
934
     *
935
     */
936
    public void addNewStudiesPlan(long courseId,CourseStudiesPlan studiesPlan,UserSession session)
937
    {
938
        Course c = DaoFactory.getCourseDaoImpl().load(courseId);
939
        studiesPlan.setCourse(c);
940
        c.getStudiesPlans().add(studiesPlan);
941
        DaoFactory.getCourseStudiesPlanDaoImpl().save(studiesPlan);
942
    }
943
 
1516 jmachado 944
    public CourseStudiesPlanImpl cloneVersionFrom(long sourcePlanId, long targetPlanId, long courseId, UserSession session)
1505 jmachado 945
    {
946
        Course course = DaoFactory.getCourseDaoImpl().load(courseId);
947
        CourseStudiesPlan source = null;
948
        CourseStudiesPlan target = null;
949
        for(CourseStudiesPlan plan: course.getStudiesPlans())
1500 jmachado 950
        {
1505 jmachado 951
            if(plan.getId() == sourcePlanId)
952
                source = plan;
953
            else if(plan.getId() == targetPlanId)
954
                target = plan;
1500 jmachado 955
        }
1505 jmachado 956
        target.setXml(source.getXml());
957
        target.setJson(source.getJson());
1516 jmachado 958
        return (CourseStudiesPlanImpl) DaoFactory.getCourseStudiesPlanDaoImpl().narrow(target);
1505 jmachado 959
    }
1507 jmachado 960
 
1505 jmachado 961
    public Curso loadCursoPlanoFromXml(1.5.0/docs/api/java/lang/String.html">String xml)
962
    {
963
        try {
964
            if(xml != null)
1500 jmachado 965
            {
1505 jmachado 966
                JAXBContext jc = JAXBContext.newInstance(Curso.class);
967
                Unmarshaller unmarshaller = jc.createUnmarshaller();
968
                Curso curso = (Curso) unmarshaller.unmarshal(new 1.5.0/docs/api/java/io/StringReader.html">StringReader(xml));
969
                return curso;
1500 jmachado 970
            }
1505 jmachado 971
            return null;
972
        } catch (JAXBException e) {
973
            logger.error(e,e);
974
            return null;
975
        }
976
    }
1496 jmachado 977
 
1505 jmachado 978
    /**
979
     * Persist the edited studies plan
980
     * Updates studiesPlanVersion
981
     * Updates studiesPlanVersionDescription
982
     * Updates PlanoEstudos XML and JSON
983
     *
984
     * @param courseId
985
     * @param coursePlanId
986
     * @param planoEditado
987
     * @param courseStudiesPlanEditado
988
     * @return
989
     */
990
    public Course savePlanoEstudosEditado(long courseId, long coursePlanId, Curso planoEditado, CourseStudiesPlan courseStudiesPlanEditado,UserSession session)
991
    {
992
        try {
993
            Course course = DaoFactory.getCourseDaoImpl().load(courseId);
994
 
995
            for(CourseStudiesPlan courseStudiesPlanPersistente: course.getStudiesPlans())
996
            {
997
                if(courseStudiesPlanPersistente.getId() == coursePlanId)
998
                {
999
                    courseStudiesPlanPersistente.setVersion(courseStudiesPlanEditado.getVersion());
1000
                    courseStudiesPlanPersistente.setVersionDescription(courseStudiesPlanEditado.getVersionDescription());
1001
 
1507 jmachado 1002
                    //REMOVED UNIDADES TO REMOVE
1003
                    for(Curso.Semestre semestre:planoEditado.getSemestre())
1004
                    {
1005
                        Iterator<UnidadeType> uIter = semestre.getUnidade().iterator();
1006
                        while(uIter.hasNext())
1007
                        {
1008
                            UnidadeType unidade = uIter.next();
1009
                            if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1010
                                uIter.remove();
1011
                        }
1012
                        for(Curso.Semestre.Perfil perfil: semestre.getPerfil())
1013
                        {
1014
                            Iterator<UnidadeType> uIter2 = perfil.getUnidade().iterator();
1015
                            while(uIter2.hasNext())
1016
                            {
1017
                                UnidadeType unidade = uIter2.next();
1018
                                if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1019
                                    uIter2.remove();
1020
                            }
1021
                        }
1022
                    }
1505 jmachado 1023
                    //Garante-se mas depois não vai para o JSON
1024
                    planoEditado.setSiges(course.getCode());//GARANTIR QUE O CODIGO SIGEST ESTA CORRECTO
1025
                    planoEditado.setNome(course.getName());
1026
                    planoEditado.setDep(course.getArea());
1027
                    //planoEditado.setDepDesc("");
1028
                    //planoEditado.setDepDescEn("");
1029
                    //planoEditado.setDepDescEs("");
1030
                    //planoEditado.setDepDescFr("");
1031
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1032
                    Marshaller marshaller = jc.createMarshaller();
1033
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1034
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1035
                    marshaller.marshal(planoEditado,xml);
1036
 
1037
                    courseStudiesPlanPersistente.setXml(xml.toString());
1038
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(planoEditado);
1039
                    //SETTING JSON in COURSE STUDIES PLAN
1040
                    courseStudiesPlanPersistente.setJson(json);
1041
                    break;
1042
                }
1043
            }
1044
            return course;
1045
        } catch (JAXBException e) {
1046
            logger.error(e,e);
1047
            return null;
1048
        } catch (TransformationException e) {
1049
            logger.error(e,e);
1050
            return null;
1051
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1052
            logger.error(e,e);
1053
            return null;
1500 jmachado 1054
        }
1055
    }
1496 jmachado 1056
 
1507 jmachado 1057
    public void generateFreshJsonPlanosEstudosFromXml(UserSession session)
1058
    {
1059
        List<CourseStudiesPlan> coursePlans = DaoFactory.getCourseStudiesPlanDaoImpl().findAll();
1060
        for(CourseStudiesPlan courseStudiesPlanPersistente: coursePlans)
1061
        {
1062
            try
1063
            {
1064
                logger.info("Generating JSON for " + courseStudiesPlanPersistente.getCourse().getName() + " version: " + courseStudiesPlanPersistente.getVersion());
1065
                Curso cursoPlano = loadCursoPlanoFromXml(courseStudiesPlanPersistente.getXml());
1518 jmachado 1066
                if(cursoPlano != null)
1067
                {
1068
                    for(Curso.Semestre s : cursoPlano.getSemestre())
1069
                    {
1070
                        SemestreImpl.setDescriptionsDefaults(s);
1071
                    }
1072
                    //send to XML again
1073
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1074
                    Marshaller marshaller = jc.createMarshaller();
1075
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1076
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1077
                    marshaller.marshal(cursoPlano,xml);
1078
                    courseStudiesPlanPersistente.setXml(xml.toString());
1079
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(cursoPlano);
1080
                    //SETTING JSON in COURSE STUDIES PLAN
1081
                    courseStudiesPlanPersistente.setJson(json);
1082
                }
1083
 
1507 jmachado 1084
            }
1085
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
1086
            {
1087
                logger.error(e,e);
1088
            }
1089
        }
1514 jmachado 1090
 
1091
        logger.info("GENERATING JSON FOR CLASS COURSE");
1092
        for(Course course: DaoFactory.getCourseDaoImpl().findAll())
1093
        {
1094
            try {
1095
                logger.info("generating json for course: " + course.getName() + " (" + course.getCode() + ")");
1096
                generateCourseJson(course);
1097
            } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1098
                logger.error(e,e);
1099
            } catch (TransformationException e) {
1100
                logger.error(e, e);
1101
            }
1102
        }
1507 jmachado 1103
    }
1500 jmachado 1104
 
1505 jmachado 1105
 
1507 jmachado 1106
 
1505 jmachado 1107
    public List<CourseDepartment> loadDepartments()
1108
    {
1109
        List<CourseDepartment> departments = DaoFactory.getCourseDepartmentDaoImpl().findAll();
1110
        for(CourseDepartment dep: departments)
1111
            dep.getName();
1112
        return departments;
1507 jmachado 1113
 
1505 jmachado 1114
    }
1115
 
1516 jmachado 1116
 
1117
    public Teacher addTeacherCommission(1.5.0/docs/api/java/lang/String.html">String teacherId,1.5.0/docs/api/java/lang/String.html">String courseId, UserSession session)
1118
    {
1119
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1120
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1121
        t.addRole(course.getValidationRole());
1122
        return t;
1123
    }
1124
 
1125
    public Teacher removeTeacherCommission(1.5.0/docs/api/java/lang/String.html">String teacherId,1.5.0/docs/api/java/lang/String.html">String courseId, UserSession session)
1126
    {
1127
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1128
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1129
        t.removeRole(course.getValidationRole());
1130
        return t;
1131
    }
1132
 
1507 jmachado 1133
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args)
1134
    {
1135
        AbstractDao.getCurrentSession().beginTransaction();
1136
        new CoursesService().generateFreshJsonPlanosEstudosFromXml(null);
1137
        AbstractDao.getCurrentSession().getTransaction().commit();
1138
    }
1505 jmachado 1139
 
1534 jmachado 1140
    public StudiesPlanImporter importStudiesPlanVersionFromFile(5+0%2Fdocs%2Fapi+InputStream">InputStream stream, UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException
1141
    {
1142
        StudiesPlanImporter importer = new StudiesPlanImporter();
1143
        importer.parseFile(stream);
1144
        1.5.0/docs/api/java/lang/System.html">System.out.println(importer.getLog());
1145
        return importer;
1146
    }
1507 jmachado 1147
 
1534 jmachado 1148
 
214 jmachado 1149
}