Subversion Repositories bacoAlunos

Rev

Rev 1995 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1814 jmachado 1
package pt.estgp.estgweb.services.courses;
2
 
1830 jmachado 3
 
1848 jmachado 4
import jomm.dao.impl.AbstractDao;
1830 jmachado 5
import jomm.utils.StreamsUtils;
1814 jmachado 6
import org.apache.log4j.Logger;
1830 jmachado 7
import org.json.JSONArray;
8
import org.json.JSONException;
9
import org.json.JSONObject;
1887 grupo5 10
import pt.estgp.estgweb.domain.*;
1814 jmachado 11
import pt.estgp.estgweb.domain.dao.DaoFactory;
1887 grupo5 12
import pt.estgp.estgweb.filters.chains.ResourceAccessControlEnum;
1830 jmachado 13
import pt.estgp.estgweb.services.courses.coursereport.CourseReportUtils;
14
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.*;
15
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.courseunitreport.CourseUnitSection;
1995 grupo5 16
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.learningresults.LearningAnalysisSection;
1887 grupo5 17
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.learningresults.LearningGlobalAnalysisSection;
18
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.learningresults.components.*;
1830 jmachado 19
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.CourseUnitDtpStat;
20
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.UnitDtpSemester;
21
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.reportucsummary.UnitsDtpTable;
22
import pt.estgp.estgweb.services.courses.coursereport.documentmodel.surveys.SurveysResultsSection;
1887 grupo5 23
import pt.estgp.estgweb.services.data.RepositoryFile4JsonView;
24
import pt.estgp.estgweb.services.data.RepositoryService;
1830 jmachado 25
import pt.estgp.estgweb.services.questionarios.QuestionariosReportsService;
26
import pt.estgp.estgweb.services.questionarios.pedagogico.reportprocessors.utils.DataTable;
27
import pt.estgp.estgweb.utils.Globals;
1992 grupo5 28
import pt.estgp.estgweb.utils.documentBuilder.Document;
1830 jmachado 29
import pt.estgp.estgweb.utils.documentBuilder.DocumentSection;
30
import pt.estgp.estgweb.utils.documentBuilder.QuestionariosDataTableComponent;
1887 grupo5 31
import pt.estgp.estgweb.web.controllers.utils.FileUploaded;
1814 jmachado 32
import pt.utl.ist.berserk.logic.serviceManager.IService;
33
 
1830 jmachado 34
import java.io.IOException;
35
import java.io.InputStream;
36
import java.net.URL;
1848 jmachado 37
import java.net.URLConnection;
1830 jmachado 38
import java.util.*;
1814 jmachado 39
 
40
/**
41
 * Created by jorgemachado on 14/10/17.
42
 */
43
public class CourseReportServices implements IService
44
{
45
    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(CourseReportServices.class);
46
 
1830 jmachado 47
 
48
 
49
 
50
 
51
 
52
 
53
    /****************************************************************************/
54
    /* SERVICOS CORE DOS REPORTS
55
    /****************************************************************************/
56
 
57
 
58
 
59
 
60
    /**
61
     *
62
     * @param courseCode
63
     * @param year
64
     * @return
65
     * @throws IOException
66
     * @throws JSONException
67
     */
1848 jmachado 68
    public CourseReportDocument createNewCourseReportDocument(1.5.0/docs/api/java/lang/String.html">String courseCode,1.5.0/docs/api/java/lang/String.html">String year) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
1830 jmachado 69
    {
1887 grupo5 70
 
71
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(courseCode);
72
 
1848 jmachado 73
        CourseReportDocument reportCourseDocument = new CourseReportDocument();
1887 grupo5 74
        reportCourseDocument.init(course,year);
1830 jmachado 75
 
76
 
1887 grupo5 77
 
1830 jmachado 78
        //FIRST SERVICE TO CALL TO OBTAIN UNITS AND EVALUATIONS
79
        //THIS IS THE BASE FOR THE REMAIN SERVICE CALLS
1841 jmachado 80
        List<DocumentSection> courseUnitSections = updateCleanCourseUnitSections(courseCode, year, reportCourseDocument);
1830 jmachado 81
 
1927 grupo5 82
        //A tabela de resultados globais não vai ser utilizada
83
        //PARA CORRER ESTE SERVICO A PARTIR DA INTERFACE É PRECISO
1841 jmachado 84
        //PERCEBER QUE DEPENDE DO SERVICO DE UPDATE DAS SECOES DAS COURSEUNITS
1830 jmachado 85
        UnitsLearningResultsTable unitsLearningResultsTable = updateCleanLearningResultsFromCourseUnitsSections(reportCourseDocument);
86
 
87
 
88
        //Atualiza no DOC a tabela de analise DTP
89
        UnitsDtpTable unitsDtpTable = updateDtpStatsTable4Course(reportCourseDocument, courseCode, year);
90
 
91
 
1927 grupo5 92
        //Atualiza as tabelas dos Quesitonários pedagogicos
1830 jmachado 93
        SurveysResultsSection surveysResultsSection = updateSurveysDataTables(courseCode, year, reportCourseDocument);
94
 
95
 
96
        return reportCourseDocument;
97
    }
98
 
1848 jmachado 99
    public SurveysResultsSection updateSurveysDataTables(1.5.0/docs/api/java/lang/String.html">String courseCode, 1.5.0/docs/api/java/lang/String.html">String year, CourseReportDocument reportCourseDocument) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException {
1830 jmachado 100
        SurveysSection surveysSection = (SurveysSection) reportCourseDocument.findDocumentSection(SurveysSection.class);
1848 jmachado 101
        SurveysResultsSection surveysResultsSection = (SurveysResultsSection) surveysSection.findSection(SurveysResultsSection.class);
1830 jmachado 102
        QuestionariosDataTableComponent dataTableComponentS1 = (QuestionariosDataTableComponent) surveysResultsSection.getComponents().get(0);
103
        QuestionariosDataTableComponent dataTableComponentS2 = (QuestionariosDataTableComponent) surveysResultsSection.getComponents().get(1);
104
 
105
        QuestionariosReportsService questionariosReportsService = new QuestionariosReportsService();
106
        1.5.0/docs/api/java/lang/String.html">String jsonDataTableS1 = questionariosReportsService.loadReportUnidadesSalasJson(courseCode,year,"S1");
107
        1.5.0/docs/api/java/lang/String.html">String jsonDataTableS2 = questionariosReportsService.loadReportUnidadesSalasJson(courseCode,year,"S2");
108
        DataTable dataTableS1 = DataTable.fromJson(jsonDataTableS1);
109
        DataTable dataTableS2 = DataTable.fromJson(jsonDataTableS2);
110
        dataTableComponentS1.setDataTable(dataTableS1);
111
        dataTableComponentS2.setDataTable(dataTableS2);
112
        return surveysResultsSection;
113
    }
114
 
115
    /**
1927 grupo5 116
     * Este serviço atualiza a tabela de resultados de aprendizagem com base nas courseunitssections
1830 jmachado 117
     * @param reportCourseDocument
118
     * @return UnitsLearningResultsTable
119
     */
1848 jmachado 120
    public UnitsLearningResultsTable updateCleanLearningResultsFromCourseUnitsSections(CourseReportDocument reportCourseDocument)
1841 jmachado 121
    {
1830 jmachado 122
        CourseUnitsReportsSection unitReportsSection = (CourseUnitsReportsSection) reportCourseDocument.findDocumentSection(CourseUnitsReportsSection.class);
123
 
124
        LearningResultsSection learningResultsSection = (LearningResultsSection) reportCourseDocument.findDocumentSection(LearningResultsSection.class);
125
        UnitsLearningResultsTable learningResultsTable = (UnitsLearningResultsTable) learningResultsSection.findDocComponent(UnitsLearningResultsTable.class);
126
 
127
        Map<Integer,UnitsLearningResultYear> anosPlano = new HashMap<Integer, UnitsLearningResultYear>();
128
        Map<String,UnitsLearningResultSemester> anoSemestre = new HashMap<String, UnitsLearningResultSemester>();
1848 jmachado 129
        for(DocumentSection subSection : unitReportsSection.getSections())
1830 jmachado 130
        {
131
            CourseUnitSection unitSection = (CourseUnitSection) subSection;
132
            int anoPlano = unitSection.getAnoPlano();
133
            UnitsLearningResultYear anoFound = anosPlano.get(anoPlano);
134
            if(anoFound == null)
1814 jmachado 135
            {
1830 jmachado 136
                anoFound = new UnitsLearningResultYear(anoPlano);
137
                anosPlano.put(anoPlano,anoFound);
138
                learningResultsTable.getYears().add(anoFound);
1814 jmachado 139
            }
140
 
1830 jmachado 141
            1.5.0/docs/api/java/lang/String.html">String semestreCode = ((CourseUnitSection) subSection).getPeriod();
142
            UnitsLearningResultSemester semestreFound = anoSemestre.get(anoPlano + "$" + semestreCode);
143
            if(semestreFound == null)
1814 jmachado 144
            {
1830 jmachado 145
                semestreFound = new UnitsLearningResultSemester(semestreCode);
146
                anoSemestre.put(anoPlano + "$" + semestreCode,semestreFound);
147
                anoFound.getSemesters().add(semestreFound);
1814 jmachado 148
            }
1830 jmachado 149
 
150
            UnitsLearningResultUc uc = new UnitsLearningResultUc();
151
            uc.setPeriod(semestreCode);
152
            uc.setName(unitSection.getName());
153
            uc.setSigesCode(unitSection.getSigesCode());
154
            if(unitSection.getCourseUnitEvaluation() != null)
155
            {
156
 
1843 jmachado 157
                uc.setCumprimentoProgramaPercent(unitSection.getCourseUnitEvaluation().getCumprimentoProgramaPercent());
1841 jmachado 158
                uc.setAlunosInscritos(unitSection.getCourseUnitEvaluation().getNumAlunosInscritos());
159
 
1830 jmachado 160
                uc.setAprovados1013(unitSection.getCourseUnitEvaluation().getNumAlunosAprov1013());
161
                uc.setAprovados1416(unitSection.getCourseUnitEvaluation().getNumAlunosAprov1416());
162
                uc.setAprovados1720(unitSection.getCourseUnitEvaluation().getNumAlunosAprov1720());
163
                uc.setSemElementos(unitSection.getCourseUnitEvaluation().getNumAlunosSemElementosAvaliacao());
164
                uc.setAprovados(unitSection.getCourseUnitEvaluation().getNumAlunosAprovTotal());
1887 grupo5 165
                uc.setReprovados(unitSection.getCourseUnitEvaluation().getNumAlunosInscritos() - unitSection.getCourseUnitEvaluation().getNumAlunosAprovTotal() - unitSection.getCourseUnitEvaluation().getNumAlunosSemElementosAvaliacao());
1830 jmachado 166
 
167
                if(uc.getAlunosInscritos() > 0)
168
                {
169
                    uc.setAprovadosPercent((float) (uc.getAprovados() * 100.0 / uc.getAlunosInscritos()));
170
                    uc.setReprovadosPercent((float) (uc.getReprovados() * 100.0 / uc.getAlunosInscritos()));
171
                    uc.setSemElementosPercent((float) (uc.getSemElementos() * 100.0 / uc.getAlunosInscritos()));
172
                }
173
 
174
                if(uc.getAprovados() > 0)
175
                {
176
                    uc.setAprovados1013Percent((float) (uc.getAprovados1013() * 100.0 / uc.getAprovados()));
177
                    uc.setAprovados1416Percent((float) (uc.getAprovados1416() * 100.0 / uc.getAprovados()));
178
                    uc.setAprovados1720Percent((float) (uc.getAprovados1720() * 100.0 / uc.getAprovados()));
179
                }
180
            }
181
            semestreFound.getUcs().add(uc);
1814 jmachado 182
        }
1830 jmachado 183
 
184
        1.5.0/docs/api/java/util/Collections.html">Collections.sort(learningResultsTable.getYears(), new Comparator<UnitsLearningResultYear>() {
185
            @1.5.0/docs/api/java/lang/Override.html">Override
186
            public int compare(UnitsLearningResultYear o1, UnitsLearningResultYear o2) {
187
                return o1.getAno() - o2.getAno();
188
            }
189
        });
190
 
191
        for(UnitsLearningResultYear learningYearLine: learningResultsTable.getYears())
192
        {
193
            1.5.0/docs/api/java/util/Collections.html">Collections.sort(learningYearLine.getSemesters(),new Comparator<UnitsLearningResultSemester>() {
194
                @1.5.0/docs/api/java/lang/Override.html">Override
195
                public int compare(UnitsLearningResultSemester o1, UnitsLearningResultSemester o2) {
196
                    return o1.getSemestre().compareTo(o2.getSemestre());
197
                }
198
            });
199
        }
200
 
1841 jmachado 201
 
202
        //UPDATE TOTAIS DE SEMESTRES E DE ANOS
1830 jmachado 203
        float totalCumProgPercentGlobal = 0;
1887 grupo5 204
        float totalInscritosGlobal = 0;
1830 jmachado 205
        float totalReprovadosPercentGlobal = 0;
206
        float totalAprovadosPercentGlobal = 0;
207
        float totalSemElementosPercentGlobal = 0;
1887 grupo5 208
        float totalAprovados1013PercentGlobal = 0;
1830 jmachado 209
        float totalAprovados1416PercentGlobal = 0;
210
        float totalAprovados1720PercentGlobal = 0;
211
        for(UnitsLearningResultYear learningYearLine: learningResultsTable.getYears())
212
        {
213
            float totalCumProgPercentAno = 0;
1887 grupo5 214
            float totalInscritosAno = 0;
1830 jmachado 215
            float totalReprovadosPercentAno = 0;
216
            float totalAprovadosPercentAno = 0;
217
            float totalSemElementosPercentAno = 0;
1887 grupo5 218
            float totalAprovados1013PercentAno = 0;
1830 jmachado 219
            float totalAprovados1416PercentAno = 0;
220
            float totalAprovados1720PercentAno = 0;
221
 
222
            for(UnitsLearningResultSemester semester: learningYearLine.getSemesters())
223
            {
224
                float totalCumProgPercent = 0;
1887 grupo5 225
                float totalInscritos = 0;
1830 jmachado 226
                float totalReprovadosPercent = 0;
227
                float totalAprovadosPercent = 0;
228
                float totalSemElementosPercent = 0;
1887 grupo5 229
                float totalAprovados1013Percent = 0;
1830 jmachado 230
                float totalAprovados1416Percent = 0;
231
                float totalAprovados1720Percent = 0;
232
                for(UnitsLearningResultUc uc: semester.getUcs())
233
                {
234
                    totalCumProgPercent += uc.getCumprimentoProgramaPercent();
235
                    totalInscritos += uc.getAlunosInscritos();
236
                    totalAprovadosPercent += uc.getAprovadosPercent();
237
                    totalReprovadosPercent += uc.getReprovadosPercent();
238
                    totalSemElementosPercent += uc.getSemElementosPercent();
239
                    totalAprovados1013Percent += uc.getAprovados1013();
240
                    totalAprovados1416Percent += uc.getAprovados1416();
241
                    totalAprovados1720Percent += uc.getAprovados1720();
242
                }
243
                //media de inscritos
244
                if(semester.getUcs().size() > 0)
245
                {
246
                    semester.setCumprimentoProgramaPercent( totalCumProgPercent / ((float)semester.getUcs().size()));
1887 grupo5 247
                    semester.setAlunosInscritos( totalInscritos  / ((float)semester.getUcs().size()));
1830 jmachado 248
                    semester.setAprovadosPercent( totalAprovadosPercent  / ((float)semester.getUcs().size()));
249
                    semester.setReprovadosPercent( totalReprovadosPercent  / ((float)semester.getUcs().size()));
250
                    semester.setSemElementosPercent( totalSemElementosPercent / ((float)semester.getUcs().size()));
251
                    semester.setAprovados1013Percent( totalAprovados1013Percent / ((float)semester.getUcs().size()));
252
                    semester.setAprovados1416Percent( totalAprovados1416Percent / ((float)semester.getUcs().size()));
253
                    semester.setAprovados1720Percent( totalAprovados1720Percent / ((float)semester.getUcs().size()));
254
                }
255
                totalCumProgPercentAno += semester.getCumprimentoProgramaPercent();
256
                totalInscritosAno += semester.getAlunosInscritos();
257
                totalAprovadosPercentAno += semester.getAprovadosPercent();
258
                totalReprovadosPercentAno += semester.getReprovadosPercent();
259
                totalSemElementosPercentAno += semester.getSemElementosPercent();
260
                totalAprovados1013PercentAno += semester.getAprovados1013();
261
                totalAprovados1416PercentAno += semester.getAprovados1416();
262
                totalAprovados1720PercentAno += semester.getAprovados1720();
263
            }
264
            //media de inscritos
265
            if(learningYearLine.getSemesters().size() > 0)
266
            {
267
                learningYearLine.setCumprimentoProgramaPercent( totalCumProgPercentAno / ((float)learningYearLine.getSemesters().size()));
1887 grupo5 268
                learningYearLine.setAlunosInscritos( totalInscritosAno  / ((float)learningYearLine.getSemesters().size()));
1830 jmachado 269
                learningYearLine.setAprovadosPercent( totalAprovadosPercentAno  / ((float)learningYearLine.getSemesters().size()));
270
                learningYearLine.setReprovadosPercent( totalReprovadosPercentAno  / ((float)learningYearLine.getSemesters().size()));
271
                learningYearLine.setSemElementosPercent( totalSemElementosPercentAno / ((float)learningYearLine.getSemesters().size()));
272
                learningYearLine.setAprovados1013Percent( totalAprovados1013PercentAno / ((float)learningYearLine.getSemesters().size()));
273
                learningYearLine.setAprovados1416Percent( totalAprovados1416PercentAno / ((float)learningYearLine.getSemesters().size()));
274
                learningYearLine.setAprovados1720Percent( totalAprovados1720PercentAno / ((float)learningYearLine.getSemesters().size()));
275
            }
276
            totalCumProgPercentGlobal += learningYearLine.getCumprimentoProgramaPercent();
277
            totalInscritosGlobal += learningYearLine.getAlunosInscritos();
278
            totalAprovadosPercentGlobal += learningYearLine.getAprovadosPercent();
279
            totalReprovadosPercentGlobal += learningYearLine.getReprovadosPercent();
280
            totalSemElementosPercentGlobal += learningYearLine.getSemElementosPercent();
281
            totalAprovados1013PercentGlobal += learningYearLine.getAprovados1013();
282
            totalAprovados1416PercentGlobal += learningYearLine.getAprovados1416();
283
            totalAprovados1720PercentGlobal += learningYearLine.getAprovados1720();
284
        }
285
 
286
        if(learningResultsTable.getYears().size() > 0)
287
        {
288
            learningResultsTable.setCumprimentoProgramaPercent( totalCumProgPercentGlobal / ((float)learningResultsTable.getYears().size()));
289
            learningResultsTable.setAlunosInscritos( totalInscritosGlobal  / (learningResultsTable.getYears().size()));
290
            learningResultsTable.setAprovadosPercent( totalAprovadosPercentGlobal  / ((float)learningResultsTable.getYears().size()));
291
            learningResultsTable.setReprovadosPercent( totalReprovadosPercentGlobal  / ((float)learningResultsTable.getYears().size()));
292
            learningResultsTable.setSemElementosPercent( totalSemElementosPercentGlobal / ((float)learningResultsTable.getYears().size()));
293
            learningResultsTable.setAprovados1013Percent( totalAprovados1013PercentGlobal / ((float)learningResultsTable.getYears().size()));
294
            learningResultsTable.setAprovados1416Percent( totalAprovados1416PercentGlobal / ((float)learningResultsTable.getYears().size()));
295
            learningResultsTable.setAprovados1720Percent( totalAprovados1720PercentGlobal / ((float)learningResultsTable.getYears().size()));
296
        }
297
        return learningResultsTable;
1814 jmachado 298
    }
299
 
1830 jmachado 300
 
301
    /**
1848 jmachado 302
     * Gera uma tabela de estatisticas dos DTP recorrendo ao servico WS de
1927 grupo5 303
     * load de tabelas DTP, caso o serviço nao devolva unidades são criadas novas
1848 jmachado 304
     * com os valores a falso.
305
     *
306
     * @param courseCode
307
     * @param year
308
     * @return UnitsDtpTable
309
     * @throws IOException
310
     * @throws JSONException
311
     */
312
    public UnitsDtpTable updateDtpStatsTable4Course(CourseReportDocument reportCourseDocument, 1.5.0/docs/api/java/lang/String.html">String courseCode, 1.5.0/docs/api/java/lang/String.html">String year) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
313
    {
314
 
315
        ReportsUcSummarySection reportsUcSummarySection = (ReportsUcSummarySection) reportCourseDocument.findDocumentSection(ReportsUcSummarySection.class);
316
        UnitsDtpTable unitsDtpTable = (UnitsDtpTable) reportsUcSummarySection.findDocComponent(UnitsDtpTable.class);
317
        UnitDtpSemester semester1 = new UnitDtpSemester();
318
        UnitDtpSemester semester2 = new UnitDtpSemester();
319
        unitsDtpTable.setSemester1(semester1);
320
        unitsDtpTable.setSemester2(semester2);
321
 
322
        List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
323
 
324
        CourseUnitDtpStat[] statsLoaded;
325
        try
326
        {
327
            1.5.0/docs/api/java/lang/String.html">String json = loadCourseUnitDtpStats(courseCode,year);
328
            JSONObject response = new JSONObject(json);
329
            JSONArray stats = (JSONArray) response.get("dtpstats");
330
            statsLoaded = CourseUnitDtpStat.fromJson(stats);
331
        }
332
        catch(1.5.0/docs/api/java/lang/Exception.html">Exception e)
333
        {
334
            logger.error(e,e);
335
            statsLoaded = new CourseUnitDtpStat[0];
336
        }
337
 
338
 
339
        for(CourseUnit cu :units)
340
        {
341
            CourseUnitDtpStat statFound = CourseReportUtils.findCourseUnitDtpStat(statsLoaded, (CourseUnitImpl) cu);
342
            if(statFound == null)
343
            {
344
                statFound = CourseReportUtils.createCourseUnitDtpStat(cu);
345
            }
346
 
347
            if(((CourseUnitImpl) cu).getSemestreAbsolutoS1S2().equals("S1"))
348
                semester1.getCourseUnitDtpStats().add(statFound);
349
            else
350
                semester2.getCourseUnitDtpStats().add(statFound);
351
        }
352
 
353
        return unitsDtpTable;
354
 
355
    }
356
 
357
    /**
1830 jmachado 358
     * Update course unit sections with reports, this method dows not change learning results table
359
     * values from learning results stays in unit but does not change learning results Table
360
     * @param courseCode
361
     * @param year
362
     * @param reportCourseDocument
363
     * @throws JSONException
364
     * @throws IOException
365
     * @return a list of CourseUnitSection
366
     */
1848 jmachado 367
    public List<DocumentSection> updateCleanCourseUnitSections(1.5.0/docs/api/java/lang/String.html">String courseCode, 1.5.0/docs/api/java/lang/String.html">String year, CourseReportDocument reportCourseDocument) throws JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException {
1841 jmachado 368
 
369
        List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
370
 
1848 jmachado 371
        CourseUnitsReportsSection unitReportsSection = (CourseUnitsReportsSection) reportCourseDocument.findDocumentSection(CourseUnitsReportsSection.class);
372
        CourseUnitSection[] courseUnitSections = null;
373
        try{
374
            1.5.0/docs/api/java/lang/String.html">String courseUnitSectionsJson = loadCourseEvaluationSections(courseCode,year);
375
            JSONObject object = new JSONObject(courseUnitSectionsJson);
376
            JSONArray evaluations = object.getJSONArray("evaluations");
377
            courseUnitSections = CourseUnitSection.fromJsonArray(evaluations.toString());
378
        }
379
        catch(1.5.0/docs/api/java/lang/Exception.html">Exception e)
380
        {
381
            logger.error(e,e);
382
            courseUnitSections = new CourseUnitSection[0];
383
        }
1830 jmachado 384
 
1848 jmachado 385
 
1927 grupo5 386
        ArrayList<DocumentSection> subSections = new ArrayList<DocumentSection>();
1848 jmachado 387
        unitReportsSection.setSections(subSections);
1830 jmachado 388
        for(CourseUnit cu :units)
389
        {
390
            CourseUnitSection sectionFound = CourseReportUtils.findCourseUnitSection(courseUnitSections, (CourseUnitImpl) cu);
391
            if(sectionFound == null)
392
            {
393
                sectionFound = CourseReportUtils.createCourseUnitEvaluationSection((CourseUnitImpl) cu);
394
            }
1841 jmachado 395
            if(sectionFound.getCourseUnitEvaluation() == null)
396
            {
397
                CourseUnitEvaluationImpl courseUnitEvaluation = DomainObjectFactory.createCourseUnitEvaluationImpl();
398
                courseUnitEvaluation.setAutoGeneratedCourseReport(true);
399
                DaoFactory.getCourseUnitEvaluationDaoImpl().save(courseUnitEvaluation);
400
                cu.setCourseUnitEvaluation(courseUnitEvaluation);
401
                sectionFound.setCourseUnitEvaluation(courseUnitEvaluation);
402
            }
1848 jmachado 403
            unitReportsSection.getSections().add(sectionFound);
1830 jmachado 404
        }
405
        return subSections;
406
    }
407
 
408
 
409
 
1887 grupo5 410
    /**
411
     * Este servico gera um grafico com a taxa global de aproveitamento e grava-o no repositorio digital
412
     * devolvendo o respectivo RepositoryFile4JsonView em json para poder ser anexado ao objecto imagem do
413
     * widget do grafico
414
     * @param reportDocumentJson
415
     * @param session
416
     * @return
417
     * @throws IOException
418
     */
419
    public 1.5.0/docs/api/java/lang/String.html">String generateGlobalLearningResultsChartImg(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
1830 jmachado 420
 
1887 grupo5 421
        CourseReportDocument reportDocument =  CourseReportDocument.fromJson(reportDocumentJson);
422
        LearningResultsSection learningResultsSection = (LearningResultsSection) reportDocument.findDocumentSection(LearningResultsSection.class);
423
        LearningGlobalAnalysisSection learningGlobalAnalysisSection = (LearningGlobalAnalysisSection) learningResultsSection.findSection(LearningGlobalAnalysisSection.class);
424
        GlobalLearningResultsChartImg chartImg = (GlobalLearningResultsChartImg) learningGlobalAnalysisSection.findDocComponent(GlobalLearningResultsChartImg.class);
1844 jmachado 425
 
1927 grupo5 426
 
1887 grupo5 427
        UnitsLearningResultsTable table = (UnitsLearningResultsTable) learningResultsSection.findDocComponent(UnitsLearningResultsTable.class);
1844 jmachado 428
 
1927 grupo5 429
 
1887 grupo5 430
        FileUploaded fileUploaded = chartImg.generateChart2tmp(table,reportDocument);
1844 jmachado 431
 
1887 grupo5 432
        RepositoryService repositoryService = new RepositoryService();
1844 jmachado 433
 
1887 grupo5 434
        boolean imageInitialized = chartImg.getImage() != null
435
                &&
436
                chartImg.getImage().getIdentifier() != null;
1844 jmachado 437
 
1887 grupo5 438
        RepositoryFile4JsonView view;
439
        if(imageInitialized)
440
        {
441
            1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.getImage().getIdentifier();
442
            view = repositoryService.replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.privateDomain, session);
443
        }
444
        else
445
        {
446
            view = repositoryService.storeRepositoryFileFromFileUpload(fileUploaded,ResourceAccessControlEnum.privateDomain,session);
447
        }
448
        chartImg.setImage(view);
449
        //TODO FALTA GUARDAR O JSON NO CURSO
450
        return view.toJson();
1830 jmachado 451
    }
452
 
1992 grupo5 453
    public 1.5.0/docs/api/java/lang/String.html">String generateGlobalLearningResultsChartYearImg(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
1830 jmachado 454
 
1992 grupo5 455
        CourseReportDocument reportDocument =  CourseReportDocument.fromJson(reportDocumentJson);
456
        LearningResultsSection learningResultsSection = (LearningResultsSection) reportDocument.findDocumentSection(LearningResultsSection.class);
457
        LearningGlobalAnalysisSection learningGlobalAnalysisSection = (LearningGlobalAnalysisSection) learningResultsSection.findSection(LearningGlobalAnalysisSection.class);
458
        GlobalLearningResultsChartYearImg chartImg = (GlobalLearningResultsChartYearImg) learningGlobalAnalysisSection.findDocComponent(GlobalLearningResultsChartYearImg.class);
1830 jmachado 459
 
460
 
1992 grupo5 461
        UnitsLearningResultsTable table = (UnitsLearningResultsTable) learningResultsSection.findDocComponent(UnitsLearningResultsTable.class);
1830 jmachado 462
 
463
 
1992 grupo5 464
        FileUploaded fileUploaded = chartImg.generateChart2tmp(table,reportDocument);
465
 
466
        RepositoryService repositoryService = new RepositoryService();
467
 
468
        boolean imageInitialized = chartImg.getImage() != null
469
                &&
470
                chartImg.getImage().getIdentifier() != null;
471
 
472
        RepositoryFile4JsonView view;
473
        if(imageInitialized)
474
        {
475
            1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.getImage().getIdentifier();
476
            view = repositoryService.replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.privateDomain, session);
477
        }
478
        else
479
        {
480
            view = repositoryService.storeRepositoryFileFromFileUpload(fileUploaded,ResourceAccessControlEnum.privateDomain,session);
481
        }
482
        chartImg.setImage(view);
483
        //TODO FALTA GUARDAR O JSON NO CURSO
484
        return view.toJson();
485
    }
486
 
1993 grupo5 487
    public 1.5.0/docs/api/java/lang/String.html">String generateLearningResultsChartSem(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
1992 grupo5 488
 
1993 grupo5 489
        CourseReportDocument reportDocument =  CourseReportDocument.fromJson(reportDocumentJson);
490
        LearningResultsSection learningResultsSection = (LearningResultsSection) reportDocument.findDocumentSection(LearningResultsSection.class);
1995 grupo5 491
        LearningAnalysisSection learningGlobalAnalysisSection = (LearningAnalysisSection) learningResultsSection.findSection(LearningAnalysisSection.class);
1993 grupo5 492
        LearningResultsChartSem chartImg = (LearningResultsChartSem) learningGlobalAnalysisSection.findDocComponent(LearningResultsChartSem.class);
1992 grupo5 493
 
494
 
1993 grupo5 495
        UnitsLearningResultsTable table = (UnitsLearningResultsTable) learningResultsSection.findDocComponent(UnitsLearningResultsTable.class);
496
 
497
        FileUploaded fileUploaded = chartImg.generateChart2tmp(table,reportDocument);
498
 
499
        RepositoryService repositoryService = new RepositoryService();
500
 
501
        boolean imageInitialized = chartImg.getImage() != null
502
                &&
503
                chartImg.getImage().getIdentifier() != null;
504
 
505
        RepositoryFile4JsonView view;
506
        if(imageInitialized)
507
        {
508
            1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.getImage().getIdentifier();
509
            view = repositoryService.replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.privateDomain, session);
510
        }
511
        else
512
        {
513
            view = repositoryService.storeRepositoryFileFromFileUpload(fileUploaded,ResourceAccessControlEnum.privateDomain,session);
514
        }
515
        chartImg.setImage(view);
516
        //TODO FALTA GUARDAR O JSON NO CURSO
517
        return view.toJson();
518
    }
519
 
520
 
521
 
1887 grupo5 522
    /****************************************************************************/
523
    /*
1830 jmachado 524
 
525
 
526
 
1887 grupo5 527
                                    SERVICOS WS-API
1830 jmachado 528
 
529
 
530
 
1887 grupo5 531
     */
1830 jmachado 532
    /****************************************************************************/
533
 
534
 
535
    /**
536
     * This service loads a list of course units given course code and year
537
     * with dtp stats codes pre-filled
538
     * @param courseCode
539
     * @param year
540
     * @return
541
     * @throws JSONException
542
     * @throws IOException
543
     */
544
    public 1.5.0/docs/api/java/lang/String.html">String loadCourseUnitDtpStats(1.5.0/docs/api/java/lang/String.html">String courseCode,1.5.0/docs/api/java/lang/String.html">String year) throws JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException {
545
 
546
 
547
        if(Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_DTP_STATS.indexOf("localhost")>=0)
548
        {
549
            JSONArray array = new JSONArray();
550
            List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
551
            for(CourseUnit cu: units)
552
            {
553
                CourseUnitDtpStat stat = CourseReportUtils.createCourseUnitDtpStat(cu);
554
                //sections.add(courseUnitSection);
555
                array.put(stat.toJsonObject());
556
            }
557
 
558
            JSONObject obj = new JSONObject();
559
            obj.put("dtpstats",array);
560
 
561
            return obj.toString();
562
        }
563
        else
564
        {
1848 jmachado 565
            1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_DTP_STATS + "?code=" + courseCode  + "&year=" + year;
566
            1.5.0/docs/api/java/lang/String.html">String json = "{ dtpstats : [] }";
567
            try{
568
                1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl);
1830 jmachado 569
 
1848 jmachado 570
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
571
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
572
 
573
                json = StreamsUtils.readString(is);
574
                is.close();
575
            }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
576
            {
577
                logger.error("Connecting " + serviceUrl,e);
578
                return json;
579
            }
1830 jmachado 580
            JSONObject jsonObject = new JSONObject(json);
1887 grupo5 581
            if(jsonObject.get("service").equals("ok"))
582
                return jsonObject.get("response").toString();
583
            else
584
                return json;
1830 jmachado 585
        }
586
    }
587
 
1992 grupo5 588
 
1974 grupo5 589
    public 1.5.0/docs/api/java/lang/String.html">String saveCourseReportDocument (1.5.0/docs/api/java/lang/String.html">String reportDocumentJson, UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
1927 grupo5 590
    {
1992 grupo5 591
        CourseReportDocument courseReportDocument = 5+0%2Fdocs%2Fapi+Document">Document.fromJson(reportDocumentJson);
592
        //CourseReportDocument courseReportDocument = CourseReportDocument.fromJson(reportDocumentJson);
1997 grupo5 593
 
1927 grupo5 594
        Course course = DaoFactory.getCourseDaoImpl().findCourseByCode(courseReportDocument.getCourseCode());
595
        List<CourseYear> courseYear = DaoFactory.getCourseYearDaoImpl().findCourseYear(courseReportDocument.getCourseCode(), courseReportDocument.getYear());
1830 jmachado 596
 
1927 grupo5 597
        if(courseYear.isEmpty())
598
        {
599
            courseYear.add(DomainObjectFactory.createCourseYearImpl());
600
            courseYear.get(0).setCourse(course);
601
            course.getCourseYears().add(courseYear.get(0));
602
            courseYear.get(0).setImportYear(courseReportDocument.getYear());
603
            DaoFactory.getCourseYearDaoImpl().save(courseYear.get(0));
604
        }
1830 jmachado 605
 
1927 grupo5 606
        courseYear.get(0).setCourseReportDocument(reportDocumentJson);
607
 
608
        return courseReportDocument.toJson();
609
    }
610
 
1992 grupo5 611
    /**
612
     *
613
     * @param courseCode
614
     * @param year
615
     * @param session
616
     * @return
617
     * @throws IOException
618
     * @throws JSONException
619
     */
620
    public 1.5.0/docs/api/java/lang/String.html">String loadCourseReportDocument(1.5.0/docs/api/java/lang/String.html">String courseCode,1.5.0/docs/api/java/lang/String.html">String year,UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException, JSONException
1935 grupo5 621
    {
622
 
623
        List<CourseYear> courseYear = DaoFactory.getCourseYearDaoImpl().findCourseYear(courseCode, year);
1992 grupo5 624
        1.5.0/docs/api/java/lang/String.html">String courseReportJson = null;
1935 grupo5 625
 
1992 grupo5 626
        if(courseYear!= null && !courseYear.isEmpty())
1935 grupo5 627
        {
1992 grupo5 628
            courseReportJson = courseYear.get(0).getCourseReportDocument();
629
        }
630
        else
631
        {
1935 grupo5 632
            try {
1992 grupo5 633
                CourseReportDocument courseReport = createNewCourseReportDocument(courseCode, year);
634
                courseReportJson = courseReport.toJson();
635
                saveCourseReportDocument(courseReportJson, session);
1935 grupo5 636
            } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
637
                1.5.0/docs/api/java/lang/System.html">System.out.println(e);
638
                e.printStackTrace();
639
            }
640
        }
1992 grupo5 641
        return courseReportJson;
1935 grupo5 642
    }
1830 jmachado 643
    /**
644
     *
1927 grupo5 645
     * Para um determinado curso e ano o serviço faz uma listagem de todas as suas unidades curriculares
646
     * e lista a sua informação básica juntamente com o relatório de avaliação disponivel
647
     * O serviço adiciona ainda o Ano de cada unidade por inspeção do Plano de Estudos
648
     * caso a unidade não seja encontrada no Plano de estudos o ano irá ser preenchido com -1
1830 jmachado 649
     *
650
     * @param courseCode codigo Siges na base de dados
651
     * @param year  201617, 201718
652
     * @return String JSONObject with a JSON ARRAY of List<CourseUnitSection>
653
     */
654
    public 1.5.0/docs/api/java/lang/String.html">String loadCourseEvaluationSections(1.5.0/docs/api/java/lang/String.html">String courseCode,1.5.0/docs/api/java/lang/String.html">String year) throws JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException {
655
 
656
 
1848 jmachado 657
        if(Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT.indexOf("localhost")>=0)
1830 jmachado 658
        {
659
            JSONArray array = new JSONArray();
660
            List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
661
            for(CourseUnit cu: units)
662
            {
663
                CourseUnitSection courseUnitSection = CourseReportUtils.createCourseUnitEvaluationSection((CourseUnitImpl) cu);
1887 grupo5 664
                if(courseUnitSection.getAnoPlano() < 0)
665
                {
666
                    logger.info("Ano do Plano not available from courseUnitsEvaluation Service, will read from API loadPlanYearForCourseUnitCode");
667
                    try{
668
                        1.5.0/docs/api/java/lang/String.html">String json = loadPlanYearForCourseUnitCode(courseCode,cu.getCode(),cu.getSemestre());
669
                        int ano = new JSONObject(json).getInt("year");
670
                        courseUnitSection.setAnoPlano(ano);
671
                    }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e )
672
                    {
673
                        logger.error("Nao conseguiu obter o ano do plano da API: " + e.toString(),e);
674
                    }
675
                }
1830 jmachado 676
                array.put(courseUnitSection.toJsonObject());
677
            }
678
 
679
            JSONObject obj = new JSONObject();
680
            obj.put("evaluations",array);
681
 
682
            return obj.toString();
683
        }
684
        else
685
        {
1848 jmachado 686
            1.5.0/docs/api/java/lang/String.html">String json = "{ evaluations : [] }";
687
            1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT + "?code=" + courseCode  + "&year=" + year;
688
            try{
689
                1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl);
1830 jmachado 690
 
1848 jmachado 691
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
692
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
693
 
694
                json = StreamsUtils.readString(is);
695
                is.close();
696
            }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
697
            {
698
                logger.error("Connecting " + serviceUrl,e);
699
                return json;
700
            }
701
 
1830 jmachado 702
            JSONObject jsonObject = new JSONObject(json);
1887 grupo5 703
            if(jsonObject.get("service").equals("ok"))
704
                return jsonObject.get("response").toString();
705
            else
706
                return json;
1830 jmachado 707
        }
708
    }
709
 
710
 
1887 grupo5 711
    /**
712
     *
713
     *
714
     * @param courseCode codigo Siges na base de dados
715
     * @param unitCode
716
     * @return Json com o ano do plano exemplo: { year : 1 }
1927 grupo5 717
     * ou -1 se não for encontrado
1887 grupo5 718
     */
719
    public 1.5.0/docs/api/java/lang/String.html">String loadPlanYearForCourseUnitCode(1.5.0/docs/api/java/lang/String.html">String courseCode,1.5.0/docs/api/java/lang/String.html">String unitCode,1.5.0/docs/api/java/lang/String.html">String period) throws JSONException, 1.5.0/docs/api/java/io/IOException.html">IOException {
720
 
721
 
722
        if(Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNIT_PLAN_YEAR.indexOf("localhost")>=0)
723
        {
724
            CourseImpl c = DaoFactory.getCourseDaoImpl().findCourseByCode(courseCode);
725
            int year = c.getUnidadeAnoPlano(period,unitCode);
726
            return "{ year : " + year + " }";
727
 
728
        }
729
        else
730
        {
731
            1.5.0/docs/api/java/lang/String.html">String json = "{ year : -1 }";
732
            1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNIT_PLAN_YEAR + "?courseCode=" + courseCode  + "&unitCode=" + unitCode + "&period=" + period;
733
            try{
734
                1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl);
735
 
736
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
737
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
738
 
739
                json = StreamsUtils.readString(is);
740
                is.close();
741
            }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
742
            {
743
                logger.error("Connecting " + serviceUrl,e);
744
                return json;
745
            }
746
 
747
            JSONObject jsonObject = new JSONObject(json);
748
            if(jsonObject.get("service").equals("ok"))
749
                return jsonObject.get("response").toString();
750
            else
751
                return json;
752
        }
753
    }
754
 
755
 
756
 
757
 
758
 
759
 
760
 
761
 
762
 
763
 
764
 
765
 
766
 
767
    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 {
768
        AbstractDao.getCurrentSession().beginTransaction();
769
 
770
        CourseReportDocument reportCourseDocument = new CourseReportServices().createNewCourseReportDocument("44","201617");
771
        1.5.0/docs/api/java/lang/System.html">System.out.println(reportCourseDocument.toJson());
772
        AbstractDao.getCurrentSession().getTransaction().commit();
773
 
774
        //System.setProperty("javax.net.ssl.trustStore", "/JORGE/COPIAS/.keystore");
775
        //System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
776
 
777
        /*URL url = new URL("http://pae.ipportalegre.pt/wsjson/api/app/ws-course-pedagogic-results-list?code=44&year=201617&period=S1");
778
 
779
 
780
 
781
        System.out.println(StreamsUtils.readString(url.openStream()));*/
782
    }
783
 
784
    /*
785
 
786
    public String loadUnitsAndCreateLearningResultsTables4Course(String courseCode, String year) throws IOException, JSONException
787
    {
788
 
789
    }
790
    */
791
    //TODO loadUnitsAndCreateLearningResultsTables4Course
792
    //HIPOTESE DEVOLVER DOIS OBJECTOS
793
    //SERVICO DE ARRANQUE
794
    //DEVOLVE UM REPORT DOCUMENT E O CHAMADOR USA O QUE QUISER
795
    //A GERACAO DE GRAFICOS FAZ-SE APENAS A PEDIDO
796
 
797
    // SE ELE PEDIR PARA ATUALIZAR TUDO CARREGA-SE UNIDADES E TABELAS NU DOC NOVO
798
    // E NO BROWSER SUBSTITUI-SE ESSES ELEMENTOS NOS ANTIGOS a seccao das unidades
799
    // e as as tabelas
800
 
1927 grupo5 801
}