Subversion Repositories bacoAlunos

Rev

Rev 1518 | 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)
1505 jmachado 426
                .exclude("dep")
1507 jmachado 427
                .exclude("removed",UnidadeType.class)
1517 jmachado 428
                .exclude("perfilId",Curso.Semestre.Perfil.class)
429
                .exclude("semestreId",Curso.Semestre.class)
1496 jmachado 430
                .create();
431
        return genson;
432
    }
433
 
434
 
435
 
436
    private static Genson getGensonCourse(){
437
        Genson genson = new Genson.Builder()
438
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
439
                .setUseFields(false)
440
                .setUseGettersAndSetters(true)
441
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
442
                .exclude("admin")
443
                .exclude("autoBlock")
444
                .exclude("autoBlockMode")
445
                .exclude("manualBlock")
446
                .exclude("newUser")
447
                .exclude("student")
448
                .exclude("superuser")
449
                .exclude("superuserOrAdmin")
450
                .exclude("teacher")
451
                .exclude("unitCheck")
452
                .exclude("id")
453
 
454
/*              .exclude(Course.class)
455
                .exclude(CourseImpl.class)
456
                .exclude(GenericUser.class)
457
                .exclude(User.class)
458
                .exclude(UserImpl.class)
459
                .exclude(Teacher.class)
460
                .exclude(TeacherImpl.class)
461
                .exclude(SigesUser.class)
462
                .exclude(SigesUserImpl.class)
463
                .exclude(GenericUser.class)
464
                .exclude(GenericUserImpl.class)
465
*/
466
                .exclude("id", Course.class)
1505 jmachado 467
                .exclude("status", Course.class)
1521 jmachado 468
                .exclude("showStudiesPlan", Course.class)
1496 jmachado 469
                .include("degreeForJsonApi", CourseImpl.class)
470
                .include("schoolForJsonApi", CourseImpl.class)
471
                .include("statusForJsonApi", CourseImpl.class)
472
 
473
                .include("name", Course.class)
1505 jmachado 474
                .include("nameEn", Course.class)
475
                .include("nameEs", Course.class)
476
                .include("nameFr", Course.class)
477
                .include("department", Course.class)
478
                .exclude("active", CourseDepartment.class)
479
                .include("sigla", CourseDepartment.class)
480
                .include("name", CourseDepartment.class)
481
                .include("nameEn", CourseDepartment.class)
482
                .include("nameEs", CourseDepartment.class)
483
                .include("nameFr", CourseDepartment.class)
1496 jmachado 484
                .include("code", Course.class)
1500 jmachado 485
                .include("validationRole", Course.class)
486
 
1496 jmachado 487
                .include("courseComission", CourseImpl.class)
488
 
489
                .include("name", GenericUser.class)
490
                .include("email", GenericUser.class)
491
                .include("sigesCode", SigesUser.class)
492
                .include("coordinator", Course.class)
493
                .create();
494
 
495
        return genson;
496
    }
497
 
498
 
499
 
214 jmachado 500
    public List<CourseView> loadCourses() throws ServiceException
501
    {
502
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
503
        List<CourseView> courseViews = new ArrayList<CourseView>();
504
        for(Course c: courses)
505
        {
506
            CourseView courseView = new CourseView(c);
507
            courseViews.add(courseView);
508
        }
509
        return courseViews;
510
    }
511
 
376 jmachado 512
    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
513
    {
1312 jmachado 514
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
515
    }
516
 
517
    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
518
    {
519
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
376 jmachado 520
        List<CourseView> courseViews = new ArrayList<CourseView>();
521
        for(Course c: courses)
522
        {
523
            CourseView courseView = new CourseView(c);
524
            courseViews.add(courseView);
525
        }
526
        return courseViews;
527
    }
528
 
249 jmachado 529
    public List<CourseView> loadCoursesImportYear() throws ServiceException
530
    {
995 jmachado 531
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
249 jmachado 532
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
533
        List<CourseView> courseViews = new ArrayList<CourseView>();
534
        for(Course c: courses)
535
        {
536
            CourseView courseView = new CourseView(c);
537
            courseViews.add(courseView);
538
        }
539
        return courseViews;
540
    }
417 jmachado 541
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
542
    {
995 jmachado 543
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
695 jmachado 544
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
417 jmachado 545
        List<CourseView> courseViews = new ArrayList<CourseView>();
546
        for(Course c: courses)
547
        {
548
            CourseView courseView = new CourseView(c);
549
            courseViews.add(courseView);
550
        }
551
        return courseViews;
552
    }
214 jmachado 553
 
790 jmachado 554
    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
555
    {
995 jmachado 556
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
790 jmachado 557
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
558
        List<CourseView> courseViews = new ArrayList<CourseView>();
559
        for(Course c: courses)
560
        {
561
            CourseView courseView = new CourseView(c);
562
            courseViews.add(courseView);
563
        }
564
        return courseViews;
565
    }
249 jmachado 566
 
1500 jmachado 567
 
568
 
569
    /** JSON API **/
570
    /**
571
     * @SERVICE@
572
     *
573
     * @param school
574
     * @param type
575
     * @return
576
     * @throws JSONException
577
     */
1496 jmachado 578
    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 {
579
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
580
        1.5.0/docs/api/java/lang/String.html">String degree = null;
581
        if(school != null && school.length() > 0)
582
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);
249 jmachado 583
 
1496 jmachado 584
        if(type != null && type.length() > 0)
585
            degree = ConfigProperties.getProperty("course.inverse." + type);
790 jmachado 586
 
1521 jmachado 587
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllShowStudiesPlanCoursesOrderByNameEvenWithoutCourseUnit(institutionalCode, degree);
1496 jmachado 588
        JSONObject coursesResponse = new JSONObject();
589
 
590
        JSONArray coursesArray = new JSONArray();
591
        for(Course cAux: courses)
592
        {
593
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
594
            JSONObject courseJson = new JSONObject();
595
            courseJson.put("name",c.getName());
596
            courseJson.put("code",c.getCode());
597
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
598
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
599
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
600
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
601
            coursesArray.put(courseJson);
602
 
603
        }
604
        coursesResponse.put("status","ok");
605
        coursesResponse.put("courses",coursesArray);
606
 
607
        return coursesResponse;
608
    }
609
 
1500 jmachado 610
    /**
611
     *
1505 jmachado 612
     * * Serviço invocado para obter o JSON de um curso
613
     * O JSON tem dois campos o courseInfo e o plano de estudos colocados separadamente
1500 jmachado 614
     *
1505 jmachado 615
     * Atenção o plano de estudos usado é o ultimo considerando o seu ID
616
     *  Nota: O plano de Estudos é uma classe persistente que tem apenas versão e descrição
617
     *  deverá ter como campo o XML e o JSON já gerados do plano de estudos que comporta
618
     *
1500 jmachado 619
     * @param code
620
     * @return
621
     * @throws JSONException
622
     * @throws IOException
623
     * @throws TransformationException
624
     * @throws JAXBException
625
     */
1498 jmachado 626
    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 627
 
628
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
629
 
630
 
631
        JSONObject coursesResponse = new JSONObject();
632
 
1498 jmachado 633
        if(course.getJson() == null)
634
        {
635
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
636
            new CoursesService().generateCourseJson(course);
637
        }
638
 
1496 jmachado 639
        if(course.getJson() != null)
640
        {
641
            JSONObject courseObj = new JSONObject(course.getJson());
642
            coursesResponse.put("courseInfo",courseObj);
1505 jmachado 643
            //Este caso apenas se dá se o plano nunca tiver sido editado ou sincronizado
644
            //Nesse caso o sistema irá tentar obtê-lo da stream do repositorio
1500 jmachado 645
            if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1498 jmachado 646
            {
1505 jmachado 647
                logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will try generate from studies plan OLD Stream");
1498 jmachado 648
                UserSession userSession = DomainObjectFactory.createUserSessionImpl();
649
                userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
1505 jmachado 650
                new CoursesService().generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1498 jmachado 651
            }
652
 
1505 jmachado 653
            if(course.getStudiesPlans() != null )
1496 jmachado 654
            {
655
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
1505 jmachado 656
                JSONObject studiesPlanObj;
657
                if(studiesPlan.getJson() != null)
658
                {
659
                    studiesPlanObj = new JSONObject(studiesPlan.getJson());
660
                    studiesPlanObj.put("version",studiesPlan.getVersion());
661
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
662
                }
663
                else
664
                {
665
                    studiesPlanObj = new JSONObject();
666
                    studiesPlanObj.put("fault","Zero contents for this version");
667
                    studiesPlanObj.put("version",studiesPlan.getVersion());
668
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
669
                }
1496 jmachado 670
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
1505 jmachado 671
 
1496 jmachado 672
            }
673
            else
674
            {
675
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
676
            }
677
        }
678
        else
679
        {
1505 jmachado 680
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE, PLEASE OPEN AND SAVE COURSE IN ADMINISTRATION");
1496 jmachado 681
        }
682
        return coursesResponse;
683
    }
684
 
1500 jmachado 685
    /**
686
     * @SERVICE@
687
     *
688
     * @param code
689
     * @return
690
     * @throws JSONException
691
     */
1502 jmachado 692
    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 693
 
694
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
1501 jmachado 695
 
1502 jmachado 696
        if(renew != null || course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1501 jmachado 697
        {
698
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
699
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
700
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
701
            try {
1505 jmachado 702
                generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1501 jmachado 703
            } catch (JAXBException e) {
704
                logger.error(e,e);
705
                return "<error>" + e.toString() + ". see log for details</error>";
706
            } catch (TransformationException e) {
707
                logger.error(e, e);
708
                return "<error>" + e.toString() + ". see log for details</error>";
709
            }
710
        }
711
 
1496 jmachado 712
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
713
        {
714
            return course.getStudiesPlans().iterator().next().getXml();
715
        }
716
        return "<error>Does not exixt</error>";
717
 
718
    }
719
 
720
 
1500 jmachado 721
    /**
722
     * @SERVICE@
723
     *
724
     * @param systemUrl
725
     * @param setActive
726
     * @return
727
     * @throws IOException
728
     * @throws JSONException
729
     * @throws TransformationException
730
     * @throws JAXBException
731
     */
1496 jmachado 732
 
1502 jmachado 733
    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 734
 
1497 jmachado 735
        1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
736
        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 737
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
738
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
739
        JSONObject obj = new JSONObject(str);
740
        JSONArray courses = obj.getJSONArray("courses");
741
        for(int i = 0; i < courses.length();i++)
742
        {
1502 jmachado 743
            1.5.0/docs/api/java/lang/String.html">String code = "";
744
            try{
745
                JSONObject course = courses.getJSONObject(i);
746
                code = course.getString("code");
747
                Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
748
                if(c == null)
749
                {
750
                    1.5.0/docs/api/java/lang/String.html">String msg = "SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system";
751
                    log.append("<info>" + msg+"</info>");
752
                    logger.info(msg);
753
                }
754
                else
755
                {
756
                    1.5.0/docs/api/java/lang/String.html">String msg = "UPDATING - Course " + code + " " + course.getString("name") + " exist in this system";
757
                    log.append("<info>" + msg+"</info>");
758
                    logger.info(msg);
1500 jmachado 759
 
1505 jmachado 760
                    //#############UPDATING Course Comission Members
1516 jmachado 761
                    updateCourseComissionMembersAndCourseInfo(systemUrl, code, c);
1505 jmachado 762
 
1502 jmachado 763
                    //#############UPDATING STUDIES PLAN
764
                    updateStudiesPlanFromRemoteSystem(systemUrl, setActive, log, course, code, c);
1500 jmachado 765
 
1505 jmachado 766
 
1502 jmachado 767
                }
1500 jmachado 768
            }
1502 jmachado 769
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
770
            {
771
                logger.error("UPDATE COURSE: " + i + " code: " + code + " FAILED");
772
                logger.error(e,e);
773
            }
1500 jmachado 774
        }
775
        return log.toString();
776
 
777
    }
778
 
1505 jmachado 779
    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 {
780
        1.5.0/docs/api/java/lang/String.html">String msg;
781
        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();
782
        1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
783
        int len = studiesPlan.length();
784
        if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
785
        {
786
            msg = "Course " + code + " " + course.getString("name") + " dont has studies plan";
787
            log.append("<warn>" + msg+"</warn>");
788
            logger.warn(msg);
789
        }
790
        else
791
        {
792
            msg = "Found studies plan for "  + code + " " + course.getString("name") + " will update ";
793
            log.append("<info>" + msg+"</info>");
794
            logger.info(msg);
795
            if(setActive)
796
            {
797
                msg = "Setting course to active";
798
                log.append("<info>" + msg+"</info>");
799
                logger.info(msg);
800
                c.setStatus(true);
801
            }
802
            //System.out.println(studiesPlan);
803
            msg = "GENERATING COURSE JSON ....";
804
            log.append("<info>" + msg+"</info>");
805
            logger.info(msg);
806
            new CoursesService().generateCourseJson(c);
807
 
808
            msg="GENERATING COURSE STUDIES PLAN JSON ....";
809
            log.append("<info>" + msg+"</info>");
810
            logger.info(msg);
811
            stream.close();
812
            stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
813
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
814
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
815
            new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,systemUrl);
816
        }
817
    }
818
 
819
 
1500 jmachado 820
    /**
821
     * Update courseComission Members
822
     * @param systemUrl
823
     * @param code
824
     * @param c
825
     * @throws IOException
826
     * @throws JSONException
827
     */
1516 jmachado 828
    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
829
    {
830
 
1500 jmachado 831
        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);
832
        5+0%2Fdocs%2Fapi+InputStream">InputStream isCourseDetails = urlCourseDetails.openStream();
833
        1.5.0/docs/api/java/lang/String.html">String strCourseDetails = StreamsUtils.readString(isCourseDetails);
834
        JSONObject objCourseDetails = new JSONObject(strCourseDetails);
1516 jmachado 835
 
836
        //DEPARTMENT
837
        JSONObject department = objCourseDetails.getJSONObject("courseInfo").getJSONObject("department");
838
        if(department != null)
839
        {
840
            1.5.0/docs/api/java/lang/String.html">String sigla = department.getString("sigla");
841
            if(sigla != null)
842
            {
843
                CourseDepartment department1 =  DaoFactory.getCourseDepartmentDaoImpl().findBySigla(sigla);
844
                if(department1 != null)
845
                {
846
                    c.setDepartment(department1);
847
                }
848
            }
849
        }
850
 
851
 
1500 jmachado 852
        1.5.0/docs/api/java/lang/String.html">String validationRole = objCourseDetails.getJSONObject("courseInfo").getString("validationRole");
853
 
1516 jmachado 854
 
855
 
856
 
1500 jmachado 857
        if(validationRole == null)
858
        {
859
            logger.info("validationRole is not defined");
860
        }
861
        else
862
        {
863
            logger.info("found validationRole: " + validationRole);
864
            c.setValidationRole(validationRole);
865
 
866
            JSONObject coordinator = objCourseDetails.getJSONObject("courseInfo").getJSONObject("coordinator");
867
            JSONArray courseComission = objCourseDetails.getJSONObject("courseInfo").getJSONArray("courseComission");
868
 
869
            Teacher coordinatorPersistent = findPersonFromCourseDetails(coordinator);
870
            if(coordinatorPersistent == null)
871
            {
872
                logger.warn("Coordinator does not exist in this system ");
873
            }
874
            else
875
            {
876
                c.setCoordinator(coordinatorPersistent);
877
            }
1516 jmachado 878
 
879
            List<User> users = DaoFactory.getUserDaoImpl().loadRoleUsers(validationRole);
880
            logger.info("Encontrados " + users.size() + " docentes com o papel de comissao " + validationRole + " vai remover");
881
            for(User u: users)
882
            {
883
                logger.info("Removendo role a " + u.getName());
884
                u.removeRole(validationRole);
885
            }
886
 
1500 jmachado 887
            for(int j = 0 ; j < courseComission.length(); j++)
888
            {
889
                JSONObject memberComission = courseComission.getJSONObject(j);
890
                Teacher memberPersistent = findPersonFromCourseDetails(memberComission);
891
                if(memberPersistent == null)
1496 jmachado 892
                {
1500 jmachado 893
                    logger.info("Member does not exist in this system ");
1496 jmachado 894
                }
895
                else
896
                {
1500 jmachado 897
                    logger.info("Adding role of course comission member");
898
                    if(!memberPersistent.hasRole(validationRole))
1497 jmachado 899
                    {
1500 jmachado 900
                        memberPersistent.addRole(validationRole);
1497 jmachado 901
                    }
1500 jmachado 902
                }
1496 jmachado 903
            }
904
        }
1500 jmachado 905
    }
1497 jmachado 906
 
1500 jmachado 907
    private Teacher findPersonFromCourseDetails(JSONObject coordinator) {
908
        int code;
909
        try {
910
            if(coordinator.has("sigesCode"))
911
            {
912
                code = coordinator.getInt("sigesCode");
913
            }
914
            else
915
            {
916
                logger.warn("there is no sigesCode for this person " + coordinator.toString());
917
                return null;
918
            }
919
        } catch (JSONException e){
920
            return null;
921
        } catch (1.5.0/docs/api/java/lang/NumberFormatException.html">NumberFormatException e){
922
            return null;
923
        }
924
        return DaoFactory.getTeacherDaoImpl().loadBySigesCode(code);
1496 jmachado 925
    }
926
 
1505 jmachado 927
 
928
 
929
    /*
930
     * Studies Plans Administration Services
931
     *
932
     */
933
    public void addNewStudiesPlan(long courseId,CourseStudiesPlan studiesPlan,UserSession session)
934
    {
935
        Course c = DaoFactory.getCourseDaoImpl().load(courseId);
936
        studiesPlan.setCourse(c);
937
        c.getStudiesPlans().add(studiesPlan);
938
        DaoFactory.getCourseStudiesPlanDaoImpl().save(studiesPlan);
939
    }
940
 
1516 jmachado 941
    public CourseStudiesPlanImpl cloneVersionFrom(long sourcePlanId, long targetPlanId, long courseId, UserSession session)
1505 jmachado 942
    {
943
        Course course = DaoFactory.getCourseDaoImpl().load(courseId);
944
        CourseStudiesPlan source = null;
945
        CourseStudiesPlan target = null;
946
        for(CourseStudiesPlan plan: course.getStudiesPlans())
1500 jmachado 947
        {
1505 jmachado 948
            if(plan.getId() == sourcePlanId)
949
                source = plan;
950
            else if(plan.getId() == targetPlanId)
951
                target = plan;
1500 jmachado 952
        }
1505 jmachado 953
        target.setXml(source.getXml());
954
        target.setJson(source.getJson());
1516 jmachado 955
        return (CourseStudiesPlanImpl) DaoFactory.getCourseStudiesPlanDaoImpl().narrow(target);
1505 jmachado 956
    }
1507 jmachado 957
 
1505 jmachado 958
    public Curso loadCursoPlanoFromXml(1.5.0/docs/api/java/lang/String.html">String xml)
959
    {
960
        try {
961
            if(xml != null)
1500 jmachado 962
            {
1505 jmachado 963
                JAXBContext jc = JAXBContext.newInstance(Curso.class);
964
                Unmarshaller unmarshaller = jc.createUnmarshaller();
965
                Curso curso = (Curso) unmarshaller.unmarshal(new 1.5.0/docs/api/java/io/StringReader.html">StringReader(xml));
966
                return curso;
1500 jmachado 967
            }
1505 jmachado 968
            return null;
969
        } catch (JAXBException e) {
970
            logger.error(e,e);
971
            return null;
972
        }
973
    }
1496 jmachado 974
 
1505 jmachado 975
    /**
976
     * Persist the edited studies plan
977
     * Updates studiesPlanVersion
978
     * Updates studiesPlanVersionDescription
979
     * Updates PlanoEstudos XML and JSON
980
     *
981
     * @param courseId
982
     * @param coursePlanId
983
     * @param planoEditado
984
     * @param courseStudiesPlanEditado
985
     * @return
986
     */
987
    public Course savePlanoEstudosEditado(long courseId, long coursePlanId, Curso planoEditado, CourseStudiesPlan courseStudiesPlanEditado,UserSession session)
988
    {
989
        try {
990
            Course course = DaoFactory.getCourseDaoImpl().load(courseId);
991
 
992
            for(CourseStudiesPlan courseStudiesPlanPersistente: course.getStudiesPlans())
993
            {
994
                if(courseStudiesPlanPersistente.getId() == coursePlanId)
995
                {
996
                    courseStudiesPlanPersistente.setVersion(courseStudiesPlanEditado.getVersion());
997
                    courseStudiesPlanPersistente.setVersionDescription(courseStudiesPlanEditado.getVersionDescription());
998
 
1507 jmachado 999
                    //REMOVED UNIDADES TO REMOVE
1000
                    for(Curso.Semestre semestre:planoEditado.getSemestre())
1001
                    {
1002
                        Iterator<UnidadeType> uIter = semestre.getUnidade().iterator();
1003
                        while(uIter.hasNext())
1004
                        {
1005
                            UnidadeType unidade = uIter.next();
1006
                            if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1007
                                uIter.remove();
1008
                        }
1009
                        for(Curso.Semestre.Perfil perfil: semestre.getPerfil())
1010
                        {
1011
                            Iterator<UnidadeType> uIter2 = perfil.getUnidade().iterator();
1012
                            while(uIter2.hasNext())
1013
                            {
1014
                                UnidadeType unidade = uIter2.next();
1015
                                if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1016
                                    uIter2.remove();
1017
                            }
1018
                        }
1019
                    }
1505 jmachado 1020
                    //Garante-se mas depois não vai para o JSON
1021
                    planoEditado.setSiges(course.getCode());//GARANTIR QUE O CODIGO SIGEST ESTA CORRECTO
1022
                    planoEditado.setNome(course.getName());
1023
                    planoEditado.setDep(course.getArea());
1024
                    //planoEditado.setDepDesc("");
1025
                    //planoEditado.setDepDescEn("");
1026
                    //planoEditado.setDepDescEs("");
1027
                    //planoEditado.setDepDescFr("");
1028
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1029
                    Marshaller marshaller = jc.createMarshaller();
1030
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1031
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1032
                    marshaller.marshal(planoEditado,xml);
1033
 
1034
                    courseStudiesPlanPersistente.setXml(xml.toString());
1035
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(planoEditado);
1036
                    //SETTING JSON in COURSE STUDIES PLAN
1037
                    courseStudiesPlanPersistente.setJson(json);
1038
                    break;
1039
                }
1040
            }
1041
            return course;
1042
        } catch (JAXBException e) {
1043
            logger.error(e,e);
1044
            return null;
1045
        } catch (TransformationException e) {
1046
            logger.error(e,e);
1047
            return null;
1048
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1049
            logger.error(e,e);
1050
            return null;
1500 jmachado 1051
        }
1052
    }
1496 jmachado 1053
 
1507 jmachado 1054
    public void generateFreshJsonPlanosEstudosFromXml(UserSession session)
1055
    {
1056
        List<CourseStudiesPlan> coursePlans = DaoFactory.getCourseStudiesPlanDaoImpl().findAll();
1057
        for(CourseStudiesPlan courseStudiesPlanPersistente: coursePlans)
1058
        {
1059
            try
1060
            {
1061
                logger.info("Generating JSON for " + courseStudiesPlanPersistente.getCourse().getName() + " version: " + courseStudiesPlanPersistente.getVersion());
1062
                Curso cursoPlano = loadCursoPlanoFromXml(courseStudiesPlanPersistente.getXml());
1518 jmachado 1063
                if(cursoPlano != null)
1064
                {
1065
                    for(Curso.Semestre s : cursoPlano.getSemestre())
1066
                    {
1067
                        SemestreImpl.setDescriptionsDefaults(s);
1068
                    }
1069
                    //send to XML again
1070
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1071
                    Marshaller marshaller = jc.createMarshaller();
1072
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1073
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1074
                    marshaller.marshal(cursoPlano,xml);
1075
                    courseStudiesPlanPersistente.setXml(xml.toString());
1076
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(cursoPlano);
1077
                    //SETTING JSON in COURSE STUDIES PLAN
1078
                    courseStudiesPlanPersistente.setJson(json);
1079
                }
1080
 
1507 jmachado 1081
            }
1082
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
1083
            {
1084
                logger.error(e,e);
1085
            }
1086
        }
1514 jmachado 1087
 
1088
        logger.info("GENERATING JSON FOR CLASS COURSE");
1089
        for(Course course: DaoFactory.getCourseDaoImpl().findAll())
1090
        {
1091
            try {
1092
                logger.info("generating json for course: " + course.getName() + " (" + course.getCode() + ")");
1093
                generateCourseJson(course);
1094
            } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1095
                logger.error(e,e);
1096
            } catch (TransformationException e) {
1097
                logger.error(e, e);
1098
            }
1099
        }
1507 jmachado 1100
    }
1500 jmachado 1101
 
1505 jmachado 1102
 
1507 jmachado 1103
 
1505 jmachado 1104
    public List<CourseDepartment> loadDepartments()
1105
    {
1106
        List<CourseDepartment> departments = DaoFactory.getCourseDepartmentDaoImpl().findAll();
1107
        for(CourseDepartment dep: departments)
1108
            dep.getName();
1109
        return departments;
1507 jmachado 1110
 
1505 jmachado 1111
    }
1112
 
1516 jmachado 1113
 
1114
    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)
1115
    {
1116
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1117
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1118
        t.addRole(course.getValidationRole());
1119
        return t;
1120
    }
1121
 
1122
    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)
1123
    {
1124
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1125
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1126
        t.removeRole(course.getValidationRole());
1127
        return t;
1128
    }
1129
 
1507 jmachado 1130
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args)
1131
    {
1132
        AbstractDao.getCurrentSession().beginTransaction();
1133
        new CoursesService().generateFreshJsonPlanosEstudosFromXml(null);
1134
        AbstractDao.getCurrentSession().getTransaction().commit();
1135
    }
1505 jmachado 1136
 
1507 jmachado 1137
 
214 jmachado 1138
}