Subversion Repositories bacoAlunos

Rev

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

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