Subversion Repositories bacoAlunos

Rev

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