Subversion Repositories bacoAlunos

Rev

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