Subversion Repositories bacoAlunos

Rev

Rev 1312 | 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;
6
import jomm.dao.impl.AbstractDao;
417 jmachado 7
import jomm.utils.FilesUtils;
1496 jmachado 8
import jomm.utils.StreamsUtils;
417 jmachado 9
import org.apache.log4j.Logger;
10
import org.dom4j.Document;
1496 jmachado 11
import org.json.JSONArray;
12
import org.json.JSONException;
13
import org.json.JSONObject;
417 jmachado 14
import pt.estgp.estgweb.Globals;
1496 jmachado 15
import pt.estgp.estgweb.domain.*;
417 jmachado 16
import pt.estgp.estgweb.domain.dao.DaoFactory;
17
import pt.estgp.estgweb.domain.views.CourseView;
18
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
1496 jmachado 19
import pt.estgp.estgweb.services.courses.xsd.Curso;
20
import pt.estgp.estgweb.services.courses.xsd.UnidadeType;
417 jmachado 21
import pt.estgp.estgweb.services.data.IRepositoryFile;
214 jmachado 22
import pt.estgp.estgweb.services.data.RepositoryService;
444 jmachado 23
import pt.estgp.estgweb.services.expceptions.AlreadyExistsException;
995 jmachado 24
import pt.estgp.estgweb.services.expceptions.ServiceException;
1496 jmachado 25
import pt.estgp.estgweb.utils.ConfigProperties;
248 jmachado 26
import pt.estgp.estgweb.utils.Dom4jUtil;
417 jmachado 27
import pt.utl.ist.berserk.logic.serviceManager.IService;
214 jmachado 28
 
1496 jmachado 29
import javax.xml.bind.JAXBContext;
30
import javax.xml.bind.JAXBException;
31
import javax.xml.bind.Marshaller;
32
import javax.xml.bind.Unmarshaller;
33
import java.io.*;
34
import java.net.URL;
35
import java.util.*;
214 jmachado 36
 
37
/*
38
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
39
 *
40
 *
41
 * Created at 17/Out/2003 , 23:45:24
42
 *
43
 */
44
/**
45
 * @author Jorge Machado
46
 *
47
 *
48
 * Created at 17/Out/2003 , 23:45:24
49
 *
50
 */
51
public class CoursesService implements IService
52
{
53
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(CoursesService.class);
54
 
55
    RepositoryService repositoryService = new RepositoryService();
56
 
57
 
58
    public CourseView loadCourse(long id, boolean initUnits) throws ServiceException
59
    {
60
        Course c = DaoFactory.getCourseDaoImpl().get(id);
61
 
62
        if(c != null)
63
        {
64
            CourseView cV = new CourseView(c,initUnits);
65
            if(c.getStudiesPlan() != null)
66
            {
67
                RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
68
                cV.setStudiesPlan(repositoryFile);
69
            }
70
 
71
            return cV;
72
        }
73
        return null;
74
    }
75
 
345 jmachado 76
    public List<String> loadImportYears(UserSession userSession) throws ServiceException
77
    {
78
        List<String> importYears = DaoFactory.getCourseDaoImpl().loadImportYears();
79
        List<String> imStrings = new ArrayList<String>();
80
        for(1.5.0/docs/api/java/lang/String.html">String importYear: importYears)
81
        {
82
            imStrings.add(importYear);
83
        }
84
        return imStrings;
85
    }
86
 
214 jmachado 87
    public CourseView loadCourseByCode(1.5.0/docs/api/java/lang/String.html">String code, boolean initUnits) throws ServiceException
88
    {
444 jmachado 89
        try{
90
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
91
            if(c != null)
214 jmachado 92
            {
444 jmachado 93
                CourseView cV = new CourseView(c,initUnits);
94
                if(c.getStudiesPlan() != null)
95
                {
96
                    RepositoryFileImpl repositoryFile = repositoryService.loadView(c.getStudiesPlan());
97
                    cV.setStudiesPlan(repositoryFile);
98
                }
99
                return cV;
214 jmachado 100
            }
101
        }
444 jmachado 102
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
103
        {
104
            logger.error(e + " loading code:" + code,e);
105
            throw new ServiceException("loading code: " + code  + " - " + e.toString(),e);
106
        }
214 jmachado 107
        return null;
108
    }
109
 
110
    public CourseView submitCourse(CourseView courseView,
111
                                   5+0%2Fdocs%2Fapi+InputStream">InputStream stream,
112
                                   1.5.0/docs/api/java/lang/String.html">String name,
113
                                   int size,
114
                                   1.5.0/docs/api/java/lang/String.html">String contentType,
1496 jmachado 115
                                   UserSession userSession) throws ServiceException, JAXBException, TransformationException, 1.5.0/docs/api/java/io/IOException.html">IOException {
214 jmachado 116
        Course c;
117
        if(courseView.getId() > 0)
444 jmachado 118
        {
214 jmachado 119
            c = DaoFactory.getCourseDaoImpl().get(courseView.getId());
444 jmachado 120
        }
214 jmachado 121
        else
122
        {
444 jmachado 123
            c = DaoFactory.getCourseDaoImpl().findCourseByCodeAndYear(courseView.getCode(),courseView.getImportYear());
124
            if(c != null)
125
                throw new AlreadyExistsException(AlreadyExistsException.ALREADY_EXISTS_COURSE);      
214 jmachado 126
            c = DomainObjectFactory.createCourseImpl();
127
            DaoFactory.getCourseDaoImpl().save(c);
128
        }
129
 
248 jmachado 130
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
131
 
1496 jmachado 132
        htmlTrasformationResult = uploadStudiesPlan(stream, name, size, contentType, userSession, c,false,null);
133
        courseView.persistViewInObject(c);
134
        CourseView cv = loadCourse(c.getId(),false);
135
        cv.setHtmlResult(htmlTrasformationResult);
136
 
137
        /**
138
         * New## generating course json
139
         */
140
        generateCourseJson(c);
141
 
142
        return cv;
143
    }
144
 
145
    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 {
146
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
214 jmachado 147
        if(stream != null && size > 0)
148
        {
268 jmachado 149
            1.5.0/docs/api/java/lang/String.html">String extension = FilesUtils.getExtension(name);
150
            if(c.getStudiesPlan() == null)
151
            {
332 jmachado 152
                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 153
                c.setStudiesPlan(identifier);
154
            }
155
            else
156
            {
157
                repositoryService.updateRepositoryFile(c.getStudiesPlan(), stream, contentType, extension, size, name, "course.studies.plan " + c.getName(), ResourceAccessControlEnum.publicDomain);
158
            }
1496 jmachado 159
            htmlTrasformationResult = generateHtmlCache(userSession, c);
160
            //####New#### Generating XML with JaxB
161
            generateXmlJaxbStudiesPlanVersion(userSession, c,forceUrlFichas,systemUrl);
162
        }
163
        return htmlTrasformationResult;
164
    }
165
 
166
    private void generateCourseJson(Course cAux) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
167
        CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
168
 
169
        if(c.getValidationRole() != null && c.getValidationRole().trim().length() > 0)
170
        {
171
            List<Teacher> courseComissionProxys = DaoFactory.getUserDaoImpl().loadRoleTeachers(c.getValidationRole());
172
            List<Teacher> courseComission = new ArrayList<Teacher>();
173
            for(Teacher t: courseComissionProxys)
248 jmachado 174
            {
1496 jmachado 175
                courseComission.add(DaoFactory.getTeacherDaoImpl().narrow(t));
248 jmachado 176
            }
1496 jmachado 177
            c.setCourseComission(courseComission);
178
        }
179
        //Getting Coordinator from proxy
180
        Teacher t = c.getCoordinator();
181
        t.getName();
182
 
183
        1.5.0/docs/api/java/lang/String.html">String jsonCourse = getGensonCourse().serialize(c);
184
        c.setJson(jsonCourse);
185
    }
186
 
187
    private 1.5.0/docs/api/java/lang/String.html">String generateHtmlCache(UserSession userSession, Course c) {
188
        1.5.0/docs/api/java/lang/String.html">String htmlTrasformationResult = null;
189
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
190
        stream = repositoryFile.getInput();
191
        try
192
        {
193
            5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(stream);
194
            Map<String,Object> parameters = new HashMap<String,Object>();
195
            parameters.put("COURSE_SIGES_CODE",c.getCode());
196
            1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.styleDocument(dom, Globals.TEMPLATE_COURSE_XSL_PATH,parameters);
197
            c.setCacheWebDocument(html);
198
        }
199
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
200
        {
201
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
202
            1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter printWriter = new 1.5.0/docs/api/java/io/PrintWriter.html">PrintWriter(writer);
203
            e.printStackTrace(printWriter);
204
            htmlTrasformationResult = "<div class=\"error\"><pre>" + e.toString() + "\n" + printWriter.toString() + "</pre></div>";
205
            printWriter.close();
206
        }
207
        try
208
        {
209
            stream.close();
210
        }
211
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
212
        {
213
            logger.error(e,e);
214
        }
215
        return htmlTrasformationResult;
216
    }
217
 
218
    /**
219
     * ##NEW METHOD###
220
     * Gera o XML normalizado para o JAXB a partir do XML importado do XML do plano XML quese usou no upload
221
     * para garantir que está bem formado
222
     * @param userSession
223
     * @param c
224
     * @return
225
     * @throws JAXBException if XML is not weel formed
226
     */
227
    private void generateXmlJaxbStudiesPlanVersion(UserSession userSession, Course c,boolean force,1.5.0/docs/api/java/lang/String.html">String systemUrl) throws JAXBException, TransformationException
228
    {
229
        CourseStudiesPlan courseStudiesPlan;
230
 
231
        if(c.getStudiesPlans() == null || c.getStudiesPlans().size() == 0)
232
        {
233
            logger.info("Generating first study plan");
234
            courseStudiesPlan = DomainObjectFactory.createCourseStudiesPlanImpl();
235
            courseStudiesPlan.setVersion(1);
236
            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());
237
            courseStudiesPlan.setCourse(c);
238
            if(c.getStudiesPlans() == null)
239
                c.setStudiesPlans(new HashSet<CourseStudiesPlan>());
240
            c.getStudiesPlans().add(courseStudiesPlan);
241
            DaoFactory.getCourseStudiesPlanDaoImpl().save(courseStudiesPlan);
242
        }
243
        else
244
        {
245
            courseStudiesPlan = c.getStudiesPlans().iterator().next();
246
            logger.info("Updating Study Plan version " + courseStudiesPlan.getVersion());
247
        }
248
 
249
        5+0%2Fdocs%2Fapi+InputStream">InputStream stream;
250
        IRepositoryFile repositoryFile = repositoryService.load(c.getStudiesPlan(),userSession);
251
        stream = repositoryFile.getInput();
252
 
253
        try {
254
            JAXBContext jc = JAXBContext.newInstance(Curso.class);
255
            Unmarshaller unmarshaller = jc.createUnmarshaller();
256
            Curso curso = (Curso) unmarshaller.unmarshal(stream);
257
 
258
            Marshaller marshaller = jc.createMarshaller();
259
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
260
            1.5.0/docs/api/java/io/StringWriter.html">StringWriter sw = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
261
            marshaller.marshal(curso, sw);
262
            //SETTING XML in COURSE STUDIES PLAN
263
            courseStudiesPlan.setXml(sw.toString());
264
            //##NOVO PARA GERAR LINK SE NAO EXISTIR
265
            generateAutoUrlFichasCurriculares(curso,systemUrl,force);
266
            1.5.0/docs/api/java/lang/String.html">String json = getGensonCursoXmlObj().serialize(curso);
267
            //SETTING JSON in COURSE STUDIES PLAN
268
            courseStudiesPlan.setJson(json);
269
 
270
        } catch (JAXBException e) {
271
            logger.error(e,e);
272
            throw e;
273
        } catch (TransformationException e) {
274
            logger.error(e, e);
275
            throw e;
276
        } catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
277
            e.printStackTrace();
278
        }
279
        try
280
        {
281
            stream.close();
282
        }
283
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
284
        {
285
            logger.error(e,e);
286
        }
287
    }
288
 
289
    private void generateAutoUrlFichasCurriculares(Curso curso,1.5.0/docs/api/java/lang/String.html">String systemUrl,boolean force)
290
    {
291
        for(Curso.Semestre s :curso.getSemestre())
292
        {
293
            for(Curso.Semestre.Perfil p :s.getPerfil())
248 jmachado 294
            {
1496 jmachado 295
                for(UnidadeType unidadeType : p.getUnidade())
296
                {
297
                    generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
298
                }
248 jmachado 299
            }
1496 jmachado 300
            for(UnidadeType unidadeType : s.getUnidade())
214 jmachado 301
            {
1496 jmachado 302
                generateAutoUrlUnidade(unidadeType,systemUrl,curso,s,force);
214 jmachado 303
            }
304
        }
305
    }
306
 
1496 jmachado 307
    private void generateAutoUrlUnidade(UnidadeType unidadeType,1.5.0/docs/api/java/lang/String.html">String systemUrl,Curso curso,Curso.Semestre semestre,boolean force)
308
    {
309
        if(force || unidadeType.getUrlFichaCurricular() == null || unidadeType.getUrlFichaCurricular().trim().length()==0)
310
        {
311
            logger.info("GENERATING FICHA CURRICULAR URL For " + unidadeType.getNome());
312
            1.5.0/docs/api/java/lang/String.html">String url = systemUrl != null ? systemUrl : "";
313
            if(!url.endsWith("/;"))
314
                url = url + "/";
315
            unidadeType.setUrlFichaCurricular(url + "startLoadCourseUnitSiges.do?unitCode=" + unidadeType.getSiges() + "&courseCode=" + curso.getSiges() + "&semestre=" + semestre.getId());
316
        }
317
    }
318
 
319
 
320
    private static Genson getGensonCursoXmlObj(){
321
        Genson genson = new Genson.Builder()
322
                .exclude("class")
323
                .create();
324
        return genson;
325
    }
326
 
327
 
328
 
329
    private static Genson getGensonCourse(){
330
        Genson genson = new Genson.Builder()
331
                .exclude(5+0%2Fdocs%2Fapi+Object">Object.class)
332
                .setUseFields(false)
333
                .setUseGettersAndSetters(true)
334
                .setMethodFilter(VisibilityFilter.PACKAGE_PUBLIC)
335
                .exclude("admin")
336
                .exclude("autoBlock")
337
                .exclude("autoBlockMode")
338
                .exclude("manualBlock")
339
                .exclude("newUser")
340
                .exclude("student")
341
                .exclude("superuser")
342
                .exclude("superuserOrAdmin")
343
                .exclude("teacher")
344
                .exclude("unitCheck")
345
                .exclude("id")
346
 
347
/*              .exclude(Course.class)
348
                .exclude(CourseImpl.class)
349
                .exclude(GenericUser.class)
350
                .exclude(User.class)
351
                .exclude(UserImpl.class)
352
                .exclude(Teacher.class)
353
                .exclude(TeacherImpl.class)
354
                .exclude(SigesUser.class)
355
                .exclude(SigesUserImpl.class)
356
                .exclude(GenericUser.class)
357
                .exclude(GenericUserImpl.class)
358
*/
359
                .exclude("id", Course.class)
360
                .exclude("status",Course.class)
361
                .include("degreeForJsonApi", CourseImpl.class)
362
                .include("schoolForJsonApi", CourseImpl.class)
363
                .include("statusForJsonApi", CourseImpl.class)
364
 
365
                .include("name", Course.class)
366
                .include("code", Course.class)
367
                .include("courseComission", CourseImpl.class)
368
 
369
                .include("name", GenericUser.class)
370
                .include("email", GenericUser.class)
371
                .include("sigesCode", SigesUser.class)
372
                .include("coordinator", Course.class)
373
                .create();
374
 
375
        return genson;
376
    }
377
 
378
 
379
 
214 jmachado 380
    public List<CourseView> loadCourses() throws ServiceException
381
    {
382
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName();
383
        List<CourseView> courseViews = new ArrayList<CourseView>();
384
        for(Course c: courses)
385
        {
386
            CourseView courseView = new CourseView(c);
387
            courseViews.add(courseView);
388
        }
389
        return courseViews;
390
    }
391
 
376 jmachado 392
    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
393
    {
1312 jmachado 394
        return loadCoursesImportYearAreaInstitution(importYear, area,null);
395
    }
396
 
397
    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
398
    {
399
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null,institutionCode);
376 jmachado 400
        List<CourseView> courseViews = new ArrayList<CourseView>();
401
        for(Course c: courses)
402
        {
403
            CourseView courseView = new CourseView(c);
404
            courseViews.add(courseView);
405
        }
406
        return courseViews;
407
    }
408
 
249 jmachado 409
    public List<CourseView> loadCoursesImportYear() throws ServiceException
410
    {
995 jmachado 411
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
249 jmachado 412
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYearIntranet);
413
        List<CourseView> courseViews = new ArrayList<CourseView>();
414
        for(Course c: courses)
415
        {
416
            CourseView courseView = new CourseView(c);
417
            courseViews.add(courseView);
418
        }
419
        return courseViews;
420
    }
417 jmachado 421
    public List<CourseView> loadCoursesImportYearByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
422
    {
995 jmachado 423
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
695 jmachado 424
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
417 jmachado 425
        List<CourseView> courseViews = new ArrayList<CourseView>();
426
        for(Course c: courses)
427
        {
428
            CourseView courseView = new CourseView(c);
429
            courseViews.add(courseView);
430
        }
431
        return courseViews;
432
    }
214 jmachado 433
 
790 jmachado 434
    public List<CourseView> loadActiveCoursesByType(1.5.0/docs/api/java/lang/String.html">String type) throws ServiceException
435
    {
995 jmachado 436
        1.5.0/docs/api/java/lang/String.html">String importYearIntranet = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
790 jmachado 437
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(importYearIntranet,null,type);
438
        List<CourseView> courseViews = new ArrayList<CourseView>();
439
        for(Course c: courses)
440
        {
441
            CourseView courseView = new CourseView(c);
442
            courseViews.add(courseView);
443
        }
444
        return courseViews;
445
    }
249 jmachado 446
 
1496 jmachado 447
    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 {
448
        1.5.0/docs/api/java/lang/String.html">String institutionalCode = null;
449
        1.5.0/docs/api/java/lang/String.html">String degree = null;
450
        if(school != null && school.length() > 0)
451
            institutionalCode = ConfigProperties.getProperty("institution.code.prefix.inverse." + school);
249 jmachado 452
 
1496 jmachado 453
        if(type != null && type.length() > 0)
454
            degree = ConfigProperties.getProperty("course.inverse." + type);
790 jmachado 455
 
1496 jmachado 456
        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllActiveOrderByNameEvenWithoutCourseUnit(institutionalCode,degree);
457
        JSONObject coursesResponse = new JSONObject();
458
 
459
        JSONArray coursesArray = new JSONArray();
460
        for(Course cAux: courses)
461
        {
462
            CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(cAux);
463
            JSONObject courseJson = new JSONObject();
464
            courseJson.put("name",c.getName());
465
            courseJson.put("code",c.getCode());
466
            courseJson.put("schoolForJsonApi",c.getSchoolForJsonApi());
467
            courseJson.put("degreeForJsonApi",c.getDegreeForJsonApi());
468
            courseJson.put("statusForJsonApi",c.getStatusForJsonApi());
469
            courseJson.put("getDetailedInfoUrl","/wsjson/api?service=getCourse&code=" + c.getCode());
470
            coursesArray.put(courseJson);
471
 
472
        }
473
        coursesResponse.put("status","ok");
474
        coursesResponse.put("courses",coursesArray);
475
 
476
        return coursesResponse;
477
    }
478
 
479
    public JSONObject getCourseDetailForJsonApi(1.5.0/docs/api/java/lang/String.html">String code) throws JSONException {
480
 
481
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
482
 
483
 
484
        JSONObject coursesResponse = new JSONObject();
485
 
486
        if(course.getJson() != null)
487
        {
488
            JSONObject courseObj = new JSONObject(course.getJson());
489
            coursesResponse.put("courseInfo",courseObj);
490
            if(course.getStudiesPlans() != null)
491
            {
492
                CourseStudiesPlan studiesPlan = course.getStudiesPlans().iterator().next();
493
                JSONObject studiesPlanObj = new JSONObject(studiesPlan.getJson());
494
                studiesPlanObj.put("version",studiesPlan.getVersion());
495
                coursesResponse.put("courseStudiesPlan",studiesPlanObj);
496
            }
497
            else
498
            {
499
                coursesResponse.put("status","JSON NOT EXIST FOR STUDIES PLAN IN THIS COURSE");
500
            }
501
        }
502
        else
503
        {
504
            coursesResponse.put("status","JSON NOT EXIST FOR COURSE");
505
        }
506
        return coursesResponse;
507
    }
508
 
509
    public 1.5.0/docs/api/java/lang/String.html">String getCourseStudiesPlanXml(1.5.0/docs/api/java/lang/String.html">String code) throws JSONException {
510
 
511
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
512
        if(course.getStudiesPlans() != null && course.getStudiesPlans().size() > 0)
513
        {
514
            return course.getStudiesPlans().iterator().next().getXml();
515
        }
516
        return "<error>Does not exixt</error>";
517
 
518
    }
519
 
520
 
521
    public static void main2(1.5.0/docs/api/java/lang/String.html">String[] args) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JAXBException, TransformationException {
522
        1.5.0/docs/api/java/net/URL.html">URL urlPlan = new 1.5.0/docs/api/java/net/URL.html">URL("http://www.estgp.pt/repositoryStream/3");
523
        1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream fs = new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream("/Users/jorgemachado/Documents/workspace/baco/impl/src/xsd/curso_EI.xml");
524
 
525
        JAXBContext jc = JAXBContext.newInstance(Curso.class);
526
        Unmarshaller unmarshaller = jc.createUnmarshaller();
527
        Curso curso = (Curso) unmarshaller.unmarshal( fs);
528
        Marshaller marshaller = jc.createMarshaller();
529
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
530
        1.5.0/docs/api/java/io/StringWriter.html">StringWriter sw = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
531
        marshaller.marshal(curso, sw);
532
 
533
        1.5.0/docs/api/java/lang/String.html">String json = getGensonCursoXmlObj().serialize(curso);
534
 
535
        AbstractDao.getCurrentSession().beginTransaction();
536
 
537
        CourseImpl c = (CourseImpl) DaoFactory.getCourseDaoImpl().narrow(DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(10)));
538
 
539
        List<Teacher> courseComissionProxys = DaoFactory.getUserDaoImpl().loadRoleTeachers(c.getValidationRole());
540
        List<Teacher> courseComission = new ArrayList<Teacher>();
541
        for(Teacher t: courseComissionProxys)
542
        {
543
            courseComission.add(DaoFactory.getTeacherDaoImpl().narrow(t));
544
        }
545
        Teacher t = c.getCoordinator();
546
        t.getName();
547
 
548
 
549
        c.setCourseComission(courseComission);
550
        1.5.0/docs/api/java/lang/String.html">String jsonCourse = getGensonCourse().serialize(c);
551
 
552
        AbstractDao.getCurrentSession().getTransaction().commit();
553
        1.5.0/docs/api/java/lang/System.html">System.out.println(json);
554
 
555
        1.5.0/docs/api/java/lang/System.html">System.out.println(jsonCourse);
556
 
557
    }
558
 
559
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException, TransformationException, JAXBException {
560
        AbstractDao.getCurrentSession().beginTransaction();
561
        1.5.0/docs/api/java/lang/String.html">String system = args.length > 0 ? args[0] : "http://localhost/baco";
562
 
563
        1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(system + "/wsjson/api?service=listCourses");
564
        5+0%2Fdocs%2Fapi+InputStream">InputStream is = url.openStream();
565
        1.5.0/docs/api/java/lang/String.html">String str = StreamsUtils.readString(is);
566
        JSONObject obj = new JSONObject(str);
567
        JSONArray courses = obj.getJSONArray("courses");
568
        for(int i = 0; i < courses.length();i++)
569
        {
570
            JSONObject course = courses.getJSONObject(i);
571
            1.5.0/docs/api/java/lang/String.html">String code = course.getString("code");
572
            Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(code);
573
            if(c == null)
574
            {
575
                logger.info("SKIPING - Course " + code + " " + course.getString("name") + " does not exist in this system" );
576
            }
577
            else
578
            {
579
                logger.info("UPDATING - Course " + code + " " + course.getString("name") + " exist in this system" );
580
                5+0%2Fdocs%2Fapi+InputStream">InputStream stream = new 1.5.0/docs/api/java/net/URL.html">URL(system + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
581
                1.5.0/docs/api/java/lang/String.html">String studiesPlan = StreamsUtils.readString(stream);
582
                int len = studiesPlan.length();
583
                if(studiesPlan == null || studiesPlan.trim().length() == 0 || studiesPlan.contains("<error>"))
584
                {
585
                    logger.error("Course " + code + " " + course.getString("name") + " dont has studies plan");
586
                }
587
                else
588
                {
589
                    logger.info("Found studies plan for "  + code + " " + course.getString("name") + " will update ");
590
                    //System.out.println(studiesPlan);
591
                    logger.info("GENERATING COURSE JSON ....");
592
                    new CoursesService().generateCourseJson(c);
593
                    logger.info("GENERATING COURSE STUDIES PLAN JSON ....");
594
                    stream.close();
595
                    stream = new 1.5.0/docs/api/java/net/URL.html">URL(system + "/wsjson/api?service=getStudiesPlanXml&code=" + code).openStream();
596
                    UserSession userSession = DomainObjectFactory.createUserSessionImpl();
597
                    userSession.setUser(DaoFactory.getUserDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(1)));
598
                    new CoursesService().uploadStudiesPlan(stream, "curso_" + code + ".xml", len,"appication/xml", userSession,c,true,"http://www.estgp.pt");
599
                }
600
            }
601
        }
602
        AbstractDao.getCurrentSession().getTransaction().commit();
603
    }
604
 
605
 
606
 
214 jmachado 607
}