Subversion Repositories bacoAlunos

Rev

Rev 1502 | Rev 1504 | 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;
417 jmachado 6
import jomm.utils.FilesUtils;
1496 jmachado 7
import jomm.utils.StreamsUtils;
417 jmachado 8
import org.apache.log4j.Logger;
9
import org.dom4j.Document;
1496 jmachado 10
import org.json.JSONArray;
11
import org.json.JSONException;
12
import org.json.JSONObject;
417 jmachado 13
import pt.estgp.estgweb.Globals;
1496 jmachado 14
import pt.estgp.estgweb.domain.*;
417 jmachado 15
import pt.estgp.estgweb.domain.dao.DaoFactory;
16
import pt.estgp.estgweb.domain.views.CourseView;
17
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
1496 jmachado 18
import pt.estgp.estgweb.services.courses.xsd.Curso;
19
import pt.estgp.estgweb.services.courses.xsd.UnidadeType;
417 jmachado 20
import pt.estgp.estgweb.services.data.IRepositoryFile;
214 jmachado 21
import pt.estgp.estgweb.services.data.RepositoryService;
444 jmachado 22
import pt.estgp.estgweb.services.expceptions.AlreadyExistsException;
995 jmachado 23
import pt.estgp.estgweb.services.expceptions.ServiceException;
1496 jmachado 24
import pt.estgp.estgweb.utils.ConfigProperties;
248 jmachado 25
import pt.estgp.estgweb.utils.Dom4jUtil;
417 jmachado 26
import pt.utl.ist.berserk.logic.serviceManager.IService;
214 jmachado 27
 
1496 jmachado 28
import javax.xml.bind.JAXBContext;
29
import javax.xml.bind.JAXBException;
30
import javax.xml.bind.Marshaller;
31
import javax.xml.bind.Unmarshaller;
1500 jmachado 32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.PrintWriter;
35
import java.io.StringWriter;
1496 jmachado 36
import java.net.URL;
37
import java.util.*;
214 jmachado 38
 
39
/*
40
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
41
 *
42
 *
43
 * Created at 17/Out/2003 , 23:45:24
44
 *
45
 */
46
/**
47
 * @author Jorge Machado
48
 *
49
 *
50
 * Created at 17/Out/2003 , 23:45:24
51
 *
52
 */
53
public class CoursesService implements IService
54
{
55
    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);
56
 
57
    RepositoryService repositoryService = new RepositoryService();
58
 
59
 
60
    public CourseView loadCourse(long id, boolean initUnits) throws ServiceException
61
    {
62
        Course c = DaoFactory.getCourseDaoImpl().get(id);
63
 
64
        if(c != null)
65
        {
66
            CourseView cV = new CourseView(c,initUnits);
67
            if(c.getStudiesPlan() != null)
68
            {
69
                RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
70
                cV.setStudiesPlan(repositoryFile);
71
            }
72
 
73
            return cV;
74
        }
75
        return null;
76
    }
77
 
345 jmachado 78
    public List<String> loadImportYears(UserSession userSession) throws ServiceException
79
    {
80
        List<String> importYears = DaoFactory.getCourseDaoImpl().loadImportYears();
81
        List<String> imStrings = new ArrayList<String>();
82
        for(1.5.0/docs/api/java/lang/String.html">String importYear: importYears)
83
        {
84
            imStrings.add(importYear);
85
        }
86
        return imStrings;
87
    }
88
 
214 jmachado 89
    public CourseView loadCourseByCode(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits) throws ServiceException
90
    {
444 jmachado 91
        try{
92
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
93
            if(c != null)
214 jmachado 94
            {
444 jmachado 95
                CourseView cV = new CourseView(c,initUnits);
96
                if(c.getStudiesPlan() != null)
97
                {
98
                    RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
99
                    cV.setStudiesPlan(repositoryFile);
100
                }
101
                return cV;
214 jmachado 102
            }
103
        }
444 jmachado 104
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
105
        {
106
            logger.error(e + " loading code:" + code,e);
107
            throw new ServiceException("loading code: " + code  + " - " + e.toString(),e);
108
        }
214 jmachado 109
        return null;
110
    }
111
 
112
    public CourseView submitCourse(CourseView courseView,
113
                                   5+0%2Fdocs%2Fapi+InputStream">InputStream stream,
114
                                   1.5.0/docs/api/java/lang/String.html">String name,
115
                                   int size,
116
                                   1.5.0/docs/api/java/lang/String.html">String contentType,
1496 jmachado 117
                                   UserSession userSession) throws ServiceException, JAXBException, TransformationException, 1.5.0/docs/api/java/io/IOException.html">IOException {
214 jmachado 118
        Course c;
119
        if(courseView.getId() > 0)
444 jmachado 120
        {
214 jmachado 121
            c = DaoFactory.getCourseDaoImpl().get(courseView.getId());
444 jmachado 122
        }
214 jmachado 123
        else
124
        {
444 jmachado 125
            c = DaoFactory.getCourseDaoImpl().findCourseByCodeAndYear(courseView.getCode(),courseView.getImportYear());
126
            if(c != null)
127
                throw new AlreadyExistsException(AlreadyExistsException.ALREADY_EXISTS_COURSE);      
214 jmachado 128
            c = DomainObjectFactory.createCourseImpl();
129
            DaoFactory.getCourseDaoImpl().save(c);
130
        }
131
 
248 jmachado 132
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
133
 
1496 jmachado 134
        htmlTrasformationResult = uploadStudiesPlan(stream, name, size, contentType, userSession, c,false,null);
135
        courseView.persistViewInObject(c);
136
        CourseView cv = loadCourse(c.getId(),false);
137
        cv.setHtmlResult(htmlTrasformationResult);
138
 
139
        /**
140
         * New## generating course json
141
         */
142
        generateCourseJson(c);
143
 
144
        return cv;
145
    }
146
 
147
    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 {
148
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
214 jmachado 149
        if(stream != null && size > 0)
150
        {
268 jmachado 151
            1.5.0/docs/api/java/lang/String.html">String extension = FilesUtils.getExtension(name);
152
            if(c.getStudiesPlan() == null)
153
            {
332 jmachado 154
                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 155
                c.setStudiesPlan(identifier);
156
            }
157
            else
158
            {
159
                repositoryService.updateRepositoryFile(c.getStudiesPlan(), stream, contentType, extension, size, name, "course.studies.plan " + c.getName(), ResourceAccessControlEnum.publicDomain);
160
            }
1496 jmachado 161
            htmlTrasformationResult = generateHtmlCache(userSession, c);
162
            //####New#### Generating XML with JaxB
163
            generateXmlJaxbStudiesPlanVersion(userSession, c,forceUrlFichas,systemUrl);
164
        }
165
        return htmlTrasformationResult;
166
    }
167
 
168
    private void generateCourseJson(Course cAux) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
169
        CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
170
 
171
        if(c.getValidationRole() != null && c.getValidationRole().trim().length() > 0)
172
        {
173
            List<Teacher> courseComissionProxys = DaoFactory.getUserDaoImpl().loadRoleTeachers(c.getValidationRole());
174
            List<Teacher> courseComission = new ArrayList<Teacher>();
175
            for(Teacher t: courseComissionProxys)
248 jmachado 176
            {
1496 jmachado 177
                courseComission.add(DaoFactory.getTeacherDaoImpl().narrow(t));
248 jmachado 178
            }
1496 jmachado 179
            c.setCourseComission(courseComission);
180
        }
181
        //Getting Coordinator from proxy
182
        Teacher t = c.getCoordinator();
1500 jmachado 183
        if(t != null)
184
            t.getName();
185
        else
186
        {
187
            logger.warn("Course does not have coordinator");
188
        }
1496 jmachado 189
 
190
        1.5.0/docs/api/java/lang/String.html">String jsonCourse = getGensonCourse().serialize(c);
191
        c.setJson(jsonCourse);
192
    }
193
 
194
    private 1.5.0/docs/api/java/lang/String.html">String generateHtmlCache(UserSession userSession, Course c) {
195
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
196
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
197
        stream = repositoryFile.getInput();
198
        try
199
        {
200
            5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(stream);
201
            Map<String,Object> parameters = new HashMap<String,Object>();
202
            parameters.put("COURSE_SIGES_CODE",c.getCode());
203
            1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.styleDocument(dom, Globals.TEMPLATE_COURSE_XSL_PATH,parameters);
204
            c.setCacheWebDocument(html);
205
        }
206
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
207
        {
208
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
209
            1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter printWriter = new 1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter(writer);
210
            e.printStackTrace(printWriter);
211
            htmlTrasformationResult = "<div class=\"error\"><pre>" + e.toString() + "\n" + printWriter.toString() + "</pre></div>";
212
            printWriter.close();
213
        }
214
        try
215
        {
216
            stream.close();
217
        }
218
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
219
        {
220
            logger.error(e,e);
221
        }
222
        return htmlTrasformationResult;
223
    }
224
 
225
    /**
226
     * ##NEW METHOD###
227
     * Gera o XML normalizado para o JAXB a partir do XML importado do XML do plano XML quese usou no upload
228
     * para garantir que está bem formado
229
     * @param userSession
230
     * @param c
231
     * @return
232
     * @throws JAXBException if XML is not weel formed
233
     */
1498 jmachado 234
    private void generateXmlJaxbStudiesPlanVersion(UserSession userSession, Course c,boolean forceFichaCurricularUrlSet,1.5.0/docs/api/java/lang/String.html">String systemUrl) throws JAXBException, TransformationException
1496 jmachado 235
    {
236
        CourseStudiesPlan courseStudiesPlan;
1500 jmachado 237
        if(c.getStudiesPlan() == null || c.getStudiesPlan().trim().length() == 0)
238
        {
239
            logger.warn("Course does not have studies plan XML file stream to use in update");
240
            return;
241
        }
1496 jmachado 242
 
243
        if(c.getStudiesPlans() == null || c.getStudiesPlans().size() == 0)
244
        {
245
            logger.info("Generating first study plan");
246
            courseStudiesPlan = DomainObjectFactory.createCourseStudiesPlanImpl();
247
            courseStudiesPlan.setVersion(1);
248
            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());
249
            courseStudiesPlan.setCourse(c);
250
            if(c.getStudiesPlans() == null)
251
                c.setStudiesPlans(new HashSet<CourseStudiesPlan>());
252
            c.getStudiesPlans().add(courseStudiesPlan);
253
            DaoFactory.getCourseStudiesPlanDaoImpl().save(courseStudiesPlan);
254
        }
255
        else
256
        {
257
            courseStudiesPlan = c.getStudiesPlans().iterator().next();
258
            logger.info("Updating Study Plan version " + courseStudiesPlan.getVersion());
259
        }
260
 
261
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;
262
        IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
1502 jmachado 263
        long lastVersion = repositoryService.loadView(c.getStudiesPlan()).getLastVersion().getId();
1496 jmachado 264
        stream = repositoryFile.getInput();
1503 jmachado 265
        //TODO TIRAR
266
        //JUST FOR DEBUG
267
        try {
268
            1.5.0/docs/api/java/lang/System.html">System.out.println(StreamsUtils.readString(stream));
269
            stream.close();
270
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
271
            e.printStackTrace();
272
        }
273
        repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
274
        stream = repositoryFile.getInput();
1496 jmachado 275
 
276
        try {
277
            JAXBContext jc = JAXBContext.newInstance(Curso.class);
278
            Unmarshaller unmarshaller = jc.createUnmarshaller();
1503 jmachado 279
            //Just in case lets update SigesCode
1496 jmachado 280
            Curso curso = (Curso) unmarshaller.unmarshal(stream);
1503 jmachado 281
            curso.setSiges(c.getCode());
1496 jmachado 282
 
283
            Marshaller marshaller = jc.createMarshaller();
284
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
285
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter sw = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
286
            marshaller.marshal(curso, sw);
287
            //SETTING XML in COURSE STUDIES PLAN
288
            courseStudiesPlan.setXml(sw.toString());
289
            //##NOVO PARA GERAR LINK SE NAO EXISTIR
1498 jmachado 290
            generateAutoUrlFichasCurriculares(curso,systemUrl,forceFichaCurricularUrlSet);
1496 jmachado 291
            1.5.0/docs/api/java/lang/String.html">String json = getGensonCursoXmlObj().serialize(curso);
292
            //SETTING JSON in COURSE STUDIES PLAN
293
            courseStudiesPlan.setJson(json);
294
 
295
        } catch (JAXBException e) {
296
            logger.error(e,e);
1502 jmachado 297
            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 298
            throw e;
299
        } catch (TransformationException e) {
300
            logger.error(e, e);
301
            throw e;
302
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
303
            e.printStackTrace();
304
        }
305
        try
306
        {
307
            stream.close();
308
        }
309
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
310
        {
311
            logger.error(e,e);
312
        }
313
    }
314
 
315
    private void generateAutoUrlFichasCurriculares(Curso curso,1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean force)
316
    {
317
        for(Curso.Semestre s :curso.getSemestre())
318
        {
319
            for(Curso.Semestre.Perfil p :s.getPerfil())
248 jmachado 320
            {
1496 jmachado 321
                for(UnidadeType unidadeType : p.getUnidade())
322
                {
323
                    generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
324
                }
248 jmachado 325
            }
1496 jmachado 326
            for(UnidadeType unidadeType : s.getUnidade())
214 jmachado 327
            {
1496 jmachado 328
                generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
214 jmachado 329
            }
330
        }
331
    }
332
 
1496 jmachado 333
    private void generateAutoUrlUnidade(UnidadeType unidadeType,1.5.0/docs/api/java/lang/String.html">String systemUrl,Curso curso,Curso.Semestre semestre,boolean force)
334
    {
335
        if(force || unidadeType.getUrlFichaCurricular() == null || unidadeType.getUrlFichaCurricular().trim().length()==0)
336
        {
337
            logger.info("GENERATING FICHA CURRICULAR URL For " + unidadeType.getNome());
338
            1.5.0/docs/api/java/lang/String.html">String url = systemUrl != null ? systemUrl : "";
339
            if(!url.endsWith("/;"))
340
                url = url + "/";
341
            unidadeType.setUrlFichaCurricular(url + "startLoadCourseUnitSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
342
        }
343
    }
344
 
345
 
346
    private static Genson getGensonCursoXmlObj(){
347
        Genson genson = new Genson.Builder()
348
                .exclude("class")
349
                .create();
350
        return genson;
351
    }
352
 
353
 
354
 
355
    private static Genson getGensonCourse(){
356
        Genson genson = new Genson.Builder()
357
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
358
                .setUseFields(false)
359
                .setUseGettersAndSetters(true)
360
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
361
                .exclude("admin")
362
                .exclude("autoBlock")
363
                .exclude("autoBlockMode")
364
                .exclude("manualBlock")
365
                .exclude("newUser")
366
                .exclude("student")
367
                .exclude("superuser")
368
                .exclude("superuserOrAdmin")
369
                .exclude("teacher")
370
                .exclude("unitCheck")
371
                .exclude("id")
372
 
373
/*              .exclude(Course.class)
374
                .exclude(CourseImpl.class)
375
                .exclude(GenericUser.class)
376
                .exclude(User.class)
377
                .exclude(UserImpl.class)
378
                .exclude(Teacher.class)
379
                .exclude(TeacherImpl.class)
380
                .exclude(SigesUser.class)
381
                .exclude(SigesUserImpl.class)
382
                .exclude(GenericUser.class)
383
                .exclude(GenericUserImpl.class)
384
*/
385
                .exclude("id", Course.class)
386
                .exclude("status",Course.class)
387
                .include("degreeForJsonApi", CourseImpl.class)
388
                .include("schoolForJsonApi", CourseImpl.class)
389
                .include("statusForJsonApi", CourseImpl.class)
390
 
391
                .include("name", Course.class)
392
                .include("code", Course.class)
1500 jmachado 393
                .include("validationRole", Course.class)
394
 
1496 jmachado 395
                .include("courseComission", CourseImpl.class)
396
 
397
                .include("name", GenericUser.class)
398
                .include("email", GenericUser.class)
399
                .include("sigesCode", SigesUser.class)
400
                .include("coordinator", Course.class)
401
                .create();
402
 
403
        return genson;
404
    }
405
 
406
 
407
 
214 jmachado 408
    public List<CourseView> loadCourses() throws ServiceException
409
    {
410
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
411
        List<CourseView> courseViews = new ArrayList<CourseView>();
412
        for(Course c: courses)
413
        {
414
            CourseView courseView = new CourseView(c);
415
            courseViews.add(courseView);
416
        }
417
        return courseViews;
418
    }
419
 
376 jmachado 420
    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
421
    {
1312 jmachado 422
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
423
    }
424
 
425
    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
426
    {
427
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
376 jmachado 428
        List<CourseView> courseViews = new ArrayList<CourseView>();
429
        for(Course c: courses)
430
        {
431
            CourseView courseView = new CourseView(c);
432
            courseViews.add(courseView);
433
        }
434
        return courseViews;
435
    }
436
 
249 jmachado 437
    public List<CourseView> loadCoursesImportYear() throws ServiceException
438
    {
995 jmachado 439
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
249 jmachado 440
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
441
        List<CourseView> courseViews = new ArrayList<CourseView>();
442
        for(Course c: courses)
443
        {
444
            CourseView courseView = new CourseView(c);
445
            courseViews.add(courseView);
446
        }
447
        return courseViews;
448
    }
417 jmachado 449
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
450
    {
995 jmachado 451
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
695 jmachado 452
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
417 jmachado 453
        List<CourseView> courseViews = new ArrayList<CourseView>();
454
        for(Course c: courses)
455
        {
456
            CourseView courseView = new CourseView(c);
457
            courseViews.add(courseView);
458
        }
459
        return courseViews;
460
    }
214 jmachado 461
 
790 jmachado 462
    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
463
    {
995 jmachado 464
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
790 jmachado 465
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
466
        List<CourseView> courseViews = new ArrayList<CourseView>();
467
        for(Course c: courses)
468
        {
469
            CourseView courseView = new CourseView(c);
470
            courseViews.add(courseView);
471
        }
472
        return courseViews;
473
    }
249 jmachado 474
 
1500 jmachado 475
 
476
 
477
    /** JSON API **/
478
    /**
479
     * @SERVICE@
480
     *
481
     * @param school
482
     * @param type
483
     * @return
484
     * @throws JSONException
485
     */
1496 jmachado 486
    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 {
487
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
488
        1.5.0/docs/api/java/lang/String.html">String degree = null;
489
        if(school != null && school.length() > 0)
490
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);
249 jmachado 491
 
1496 jmachado 492
        if(type != null && type.length() > 0)
493
            degree = ConfigProperties.getProperty("course.inverse." + type);
790 jmachado 494
 
1496 jmachado 495
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(institutionalCode,degree);
496
        JSONObject coursesResponse = new JSONObject();
497
 
498
        JSONArray coursesArray = new JSONArray();
499
        for(Course cAux: courses)
500
        {
501
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
502
            JSONObject courseJson = new JSONObject();
503
            courseJson.put("name",c.getName());
504
            courseJson.put("code",c.getCode());
505
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
506
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
507
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
508
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
509
            coursesArray.put(courseJson);
510
 
511
        }
512
        coursesResponse.put("status","ok");
513
        coursesResponse.put("courses",coursesArray);
514
 
515
        return coursesResponse;
516
    }
517
 
1500 jmachado 518
    /**
519
     *
520
     * * @SERVICE@
521
     *
522
     * @param code
523
     * @return
524
     * @throws JSONException
525
     * @throws IOException
526
     * @throws TransformationException
527
     * @throws JAXBException
528
     */
1498 jmachado 529
    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 530
 
531
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
532
 
533
 
534
        JSONObject coursesResponse = new JSONObject();
535
 
1498 jmachado 536
        if(course.getJson() == null)
537
        {
538
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
539
            new CoursesService().generateCourseJson(course);
540
        }
541
 
1496 jmachado 542
        if(course.getJson() != null)
543
        {
544
            JSONObject courseObj = new JSONObject(course.getJson());
545
            coursesResponse.put("courseInfo",courseObj);
1500 jmachado 546
            if(course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1498 jmachado 547
            {
548
                logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
549
                UserSession userSession = DomainObjectFactory.createUserSessionImpl();
550
                userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
551
                new CoursesService().generateXmlJaxbStudiesPlanVersion(userSession, course, false, null);
552
            }
553
 
1496 jmachado 554
            if(course.getStudiesPlans() != null)
555
            {
556
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
557
                JSONObject studiesPlanObj = new JSONObject(studiesPlan.getJson());
558
                studiesPlanObj.put("version",studiesPlan.getVersion());
559
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
560
            }
561
            else
562
            {
563
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
564
            }
565
        }
566
        else
567
        {
568
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE");
569
        }
570
        return coursesResponse;
571
    }
572
 
1500 jmachado 573
    /**
574
     * @SERVICE@
575
     *
576
     * @param code
577
     * @return
578
     * @throws JSONException
579
     */
1502 jmachado 580
    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 581
 
582
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
1501 jmachado 583
 
1502 jmachado 584
        if(renew != null || course.getStudiesPlans() == null || course.getStudiesPlans().size() == 0)
1501 jmachado 585
        {
586
            logger.info("status JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE, will generate");
587
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
588
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
589
            try {
590
                generateXmlJaxbStudiesPlanVersion(userSession, course, false, null);
591
            } catch (JAXBException e) {
592
                logger.error(e,e);
593
                return "<error>" + e.toString() + ". see log for details</error>";
594
            } catch (TransformationException e) {
595
                logger.error(e, e);
596
                return "<error>" + e.toString() + ". see log for details</error>";
597
            }
598
        }
599
 
1496 jmachado 600
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
601
        {
602
            return course.getStudiesPlans().iterator().next().getXml();
603
        }
604
        return "<error>Does not exixt</error>";
605
 
606
    }
607
 
608
 
1500 jmachado 609
    /**
610
     * @SERVICE@
611
     *
612
     * @param systemUrl
613
     * @param setActive
614
     * @return
615
     * @throws IOException
616
     * @throws JSONException
617
     * @throws TransformationException
618
     * @throws JAXBException
619
     */
1496 jmachado 620
 
1502 jmachado 621
    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 622
 
1497 jmachado 623
        1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder log = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
624
        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 625
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
626
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
627
        JSONObject obj = new JSONObject(str);
628
        JSONArray courses = obj.getJSONArray("courses");
629
        for(int i = 0; i < courses.length();i++)
630
        {
1502 jmachado 631
            1.5.0/docs/api/java/lang/String.html">String code = "";
632
            try{
633
                JSONObject course = courses.getJSONObject(i);
634
                code = course.getString("code");
635
                Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
636
                if(c == null)
637
                {
638
                    1.5.0/docs/api/java/lang/String.html">String msg = "SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system";
639
                    log.append("<info>" + msg+"</info>");
640
                    logger.info(msg);
641
                }
642
                else
643
                {
644
                    1.5.0/docs/api/java/lang/String.html">String msg = "UPDATING - Course " + code + " " + course.getString("name") + " exist in this system";
645
                    log.append("<info>" + msg+"</info>");
646
                    logger.info(msg);
1500 jmachado 647
 
1502 jmachado 648
                    //#############UPDATING STUDIES PLAN
649
                    updateStudiesPlanFromRemoteSystem(systemUrl, setActive, log, course, code, c);
1500 jmachado 650
 
1502 jmachado 651
                    //#############UPDATING Course Comission Members
652
                    updateCourseComissionMembers(systemUrl, code, c);
653
                }
1500 jmachado 654
            }
1502 jmachado 655
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
656
            {
657
                logger.error("UPDATE COURSE: " + i + " code: " + code + " FAILED");
658
                logger.error(e,e);
659
            }
1500 jmachado 660
        }
661
        return log.toString();
662
 
663
    }
664
 
665
    /**
666
     * Update courseComission Members
667
     * @param systemUrl
668
     * @param code
669
     * @param c
670
     * @throws IOException
671
     * @throws JSONException
672
     */
673
    private void updateCourseComissionMembers(1.5.0/docs/api/java/lang/String.html">String systemUrl, 1.5.0/docs/api/java/lang/String.html">String code, Course c) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException {
674
        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);
675
        5+0%2Fdocs%2Fapi+InputStream">InputStream isCourseDetails = urlCourseDetails.openStream();
676
        1.5.0/docs/api/java/lang/String.html">String strCourseDetails = StreamsUtils.readString(isCourseDetails);
677
        JSONObject objCourseDetails = new JSONObject(strCourseDetails);
678
        1.5.0/docs/api/java/lang/String.html">String validationRole = objCourseDetails.getJSONObject("courseInfo").getString("validationRole");
679
 
680
        if(validationRole == null)
681
        {
682
            logger.info("validationRole is not defined");
683
        }
684
        else
685
        {
686
            logger.info("found validationRole: " + validationRole);
687
            c.setValidationRole(validationRole);
688
 
689
            JSONObject coordinator = objCourseDetails.getJSONObject("courseInfo").getJSONObject("coordinator");
690
            JSONArray courseComission = objCourseDetails.getJSONObject("courseInfo").getJSONArray("courseComission");
691
 
692
            Teacher coordinatorPersistent = findPersonFromCourseDetails(coordinator);
693
            if(coordinatorPersistent == null)
694
            {
695
                logger.warn("Coordinator does not exist in this system ");
696
            }
697
            else
698
            {
699
                c.setCoordinator(coordinatorPersistent);
700
            }
701
            for(int j = 0 ; j < courseComission.length(); j++)
702
            {
703
                JSONObject memberComission = courseComission.getJSONObject(j);
704
                Teacher memberPersistent = findPersonFromCourseDetails(memberComission);
705
                if(memberPersistent == null)
1496 jmachado 706
                {
1500 jmachado 707
                    logger.info("Member does not exist in this system ");
1496 jmachado 708
                }
709
                else
710
                {
1500 jmachado 711
                    logger.info("Adding role of course comission member");
712
                    if(!memberPersistent.hasRole(validationRole))
1497 jmachado 713
                    {
1500 jmachado 714
                        memberPersistent.addRole(validationRole);
1497 jmachado 715
                    }
1500 jmachado 716
                }
1497 jmachado 717
 
1496 jmachado 718
            }
719
        }
1500 jmachado 720
    }
1497 jmachado 721
 
1500 jmachado 722
    private Teacher findPersonFromCourseDetails(JSONObject coordinator) {
723
        int code;
724
        try {
725
            if(coordinator.has("sigesCode"))
726
            {
727
                code = coordinator.getInt("sigesCode");
728
            }
729
            else
730
            {
731
                logger.warn("there is no sigesCode for this person " + coordinator.toString());
732
                return null;
733
            }
734
        } catch (JSONException e){
735
            return null;
736
        } catch (1.5.0/docs/api/java/lang/NumberFormatException.html">NumberFormatException e){
737
            return null;
738
        }
739
        return DaoFactory.getTeacherDaoImpl().loadBySigesCode(code);
1496 jmachado 740
    }
741
 
1500 jmachado 742
    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 {
743
        1.5.0/docs/api/java/lang/String.html">String msg;
1502 jmachado 744
        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();
1500 jmachado 745
        1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
746
        int len = studiesPlan.length();
747
        if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
748
        {
749
            msg = "Course " + code + " " + course.getString("name") + " dont has studies plan";
750
            log.append("<warn>" + msg+"</warn>");
751
            logger.warn(msg);
752
        }
753
        else
754
        {
755
            msg = "Found studies plan for "  + code + " " + course.getString("name") + " will update ";
756
            log.append("<info>" + msg+"</info>");
757
            logger.info(msg);
758
            if(setActive)
759
            {
760
                msg = "Setting course to active";
761
                log.append("<info>" + msg+"</info>");
762
                logger.info(msg);
763
                c.setStatus(true);
764
            }
765
            //System.out.println(studiesPlan);
766
            msg = "GENERATING COURSE JSON ....";
767
            log.append("<info>" + msg+"</info>");
768
            logger.info(msg);
769
            new CoursesService().generateCourseJson(c);
1496 jmachado 770
 
1500 jmachado 771
            msg="GENERATING COURSE STUDIES PLAN JSON ....";
772
            log.append("<info>" + msg+"</info>");
773
            logger.info(msg);
774
            stream.close();
775
            stream = new 1.5.0/docs/api/java/net/URL.html">URL(systemUrl + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
776
            UserSession userSession = DomainObjectFactory.createUserSessionImpl();
777
            userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
1502 jmachado 778
            new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,systemUrl);
1500 jmachado 779
        }
780
    }
1496 jmachado 781
 
1500 jmachado 782
 
214 jmachado 783
}