Subversion Repositories bacoAlunos

Rev

Rev 1906 | Rev 1919 | 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);
1912 grupo6 411
        chartImg.setWidth(500);
412
        float relative = 500 / GlobalLearningResultsChartImg.WIDTH;
413
        float height = relative * GlobalLearningResultsChartImg.HEIGHT;
414
        chartImg.setHeight((int) height);
1873 grupo7 415
        //TODO FALTA GUARDAR O JSON NO CURSO
1912 grupo6 416
        return chartImg.toJson();
1830 jmachado 417
    }
418
 
1906 grupo6 419
 
420
    public 1.5.0/docs/api/java/lang/String.html">String generateGlobalLearningResultsChartYearImg(1.5.0/docs/api/java/lang/String.html">String reportDocumentJson,
421
                                                        UserSession session) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
422
 
423
        CourseReportDocument reportDocument = CourseReportDocument.fromJson(reportDocumentJson);
424
        LearningResultsSection learningResultsSection = (LearningResultsSection) reportDocument.findDocumentSection(LearningResultsSection.class);
425
        LearningGlobalAnalysisSection learningGlobalAnalysisSection = (LearningGlobalAnalysisSection) learningResultsSection.findSection(LearningGlobalAnalysisSection.class);
426
        GlobalLearningResultsChartYearImg chartImg = (GlobalLearningResultsChartYearImg) learningGlobalAnalysisSection.findDocComponent(GlobalLearningResultsChartYearImg.class);
427
 
428
 
429
        UnitsLearningResultsTable table = (UnitsLearningResultsTable) learningResultsSection.findDocComponent(UnitsLearningResultsTable.class);
430
 
431
 
432
        FileUploaded fileUploaded = chartImg.generateChart2tmp(table, reportDocument);
433
 
434
        RepositoryService repositoryService = new RepositoryService();
435
 
436
        boolean imageInitialized = chartImg.getImage() != null
437
                &&
438
                chartImg.getImage().getIdentifier() != null;
439
 
440
        RepositoryFile4JsonView view;
441
        if (imageInitialized) {
442
            1.5.0/docs/api/java/lang/String.html">String identifier = chartImg.getImage().getIdentifier();
443
            view = repositoryService.replaceRepositoryFileFromFileUpload(identifier, fileUploaded, ResourceAccessControlEnum.privateDomain, session);
444
        } else {
445
            view = repositoryService.storeRepositoryFileFromFileUpload(fileUploaded, ResourceAccessControlEnum.privateDomain, session);
446
        }
447
        chartImg.setImage(view);
1912 grupo6 448
 
449
        chartImg.setWidth(500);
450
        float relative = 500 / GlobalLearningResultsChartYearImg.WIDTH;
451
        float height = relative * GlobalLearningResultsChartYearImg.HEIGHT;
452
        chartImg.setHeight((int) height);
1906 grupo6 453
        //TODO FALTA GUARDAR O JSON NO CURSO
1912 grupo6 454
        return chartImg.toJson();
1906 grupo6 455
    }
456
 
1905 grupo7 457
    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 458
 
1905 grupo7 459
        CourseReportDocument reportDocument = CourseReportDocument.fromJson(reportDocumentJson);
1830 jmachado 460
 
1905 grupo7 461
        Course c = DaoFactory.getCourseDaoImpl().findCourseByCode(reportDocument.getCourseCode());
462
        CourseYear y = null;
463
        for (CourseYear courseYear : c.getCourseYears()) {
464
            if (courseYear.getImportYear().equals(reportDocument.getYear())) {
465
                y = courseYear;
466
                break;
467
            }
468
        }
1830 jmachado 469
 
1905 grupo7 470
        if (y == null) {
471
            y = DomainObjectFactory.createCourseYearImpl();
472
            DaoFactory.getCourseYearDaoImpl().save(y);
473
            y.setImportYear(reportDocument.getYear());
474
            c.getCourseYears().add(y);
475
            y.setCourse(c);
476
        }
1830 jmachado 477
 
1905 grupo7 478
        y.setCourseReport(reportDocumentJson);
1830 jmachado 479
 
1905 grupo7 480
        return reportDocument.toJson();
481
    }
482
 
483
 
1873 grupo7 484
    /****************************************************************************/
485
    /*
1830 jmachado 486
 
487
 
488
 
1873 grupo7 489
                                    SERVICOS WS-API
1830 jmachado 490
 
491
 
492
 
1873 grupo7 493
     */
1830 jmachado 494
    /****************************************************************************/
495
 
496
 
497
    /**
498
     * This service loads a list of course units given course code and year
499
     * with dtp stats codes pre-filled
1905 grupo7 500
     *
1830 jmachado 501
     * @param courseCode
502
     * @param year
503
     * @return
504
     * @throws JSONException
505
     * @throws IOException
506
     */
1905 grupo7 507
    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 508
 
509
 
1905 grupo7 510
        if (Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_DTP_STATS.indexOf("localhost") >= 0) {
1830 jmachado 511
            JSONArray array = new JSONArray();
512
            List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
1905 grupo7 513
            for (CourseUnit cu : units) {
1830 jmachado 514
                CourseUnitDtpStat stat = CourseReportUtils.createCourseUnitDtpStat(cu);
515
                //sections.add(courseUnitSection);
516
                array.put(stat.toJsonObject());
517
            }
518
 
519
            JSONObject obj = new JSONObject();
1905 grupo7 520
            obj.put("dtpstats", array);
1830 jmachado 521
 
522
            return obj.toString();
1905 grupo7 523
        } else {
524
            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 525
            1.5.0/docs/api/java/lang/String.html">String json = "{ dtpstats : [] }";
1905 grupo7 526
            try {
1848 jmachado 527
                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 528
 
1848 jmachado 529
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
530
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
531
 
532
                json = StreamsUtils.readString(is);
533
                is.close();
1905 grupo7 534
            } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
535
                logger.error("Connecting " + serviceUrl, e);
1848 jmachado 536
                return json;
537
            }
1830 jmachado 538
            JSONObject jsonObject = new JSONObject(json);
1905 grupo7 539
            if (jsonObject.get("service").equals("ok"))
1873 grupo7 540
                return jsonObject.get("response").toString();
541
            else
542
                return json;
1830 jmachado 543
        }
544
    }
545
 
546
 
547
    /**
548
     * Para um determinado curso e ano o serviço faz uma listagem de todas as suas unidades curriculares
549
     * e lista a sua informação básica juntamente com o relatório de avaliação disponivel
550
     * O serviço adiciona ainda o Ano de cada unidade por inspeção do Plano de Estudos
551
     * caso a unidade não seja encontrada no Plano de estudos o ano irá ser preenchido com -1
552
     *
553
     * @param courseCode codigo Siges na base de dados
1905 grupo7 554
     * @param year       201617, 201718
1830 jmachado 555
     * @return String JSONObject with a JSON ARRAY of List<CourseUnitSection>
556
     */
1905 grupo7 557
    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 558
 
559
 
1905 grupo7 560
        if (Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT.indexOf("localhost") >= 0) {
1830 jmachado 561
            JSONArray array = new JSONArray();
562
            List<CourseUnit> units = DaoFactory.getCourseUnitDaoImpl().loadByCourseSiges(courseCode, year);
1905 grupo7 563
            for (CourseUnit cu : units) {
1830 jmachado 564
                CourseUnitSection courseUnitSection = CourseReportUtils.createCourseUnitEvaluationSection((CourseUnitImpl) cu);
1905 grupo7 565
                if (courseUnitSection.getAnoPlano() < 0) {
1873 grupo7 566
                    logger.info("Ano do Plano not available from courseUnitsEvaluation Service, will read from API loadPlanYearForCourseUnitCode");
1905 grupo7 567
                    try {
568
                        1.5.0/docs/api/java/lang/String.html">String json = loadPlanYearForCourseUnitCode(courseCode, cu.getCode(), cu.getSemestre());
1873 grupo7 569
                        int ano = new JSONObject(json).getInt("year");
570
                        courseUnitSection.setAnoPlano(ano);
1905 grupo7 571
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
572
                        logger.error("Nao conseguiu obter o ano do plano da API: " + e.toString(), e);
1873 grupo7 573
                    }
574
                }
1830 jmachado 575
                array.put(courseUnitSection.toJsonObject());
576
            }
577
 
578
            JSONObject obj = new JSONObject();
1905 grupo7 579
            obj.put("evaluations", array);
1830 jmachado 580
 
581
            return obj.toString();
1905 grupo7 582
        } else {
1848 jmachado 583
            1.5.0/docs/api/java/lang/String.html">String json = "{ evaluations : [] }";
1905 grupo7 584
            1.5.0/docs/api/java/lang/String.html">String serviceUrl = Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNITS_EVALUATION_REPORT + "?code=" + courseCode + "&year=" + year;
585
            try {
1848 jmachado 586
                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 587
 
1848 jmachado 588
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
589
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
590
 
591
                json = StreamsUtils.readString(is);
592
                is.close();
1905 grupo7 593
            } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
594
                logger.error("Connecting " + serviceUrl, e);
1848 jmachado 595
                return json;
596
            }
597
 
1830 jmachado 598
            JSONObject jsonObject = new JSONObject(json);
1905 grupo7 599
            if (jsonObject.get("service").equals("ok"))
1873 grupo7 600
                return jsonObject.get("response").toString();
601
            else
602
                return json;
1830 jmachado 603
        }
604
    }
605
 
606
 
1873 grupo7 607
    /**
608
     * @param courseCode codigo Siges na base de dados
609
     * @param unitCode
610
     * @return Json com o ano do plano exemplo: { year : 1 }
611
     * ou -1 se não for encontrado
612
     */
1905 grupo7 613
    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 614
 
615
 
1905 grupo7 616
        if (Globals.SYSTEM_WSJSON_SERVICE_COURSE_UNIT_PLAN_YEAR.indexOf("localhost") >= 0) {
1873 grupo7 617
            CourseImpl c = DaoFactory.getCourseDaoImpl().findCourseByCode(courseCode);
1905 grupo7 618
            int year = c.getUnidadeAnoPlano(period, unitCode);
1873 grupo7 619
            return "{ year : " + year + " }";
620
 
1905 grupo7 621
        } else {
1873 grupo7 622
            1.5.0/docs/api/java/lang/String.html">String json = "{ year : -1 }";
1905 grupo7 623
            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;
624
            try {
1873 grupo7 625
                1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(serviceUrl);
626
 
627
                1.5.0/docs/api/java/net/URLConnection.html">URLConnection conn = url.openConnection();
628
                5+0%2Fdocs%2Fapi+InputStream">InputStream is = conn.getInputStream();
629
 
630
                json = StreamsUtils.readString(is);
631
                is.close();
1905 grupo7 632
            } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
633
                logger.error("Connecting " + serviceUrl, e);
1873 grupo7 634
                return json;
635
            }
636
 
637
            JSONObject jsonObject = new JSONObject(json);
1905 grupo7 638
            if (jsonObject.get("service").equals("ok"))
1873 grupo7 639
                return jsonObject.get("response").toString();
640
            else
641
                return json;
642
        }
643
    }
644
 
645
 
646
    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 {
647
        AbstractDao.getCurrentSession().beginTransaction();
648
 
1905 grupo7 649
        CourseReportDocument reportCourseDocument = new CourseReportServices().createNewCourseReportDocument("44", "201617");
1873 grupo7 650
        1.5.0/docs/api/java/lang/System.html">System.out.println(reportCourseDocument.toJson());
651
        AbstractDao.getCurrentSession().getTransaction().commit();
652
 
653
        //System.setProperty("javax.net.ssl.trustStore", "/JORGE/COPIAS/.keystore");
654
        //System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
655
 
656
        /*URL url = new URL("http://pae.ipportalegre.pt/wsjson/api/app/ws-course-pedagogic-results-list?code=44&year=201617&period=S1");
657
 
658
 
659
 
660
        System.out.println(StreamsUtils.readString(url.openStream()));*/
661
    }
662
 
663
    /*
664
 
665
    public String loadUnitsAndCreateLearningResultsTables4Course(String courseCode, String year) throws IOException, JSONException
666
    {
667
 
668
    }
669
    */
670
    //TODO loadUnitsAndCreateLearningResultsTables4Course
671
    //HIPOTESE DEVOLVER DOIS OBJECTOS
672
    //SERVICO DE ARRANQUE
673
    //DEVOLVE UM REPORT DOCUMENT E O CHAMADOR USA O QUE QUISER
674
    //A GERACAO DE GRAFICOS FAZ-SE APENAS A PEDIDO
675
 
676
    // SE ELE PEDIR PARA ATUALIZAR TUDO CARREGA-SE UNIDADES E TABELAS NU DOC NOVO
677
    // E NO BROWSER SUBSTITUI-SE ESSES ELEMENTOS NOS ANTIGOS a seccao das unidades
678
    // e as as tabelas
679
 
680
 
1814 jmachado 681
}