Subversion Repositories bacoAlunos

Rev

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