Subversion Repositories bacoAlunos

Rev

Rev 1667 | 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;
1496 jmachado 20
import pt.estgp.estgweb.services.courses.xsd.Curso;
1518 jmachado 21
import pt.estgp.estgweb.services.courses.xsd.SemestreImpl;
1496 jmachado 22
import pt.estgp.estgweb.services.courses.xsd.UnidadeType;
417 jmachado 23
import pt.estgp.estgweb.services.data.IRepositoryFile;
214 jmachado 24
import pt.estgp.estgweb.services.data.RepositoryService;
444 jmachado 25
import pt.estgp.estgweb.services.expceptions.AlreadyExistsException;
995 jmachado 26
import pt.estgp.estgweb.services.expceptions.ServiceException;
1667 jmachado 27
import pt.estgp.estgweb.services.users.UserRoleConfigService;
1496 jmachado 28
import pt.estgp.estgweb.utils.ConfigProperties;
248 jmachado 29
import pt.estgp.estgweb.utils.Dom4jUtil;
1667 jmachado 30
import pt.estgp.estgweb.utils.StringsUtils;
417 jmachado 31
import pt.utl.ist.berserk.logic.serviceManager.IService;
214 jmachado 32
 
1496 jmachado 33
import javax.xml.bind.JAXBContext;
34
import javax.xml.bind.JAXBException;
35
import javax.xml.bind.Marshaller;
36
import javax.xml.bind.Unmarshaller;
1505 jmachado 37
import java.io.*;
1496 jmachado 38
import java.net.URL;
39
import java.util.*;
214 jmachado 40
 
41
/*
42
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
43
 *
44
 *
45
 * Created at 17/Out/2003 , 23:45:24
46
 *
47
 */
48
/**
49
 * @author Jorge Machado
50
 *
51
 *
52
 * Created at 17/Out/2003 , 23:45:24
53
 *
54
 */
55
public class CoursesService implements IService
56
{
57
    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);
58
 
59
    RepositoryService repositoryService = new RepositoryService();
60
 
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,
1496 jmachado 173
                                   UserSession userSession) throws ServiceException, JAXBException, TransformationException, 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
 
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, TransformationException {
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
            {
332 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,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
 
1496 jmachado 229
    private void generateCourseJson(Course cAux) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
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
     */
1505 jmachado 295
    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 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
 
358
            1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().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
        } catch (TransformationException e) {
367
            logger.error(e, e);
368
            throw e;
369
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
370
            e.printStackTrace();
371
        }
372
        try
373
        {
374
            stream.close();
375
        }
376
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
377
        {
378
            logger.error(e,e);
379
        }
380
    }
381
 
1505 jmachado 382
 
1506 jmachado 383
    /**
384
     * Apenas é chamado quando se tenta injectar um programa a partir de um upload que foi feito
385
     * pelo user ou pela sincronização remota
386
     * @param curso
387
     * @param systemUrl
388
     * @param force
389
     */
1496 jmachado 390
    private void generateAutoUrlFichasCurriculares(Curso curso,1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean force)
391
    {
392
        for(Curso.Semestre s :curso.getSemestre())
393
        {
394
            for(Curso.Semestre.Perfil p :s.getPerfil())
248 jmachado 395
            {
1496 jmachado 396
                for(UnidadeType unidadeType : p.getUnidade())
397
                {
398
                    generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
399
                }
248 jmachado 400
            }
1496 jmachado 401
            for(UnidadeType unidadeType : s.getUnidade())
214 jmachado 402
            {
1496 jmachado 403
                generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
214 jmachado 404
            }
405
        }
406
    }
407
 
1496 jmachado 408
    private void generateAutoUrlUnidade(UnidadeType unidadeType,1.5.0/docs/api/java/lang/String.html">String systemUrl,Curso curso,Curso.Semestre semestre,boolean force)
409
    {
410
        if(force || unidadeType.getUrlFichaCurricular() == null || unidadeType.getUrlFichaCurricular().trim().length()==0)
411
        {
412
            logger.info("GENERATING FICHA CURRICULAR URL For " + unidadeType.getNome());
413
            1.5.0/docs/api/java/lang/String.html">String url = systemUrl != null ? systemUrl : "";
1504 jmachado 414
            if(!url.endsWith("/"))
1496 jmachado 415
                url = url + "/";
1504 jmachado 416
 
1505 jmachado 417
            //Nao fornece o ano pois o servico irá assumir o ultimo
1504 jmachado 418
            unidadeType.setUrlFichaCurricular(url + "startLoadCourseUnitProgramSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
419
            unidadeType.setUrlUnidadeCurricular(url + "startLoadCourseUnitSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
1496 jmachado 420
        }
421
    }
422
 
423
 
1505 jmachado 424
    private static Genson getGensonPlanoEstudos(){
1496 jmachado 425
        Genson genson = new Genson.Builder()
426
                .exclude("class")
1507 jmachado 427
                .exclude("siges", Curso.class)
428
                .exclude("nome",Curso.class)
1534 jmachado 429
                .exclude("codigoPlanoSiges",Curso.class)
430
                .exclude("anoPlanoSiges",Curso.class)
431
                .exclude("descPlanoSiges",Curso.class)
1505 jmachado 432
                .exclude("dep")
1507 jmachado 433
                .exclude("removed",UnidadeType.class)
1517 jmachado 434
                .exclude("perfilId",Curso.Semestre.Perfil.class)
435
                .exclude("semestreId",Curso.Semestre.class)
1496 jmachado 436
                .create();
437
        return genson;
438
    }
439
 
440
 
441
 
442
    private static Genson getGensonCourse(){
443
        Genson genson = new Genson.Builder()
444
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
445
                .setUseFields(false)
446
                .setUseGettersAndSetters(true)
447
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
448
                .exclude("admin")
449
                .exclude("autoBlock")
450
                .exclude("autoBlockMode")
451
                .exclude("manualBlock")
452
                .exclude("newUser")
453
                .exclude("student")
454
                .exclude("superuser")
455
                .exclude("superuserOrAdmin")
456
                .exclude("teacher")
457
                .exclude("unitCheck")
458
                .exclude("id")
459
 
460
/*              .exclude(Course.class)
461
                .exclude(CourseImpl.class)
462
                .exclude(GenericUser.class)
463
                .exclude(User.class)
464
                .exclude(UserImpl.class)
465
                .exclude(Teacher.class)
466
                .exclude(TeacherImpl.class)
467
                .exclude(SigesUser.class)
468
                .exclude(SigesUserImpl.class)
469
                .exclude(GenericUser.class)
470
                .exclude(GenericUserImpl.class)
471
*/
472
                .exclude("id", Course.class)
1505 jmachado 473
                .exclude("status", Course.class)
1521 jmachado 474
                .exclude("showStudiesPlan", Course.class)
1496 jmachado 475
                .include("degreeForJsonApi", CourseImpl.class)
1543 jmachado 476
                .include("degreeForJsonApiEn", CourseImpl.class)
477
                .include("degreeForJsonApiEs", CourseImpl.class)
478
                .include("degreeForJsonApiFr", CourseImpl.class)
1496 jmachado 479
                .include("schoolForJsonApi", CourseImpl.class)
480
                .include("statusForJsonApi", CourseImpl.class)
481
 
482
                .include("name", Course.class)
1505 jmachado 483
                .include("nameEn", Course.class)
484
                .include("nameEs", Course.class)
485
                .include("nameFr", Course.class)
486
                .include("department", Course.class)
487
                .exclude("active", CourseDepartment.class)
488
                .include("sigla", CourseDepartment.class)
489
                .include("name", CourseDepartment.class)
490
                .include("nameEn", CourseDepartment.class)
491
                .include("nameEs", CourseDepartment.class)
492
                .include("nameFr", CourseDepartment.class)
1496 jmachado 493
                .include("code", Course.class)
1500 jmachado 494
                .include("validationRole", Course.class)
495
 
1496 jmachado 496
                .include("courseComission", CourseImpl.class)
497
 
498
                .include("name", GenericUser.class)
499
                .include("email", GenericUser.class)
500
                .include("sigesCode", SigesUser.class)
501
                .include("coordinator", Course.class)
502
                .create();
503
 
504
        return genson;
505
    }
506
 
507
 
508
 
214 jmachado 509
    public List<CourseView> loadCourses() throws ServiceException
510
    {
511
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
512
        List<CourseView> courseViews = new ArrayList<CourseView>();
513
        for(Course c: courses)
514
        {
515
            CourseView courseView = new CourseView(c);
516
            courseViews.add(courseView);
517
        }
518
        return courseViews;
519
    }
520
 
376 jmachado 521
    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
522
    {
1312 jmachado 523
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
524
    }
525
 
526
    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
527
    {
528
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
376 jmachado 529
        List<CourseView> courseViews = new ArrayList<CourseView>();
530
        for(Course c: courses)
531
        {
532
            CourseView courseView = new CourseView(c);
533
            courseViews.add(courseView);
534
        }
535
        return courseViews;
536
    }
537
 
249 jmachado 538
    public List<CourseView> loadCoursesImportYear() throws ServiceException
539
    {
995 jmachado 540
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
249 jmachado 541
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
542
        List<CourseView> courseViews = new ArrayList<CourseView>();
543
        for(Course c: courses)
544
        {
545
            CourseView courseView = new CourseView(c);
546
            courseViews.add(courseView);
547
        }
548
        return courseViews;
549
    }
417 jmachado 550
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
551
    {
995 jmachado 552
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
695 jmachado 553
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
417 jmachado 554
        List<CourseView> courseViews = new ArrayList<CourseView>();
555
        for(Course c: courses)
556
        {
557
            CourseView courseView = new CourseView(c);
558
            courseViews.add(courseView);
559
        }
560
        return courseViews;
561
    }
214 jmachado 562
 
790 jmachado 563
    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
564
    {
995 jmachado 565
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
790 jmachado 566
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
567
        List<CourseView> courseViews = new ArrayList<CourseView>();
568
        for(Course c: courses)
569
        {
570
            CourseView courseView = new CourseView(c);
571
            courseViews.add(courseView);
572
        }
573
        return courseViews;
574
    }
249 jmachado 575
 
1500 jmachado 576
 
577
 
578
    /** JSON API **/
579
    /**
580
     * @SERVICE@
581
     *
582
     * @param school
583
     * @param type
584
     * @return
585
     * @throws JSONException
586
     */
1496 jmachado 587
    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 {
588
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
589
        1.5.0/docs/api/java/lang/String.html">String degree = null;
590
        if(school != null && school.length() > 0)
591
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);
249 jmachado 592
 
1496 jmachado 593
        if(type != null && type.length() > 0)
594
            degree = ConfigProperties.getProperty("course.inverse." + type);
790 jmachado 595
 
1521 jmachado 596
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllShowStudiesPlanCoursesOrderByNameEvenWithoutCourseUnit(institutionalCode, degree);
1496 jmachado 597
        JSONObject coursesResponse = new JSONObject();
598
 
599
        JSONArray coursesArray = new JSONArray();
600
        for(Course cAux: courses)
601
        {
602
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
603
            JSONObject courseJson = new JSONObject();
604
            courseJson.put("name",c.getName());
605
            courseJson.put("code",c.getCode());
606
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
607
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
1543 jmachado 608
            courseJson.put("degreeForJsonApiEn",c.getDegreeForJsonApiEn());
609
            courseJson.put("degreeForJsonApiEs",c.getDegreeForJsonApiEs());
610
            courseJson.put("degreeForJsonApiFr",c.getDegreeForJsonApiFr());
1496 jmachado 611
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
612
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
613
            coursesArray.put(courseJson);
614
 
615
        }
616
        coursesResponse.put("status","ok");
617
        coursesResponse.put("courses",coursesArray);
618
 
619
        return coursesResponse;
620
    }
621
 
1500 jmachado 622
    /**
623
     *
1505 jmachado 624
     * * Serviço invocado para obter o JSON de um curso
625
     * O JSON tem dois campos o courseInfo e o plano de estudos colocados separadamente
1500 jmachado 626
     *
1505 jmachado 627
     * Atenção o plano de estudos usado é o ultimo considerando o seu ID
628
     *  Nota: O plano de Estudos é uma classe persistente que tem apenas versão e descrição
629
     *  deverá ter como campo o XML e o JSON já gerados do plano de estudos que comporta
630
     *
1500 jmachado 631
     * @param code
632
     * @return
633
     * @throws JSONException
634
     * @throws IOException
635
     * @throws TransformationException
636
     * @throws JAXBException
637
     */
1498 jmachado 638
    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 639
 
640
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
641
 
642
 
643
        JSONObject coursesResponse = new JSONObject();
644
 
1498 jmachado 645
        if(course.getJson() == null)
646
        {
647
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
648
            new CoursesService().generateCourseJson(course);
649
        }
650
 
1496 jmachado 651
        if(course.getJson() != null)
652
        {
653
            JSONObject courseObj = new JSONObject(course.getJson());
654
            coursesResponse.put("courseInfo",courseObj);
1505 jmachado 655
            //Este caso apenas se dá se o plano nunca tiver sido editado ou sincronizado
656
            //Nesse caso o sistema irá tentar obtê-lo da stream do repositorio
1500 jmachado 657
            if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1498 jmachado 658
            {
1505 jmachado 659
                logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will try generate from studies plan OLD Stream");
1498 jmachado 660
                UserSession userSession = DomainObjectFactory.createUserSessionImpl();
661
                userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
1505 jmachado 662
                new CoursesService().generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1498 jmachado 663
            }
664
 
1505 jmachado 665
            if(course.getStudiesPlans() != null )
1496 jmachado 666
            {
667
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
1505 jmachado 668
                JSONObject studiesPlanObj;
669
                if(studiesPlan.getJson() != null)
670
                {
671
                    studiesPlanObj = new JSONObject(studiesPlan.getJson());
672
                    studiesPlanObj.put("version",studiesPlan.getVersion());
673
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
674
                }
675
                else
676
                {
677
                    studiesPlanObj = new JSONObject();
678
                    studiesPlanObj.put("fault","Zero contents for this version");
679
                    studiesPlanObj.put("version",studiesPlan.getVersion());
680
                    coursesResponse.put("courseStudiesPlan",studiesPlanObj);
681
                }
1496 jmachado 682
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
1505 jmachado 683
 
1496 jmachado 684
            }
685
            else
686
            {
687
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
688
            }
689
        }
690
        else
691
        {
1505 jmachado 692
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE, PLEASE OPEN AND SAVE COURSE IN ADMINISTRATION");
1496 jmachado 693
        }
694
        return coursesResponse;
695
    }
696
 
1500 jmachado 697
    /**
698
     * @SERVICE@
699
     *
700
     * @param code
701
     * @return
702
     * @throws JSONException
703
     */
1502 jmachado 704
    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 705
 
706
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
1501 jmachado 707
 
1502 jmachado 708
        if(renew != null || course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1501 jmachado 709
        {
710
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
711
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
712
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
713
            try {
1505 jmachado 714
                generateXmlJaxbStudiesPlanVersionFromRepositoryOldPlanStream(userSession, course, false, null);
1501 jmachado 715
            } catch (JAXBException e) {
716
                logger.error(e,e);
717
                return "<error>" + e.toString() + ". see log for details</error>";
718
            } catch (TransformationException e) {
719
                logger.error(e, e);
720
                return "<error>" + e.toString() + ". see log for details</error>";
721
            }
722
        }
723
 
1496 jmachado 724
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
725
        {
726
            return course.getStudiesPlans().iterator().next().getXml();
727
        }
728
        return "<error>Does not exixt</error>";
729
 
730
    }
731
 
732
 
1500 jmachado 733
    /**
734
     * @SERVICE@
735
     *
736
     * @param systemUrl
737
     * @param setActive
738
     * @return
739
     * @throws IOException
740
     * @throws JSONException
741
     * @throws TransformationException
742
     * @throws JAXBException
743
     */
1496 jmachado 744
 
1502 jmachado 745
    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 746
 
1497 jmachado 747
        1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
748
        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 749
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
750
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
751
        JSONObject obj = new JSONObject(str);
752
        JSONArray courses = obj.getJSONArray("courses");
753
        for(int i = 0; i < courses.length();i++)
754
        {
1502 jmachado 755
            1.5.0/docs/api/java/lang/String.html">String code = "";
756
            try{
757
                JSONObject course = courses.getJSONObject(i);
758
                code = course.getString("code");
759
                Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
760
                if(c == null)
761
                {
762
                    1.5.0/docs/api/java/lang/String.html">String msg = "SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system";
763
                    log.append("<info>" + msg+"</info>");
764
                    logger.info(msg);
765
                }
766
                else
767
                {
768
                    1.5.0/docs/api/java/lang/String.html">String msg = "UPDATING - Course " + code + " " + course.getString("name") + " exist in this system";
769
                    log.append("<info>" + msg+"</info>");
770
                    logger.info(msg);
1500 jmachado 771
 
1505 jmachado 772
                    //#############UPDATING Course Comission Members
1516 jmachado 773
                    updateCourseComissionMembersAndCourseInfo(systemUrl, code, c);
1505 jmachado 774
 
1502 jmachado 775
                    //#############UPDATING STUDIES PLAN
776
                    updateStudiesPlanFromRemoteSystem(systemUrl, setActive, log, course, code, c);
1500 jmachado 777
 
1505 jmachado 778
 
1502 jmachado 779
                }
1500 jmachado 780
            }
1502 jmachado 781
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
782
            {
783
                logger.error("UPDATE COURSE: " + i + " code: " + code + " FAILED");
784
                logger.error(e,e);
785
            }
1500 jmachado 786
        }
787
        return log.toString();
788
 
789
    }
790
 
1505 jmachado 791
    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 {
792
        1.5.0/docs/api/java/lang/String.html">String msg;
793
        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();
794
        1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
795
        int len = studiesPlan.length();
796
        if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
797
        {
798
            msg = "Course " + code + " " + course.getString("name") + " dont has studies plan";
799
            log.append("<warn>" + msg+"</warn>");
800
            logger.warn(msg);
801
        }
802
        else
803
        {
804
            msg = "Found studies plan for "  + code + " " + course.getString("name") + " will update ";
805
            log.append("<info>" + msg+"</info>");
806
            logger.info(msg);
807
            if(setActive)
808
            {
809
                msg = "Setting course to active";
810
                log.append("<info>" + msg+"</info>");
811
                logger.info(msg);
812
                c.setStatus(true);
813
            }
814
            //System.out.println(studiesPlan);
815
            msg = "GENERATING COURSE JSON ....";
816
            log.append("<info>" + msg+"</info>");
817
            logger.info(msg);
818
            new CoursesService().generateCourseJson(c);
819
 
820
            msg="GENERATING COURSE STUDIES PLAN JSON ....";
821
            log.append("<info>" + msg+"</info>");
822
            logger.info(msg);
823
            stream.close();
824
            stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
825
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
826
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
827
            new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,systemUrl);
828
        }
829
    }
830
 
831
 
1500 jmachado 832
    /**
833
     * Update courseComission Members
834
     * @param systemUrl
835
     * @param code
836
     * @param c
837
     * @throws IOException
838
     * @throws JSONException
839
     */
1516 jmachado 840
    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
841
    {
842
 
1500 jmachado 843
        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);
844
        5+0%2Fdocs%2Fapi+InputStream">InputStream isCourseDetails = urlCourseDetails.openStream();
845
        1.5.0/docs/api/java/lang/String.html">String strCourseDetails = StreamsUtils.readString(isCourseDetails);
846
        JSONObject objCourseDetails = new JSONObject(strCourseDetails);
1516 jmachado 847
 
848
        //DEPARTMENT
849
        JSONObject department = objCourseDetails.getJSONObject("courseInfo").getJSONObject("department");
850
        if(department != null)
851
        {
852
            1.5.0/docs/api/java/lang/String.html">String sigla = department.getString("sigla");
853
            if(sigla != null)
854
            {
855
                CourseDepartment department1 =  DaoFactory.getCourseDepartmentDaoImpl().findBySigla(sigla);
856
                if(department1 != null)
857
                {
858
                    c.setDepartment(department1);
859
                }
860
            }
861
        }
862
 
863
 
1500 jmachado 864
        1.5.0/docs/api/java/lang/String.html">String validationRole = objCourseDetails.getJSONObject("courseInfo").getString("validationRole");
865
 
1516 jmachado 866
 
867
 
868
 
1500 jmachado 869
        if(validationRole == null)
870
        {
871
            logger.info("validationRole is not defined");
872
        }
873
        else
874
        {
875
            logger.info("found validationRole: " + validationRole);
876
            c.setValidationRole(validationRole);
877
 
878
            JSONObject coordinator = objCourseDetails.getJSONObject("courseInfo").getJSONObject("coordinator");
879
            JSONArray courseComission = objCourseDetails.getJSONObject("courseInfo").getJSONArray("courseComission");
880
 
881
            Teacher coordinatorPersistent = findPersonFromCourseDetails(coordinator);
882
            if(coordinatorPersistent == null)
883
            {
884
                logger.warn("Coordinator does not exist in this system ");
885
            }
886
            else
887
            {
888
                c.setCoordinator(coordinatorPersistent);
889
            }
1516 jmachado 890
 
891
            List<User> users = DaoFactory.getUserDaoImpl().loadRoleUsers(validationRole);
892
            logger.info("Encontrados " + users.size() + " docentes com o papel de comissao " + validationRole + " vai remover");
893
            for(User u: users)
894
            {
895
                logger.info("Removendo role a " + u.getName());
896
                u.removeRole(validationRole);
897
            }
898
 
1500 jmachado 899
            for(int j = 0 ; j < courseComission.length(); j++)
900
            {
901
                JSONObject memberComission = courseComission.getJSONObject(j);
902
                Teacher memberPersistent = findPersonFromCourseDetails(memberComission);
903
                if(memberPersistent == null)
1496 jmachado 904
                {
1500 jmachado 905
                    logger.info("Member does not exist in this system ");
1496 jmachado 906
                }
907
                else
908
                {
1500 jmachado 909
                    logger.info("Adding role of course comission member");
910
                    if(!memberPersistent.hasRole(validationRole))
1497 jmachado 911
                    {
1500 jmachado 912
                        memberPersistent.addRole(validationRole);
1497 jmachado 913
                    }
1500 jmachado 914
                }
1496 jmachado 915
            }
916
        }
1500 jmachado 917
    }
1497 jmachado 918
 
1500 jmachado 919
    private Teacher findPersonFromCourseDetails(JSONObject coordinator) {
920
        int code;
921
        try {
922
            if(coordinator.has("sigesCode"))
923
            {
924
                code = coordinator.getInt("sigesCode");
925
            }
926
            else
927
            {
928
                logger.warn("there is no sigesCode for this person " + coordinator.toString());
929
                return null;
930
            }
931
        } catch (JSONException e){
932
            return null;
933
        } catch (1.5.0/docs/api/java/lang/NumberFormatException.html">NumberFormatException e){
934
            return null;
935
        }
936
        return DaoFactory.getTeacherDaoImpl().loadBySigesCode(code);
1496 jmachado 937
    }
938
 
1505 jmachado 939
 
940
 
941
    /*
942
     * Studies Plans Administration Services
943
     *
944
     */
945
    public void addNewStudiesPlan(long courseId,CourseStudiesPlan studiesPlan,UserSession session)
946
    {
947
        Course c = DaoFactory.getCourseDaoImpl().load(courseId);
948
        studiesPlan.setCourse(c);
949
        c.getStudiesPlans().add(studiesPlan);
950
        DaoFactory.getCourseStudiesPlanDaoImpl().save(studiesPlan);
951
    }
952
 
1516 jmachado 953
    public CourseStudiesPlanImpl cloneVersionFrom(long sourcePlanId, long targetPlanId, long courseId, UserSession session)
1505 jmachado 954
    {
955
        Course course = DaoFactory.getCourseDaoImpl().load(courseId);
956
        CourseStudiesPlan source = null;
957
        CourseStudiesPlan target = null;
958
        for(CourseStudiesPlan plan: course.getStudiesPlans())
1500 jmachado 959
        {
1505 jmachado 960
            if(plan.getId() == sourcePlanId)
961
                source = plan;
962
            else if(plan.getId() == targetPlanId)
963
                target = plan;
1500 jmachado 964
        }
1505 jmachado 965
        target.setXml(source.getXml());
966
        target.setJson(source.getJson());
1516 jmachado 967
        return (CourseStudiesPlanImpl) DaoFactory.getCourseStudiesPlanDaoImpl().narrow(target);
1505 jmachado 968
    }
1507 jmachado 969
 
1505 jmachado 970
    public Curso loadCursoPlanoFromXml(1.5.0/docs/api/java/lang/String.html">String xml)
971
    {
972
        try {
973
            if(xml != null)
1500 jmachado 974
            {
1505 jmachado 975
                JAXBContext jc = JAXBContext.newInstance(Curso.class);
976
                Unmarshaller unmarshaller = jc.createUnmarshaller();
977
                Curso curso = (Curso) unmarshaller.unmarshal(new 1.5.0/docs/api/java/io/StringReader.html">StringReader(xml));
978
                return curso;
1500 jmachado 979
            }
1505 jmachado 980
            return null;
981
        } catch (JAXBException e) {
982
            logger.error(e,e);
983
            return null;
984
        }
985
    }
1496 jmachado 986
 
1505 jmachado 987
    /**
988
     * Persist the edited studies plan
989
     * Updates studiesPlanVersion
990
     * Updates studiesPlanVersionDescription
991
     * Updates PlanoEstudos XML and JSON
992
     *
993
     * @param courseId
994
     * @param coursePlanId
995
     * @param planoEditado
996
     * @param courseStudiesPlanEditado
997
     * @return
998
     */
999
    public Course savePlanoEstudosEditado(long courseId, long coursePlanId, Curso planoEditado, CourseStudiesPlan courseStudiesPlanEditado,UserSession session)
1000
    {
1001
        try {
1002
            Course course = DaoFactory.getCourseDaoImpl().load(courseId);
1003
 
1004
            for(CourseStudiesPlan courseStudiesPlanPersistente: course.getStudiesPlans())
1005
            {
1006
                if(courseStudiesPlanPersistente.getId() == coursePlanId)
1007
                {
1008
                    courseStudiesPlanPersistente.setVersion(courseStudiesPlanEditado.getVersion());
1009
                    courseStudiesPlanPersistente.setVersionDescription(courseStudiesPlanEditado.getVersionDescription());
1010
 
1507 jmachado 1011
                    //REMOVED UNIDADES TO REMOVE
1012
                    for(Curso.Semestre semestre:planoEditado.getSemestre())
1013
                    {
1014
                        Iterator<UnidadeType> uIter = semestre.getUnidade().iterator();
1015
                        while(uIter.hasNext())
1016
                        {
1017
                            UnidadeType unidade = uIter.next();
1018
                            if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1019
                                uIter.remove();
1020
                        }
1021
                        for(Curso.Semestre.Perfil perfil: semestre.getPerfil())
1022
                        {
1023
                            Iterator<UnidadeType> uIter2 = perfil.getUnidade().iterator();
1024
                            while(uIter2.hasNext())
1025
                            {
1026
                                UnidadeType unidade = uIter2.next();
1027
                                if(unidade.getRemoved() != null && unidade.getRemoved().equals("true"))
1028
                                    uIter2.remove();
1029
                            }
1030
                        }
1031
                    }
1505 jmachado 1032
                    //Garante-se mas depois não vai para o JSON
1033
                    planoEditado.setSiges(course.getCode());//GARANTIR QUE O CODIGO SIGEST ESTA CORRECTO
1034
                    planoEditado.setNome(course.getName());
1035
                    planoEditado.setDep(course.getArea());
1036
                    //planoEditado.setDepDesc("");
1037
                    //planoEditado.setDepDescEn("");
1038
                    //planoEditado.setDepDescEs("");
1039
                    //planoEditado.setDepDescFr("");
1040
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1041
                    Marshaller marshaller = jc.createMarshaller();
1042
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1043
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1044
                    marshaller.marshal(planoEditado,xml);
1045
 
1046
                    courseStudiesPlanPersistente.setXml(xml.toString());
1047
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(planoEditado);
1048
                    //SETTING JSON in COURSE STUDIES PLAN
1049
                    courseStudiesPlanPersistente.setJson(json);
1050
                    break;
1051
                }
1052
            }
1053
            return course;
1054
        } catch (JAXBException e) {
1055
            logger.error(e,e);
1056
            return null;
1057
        } catch (TransformationException e) {
1058
            logger.error(e,e);
1059
            return null;
1060
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1061
            logger.error(e,e);
1062
            return null;
1500 jmachado 1063
        }
1064
    }
1496 jmachado 1065
 
1507 jmachado 1066
    public void generateFreshJsonPlanosEstudosFromXml(UserSession session)
1067
    {
1068
        List<CourseStudiesPlan> coursePlans = DaoFactory.getCourseStudiesPlanDaoImpl().findAll();
1069
        for(CourseStudiesPlan courseStudiesPlanPersistente: coursePlans)
1070
        {
1071
            try
1072
            {
1073
                logger.info("Generating JSON for " + courseStudiesPlanPersistente.getCourse().getName() + " version: " + courseStudiesPlanPersistente.getVersion());
1074
                Curso cursoPlano = loadCursoPlanoFromXml(courseStudiesPlanPersistente.getXml());
1518 jmachado 1075
                if(cursoPlano != null)
1076
                {
1077
                    for(Curso.Semestre s : cursoPlano.getSemestre())
1078
                    {
1079
                        SemestreImpl.setDescriptionsDefaults(s);
1080
                    }
1081
                    //send to XML again
1082
                    JAXBContext jc = JAXBContext.newInstance(Curso.class);
1083
                    Marshaller marshaller = jc.createMarshaller();
1084
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1085
                    1.5.0/docs/api/java/io/StringWriter.html">StringWriter xml = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
1086
                    marshaller.marshal(cursoPlano,xml);
1087
                    courseStudiesPlanPersistente.setXml(xml.toString());
1088
                    1.5.0/docs/api/java/lang/String.html">String json = getGensonPlanoEstudos().serialize(cursoPlano);
1089
                    //SETTING JSON in COURSE STUDIES PLAN
1090
                    courseStudiesPlanPersistente.setJson(json);
1091
                }
1092
 
1507 jmachado 1093
            }
1094
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
1095
            {
1096
                logger.error(e,e);
1097
            }
1098
        }
1514 jmachado 1099
 
1100
        logger.info("GENERATING JSON FOR CLASS COURSE");
1101
        for(Course course: DaoFactory.getCourseDaoImpl().findAll())
1102
        {
1103
            try {
1104
                logger.info("generating json for course: " + course.getName() + " (" + course.getCode() + ")");
1105
                generateCourseJson(course);
1106
            } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
1107
                logger.error(e,e);
1108
            } catch (TransformationException e) {
1109
                logger.error(e, e);
1110
            }
1111
        }
1507 jmachado 1112
    }
1500 jmachado 1113
 
1505 jmachado 1114
 
1507 jmachado 1115
 
1505 jmachado 1116
    public List<CourseDepartment> loadDepartments()
1117
    {
1118
        List<CourseDepartment> departments = DaoFactory.getCourseDepartmentDaoImpl().findAll();
1119
        for(CourseDepartment dep: departments)
1120
            dep.getName();
1121
        return departments;
1507 jmachado 1122
 
1505 jmachado 1123
    }
1124
 
1516 jmachado 1125
 
1126
    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)
1127
    {
1128
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1129
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1130
        t.addRole(course.getValidationRole());
1131
        return t;
1132
    }
1133
 
1134
    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)
1135
    {
1136
        Course course = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
1137
        Teacher t = DaoFactory.getTeacherDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(teacherId));
1138
        t.removeRole(course.getValidationRole());
1139
        return t;
1140
    }
1141
 
1507 jmachado 1142
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args)
1143
    {
1144
        AbstractDao.getCurrentSession().beginTransaction();
1145
        new CoursesService().generateFreshJsonPlanosEstudosFromXml(null);
1146
        AbstractDao.getCurrentSession().getTransaction().commit();
1147
    }
1505 jmachado 1148
 
1535 jmachado 1149
    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 1150
    {
1151
        StudiesPlanImporter importer = new StudiesPlanImporter();
1152
        importer.parseFile(stream);
1153
        1.5.0/docs/api/java/lang/System.html">System.out.println(importer.getLog());
1535 jmachado 1154
        CourseStudiesPlan plan = DaoFactory.getCourseStudiesPlanDaoImpl().load(studiesPlanId);
1155
        plan.setImportLog(importer.getLog());
1534 jmachado 1156
        return importer;
1157
    }
1541 jmachado 1158
    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
1159
    {
1160
        StudiesPlanImporter importer = new StudiesPlanImporter();
1161
        importer.parseFile(stream);
1162
        1.5.0/docs/api/java/lang/System.html">System.out.println(importer.getLog());
1163
        CourseStudiesPlan plan = DaoFactory.getCourseStudiesPlanDaoImpl().load(studiesPlanId);
1164
        plan.setImportLog(plan.getImportLog() + "\n\n############\n\n##MERGING\n\n" + importer.getLog());
1165
        return importer;
1166
    }
1507 jmachado 1167
 
1667 jmachado 1168
    public UserRoleConfig createRoleCourseComission(long courseId,UserSession userSession)
1169
    {
1170
        Course c = DaoFactory.getCourseDaoImpl().load(courseId);
1171
        if(c.getValidationRole() == null || c.getValidationRole().trim().length() == 0)
1172
        {
1173
            1.5.0/docs/api/java/lang/String.html">String normalizedName = StringsUtils.getNormalizedNameSafeforCode(c.getName());
1174
            if(normalizedName == null)
1175
                throw new 1.5.0/docs/api/java/lang/RuntimeException.html">RuntimeException("Erro o curso " + c.getId() +" + nao tem nome");
1176
            1.5.0/docs/api/java/lang/String.html">String roleValidation = "courseValidateProgram" + normalizedName;
1177
            UserRoleConfigImpl newUserRoleConfig = DomainObjectFactory.createUserRoleConfigImpl();
1178
            newUserRoleConfig.setRole(roleValidation);
1179
            newUserRoleConfig.setValid(true);
1180
            newUserRoleConfig.setValue("Comissão de Curso de " + c.getName());
1181
            newUserRoleConfig.setValuePt("Comissão de Curso de " + c.getName());
1182
            newUserRoleConfig.setValueEn("");
1183
            newUserRoleConfig.setValueEs("");
1184
            newUserRoleConfig.setValueFr("");
1185
            new  UserRoleConfigService().addUpdateRole(newUserRoleConfig,userSession);
1186
            c.setValidationRole(roleValidation);
1187
            return  newUserRoleConfig;
1188
        }
1189
        return null;
1190
    }
1534 jmachado 1191
 
1667 jmachado 1192
    public Teacher changeCoordinator(long teacherId,long courseId,UserSession userSession)
1193
    {
1194
        Course c = DaoFactory.getCourseDaoImpl().load(courseId);
1195
        Teacher t = DaoFactory.getTeacherDaoImpl().load(teacherId);
1196
        c.setCoordinator(t);
1197
        t = DaoFactory.getTeacherDaoImpl().narrow(t);
1198
        return t;
1199
    }
1200
 
1670 jmachado 1201
    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
1202
    {
1203
        CourseDepartmentImpl courseDepartment = CourseDepartmentImpl.loadFromJson(json);
1204
        CourseDepartmentImpl courseDepartmentPersistent = (CourseDepartmentImpl) DaoFactory.getCourseDepartmentDaoImpl().load(courseDepartment.getSigla());
1205
        courseDepartmentPersistent.setSigla(courseDepartment.getSigla());
1206
        courseDepartmentPersistent.setActive(courseDepartment.isActive());
1207
        courseDepartmentPersistent.setName(courseDepartment.getName());
1208
        courseDepartmentPersistent.setNameEs(courseDepartment.getNameEs());
1209
        courseDepartmentPersistent.setNameEn(courseDepartment.getNameEs());
1210
        courseDepartmentPersistent.setNameFr(courseDepartment.getNameFr());
1211
        courseDepartmentPersistent.setInstitutionalCode(courseDepartment.getInstitutionalCode());
1212
        courseDepartmentPersistent.setBoardRole(courseDepartment.getBoardRole());
1213
        courseDepartmentPersistent.setDirectorRole(courseDepartment.getDirectorRole());
1214
        if(courseDepartment.getCourseSchool() != null && courseDepartment.getCourseSchool().getId() > 0)
1215
        {
1216
            CourseSchoolImpl courseSchool = (CourseSchoolImpl) DaoFactory.getCourseSchoolDaoImpl().load(courseDepartment.getCourseSchool().getId());
1217
            courseDepartmentPersistent.setCourseSchool(courseSchool);
1218
        }
1219
        else
1220
            courseDepartmentPersistent.setCourseSchool(null);
1221
        return courseDepartmentPersistent;
1667 jmachado 1222
 
1670 jmachado 1223
    }
1224
 
1225
    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
1226
    {
1227
        CourseDepartmentImpl courseDepartment = CourseDepartmentImpl.loadFromJson(json);
1228
        CourseDepartmentImpl courseDepartmentPersistent = (CourseDepartmentImpl) DaoFactory.getCourseDepartmentDaoImpl().load(courseDepartment.getSigla());
1229
        DaoFactory.getCourseDepartmentDaoImpl().delete(courseDepartmentPersistent);
1230
        return courseDepartmentPersistent;
1231
 
1232
    }
1233
 
1234
    public CourseDepartmentImpl newDepartmentFromJson(UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException
1235
    {
1236
        CourseDepartmentImpl courseDepartmentPersistent = DomainObjectFactory.createCourseDepartmentImpl();
1237
 
1238
        courseDepartmentPersistent.setSigla(BytesUtils.generateKey().substring(0,10));
1239
        courseDepartmentPersistent.setActive(false);
1240
        DaoFactory.getCourseDepartmentDaoImpl().save(courseDepartmentPersistent);
1241
        return courseDepartmentPersistent;
1242
 
1243
    }
1244
 
1245
 
1246
    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
1247
    {
1248
        CourseSchoolImpl courseSchool = CourseSchoolImpl.loadFromJson(json);
1249
        CourseSchoolImpl courseSchoolPersistent = (CourseSchoolImpl) DaoFactory.getCourseSchoolDaoImpl().load(courseSchool.getId());
1250
 
1251
        courseSchoolPersistent.setActive(courseSchool.isActive());
1252
        courseSchoolPersistent.setName(courseSchool.getName());
1253
        courseSchoolPersistent.setNameEs(courseSchool.getNameEs());
1254
        courseSchoolPersistent.setNameEn(courseSchool.getNameEs());
1255
        courseSchoolPersistent.setNameFr(courseSchool.getNameFr());
1256
        courseSchoolPersistent.setInstitutionalCode(courseSchool.getInstitutionalCode());
1257
 
1258
        courseSchoolPersistent.setSchoolDirectorRole(courseSchool.getSchoolDirectorRole());
1259
        courseSchoolPersistent.setSchoolBoardRole(courseSchool.getSchoolBoardRole());
1260
        courseSchoolPersistent.setSchoolSecretariadoRole(courseSchool.getSchoolSecretariadoRole());
1261
 
1262
        courseSchoolPersistent.setCtcPresidentRole(courseSchool.getCtcPresidentRole());
1263
        courseSchoolPersistent.setCtcMemberRole(courseSchool.getCtcMemberRole());
1264
        courseSchoolPersistent.setCtcSecretariadoRole(courseSchool.getCtcSecretariadoRole());
1265
 
1266
        courseSchoolPersistent.setPedagogicoPresidentRole(courseSchool.getPedagogicoPresidentRole());
1267
        courseSchoolPersistent.setPedagogicoMemberRole(courseSchool.getPedagogicoMemberRole());
1268
        courseSchoolPersistent.setPedagogicoSecretariadoRole(courseSchool.getPedagogicoSecretariadoRole());
1269
 
1270
        return courseSchoolPersistent;
1271
 
1272
    }
1273
 
1274
    public CourseSchoolImpl newSchoolFromJson(UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException
1275
    {
1276
        CourseSchoolImpl courseSchoolPersistent = DomainObjectFactory.createCourseSchoolImpl();
1277
 
1278
        courseSchoolPersistent.setActive(false);
1279
        DaoFactory.getCourseSchoolDaoImpl().save(courseSchoolPersistent);
1280
        return courseSchoolPersistent;
1281
 
1282
    }
1283
 
1284
    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
1285
    {
1286
        CourseSchoolImpl courseSchool = CourseSchoolImpl.loadFromJson(json);
1287
        CourseSchoolImpl courseSchoolPersistent = (CourseSchoolImpl) DaoFactory.getCourseSchoolDaoImpl().load(courseSchool.getId());
1288
        DaoFactory.getCourseSchoolDaoImpl().delete(courseSchoolPersistent);
1289
        return courseSchoolPersistent;
1290
 
1291
    }
1292
 
1293
 
214 jmachado 1294
}