Subversion Repositories bacoAlunos

Rev

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