Subversion Repositories bacoAlunos

Rev

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