Subversion Repositories bacoAlunos

Rev

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