Subversion Repositories bacoAlunos

Rev

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