Subversion Repositories bacoAlunos

Rev

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