Subversion Repositories bacoAlunos

Rev

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

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