Subversion Repositories bacoAlunos

Rev

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

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